From a18cda0fc234663d5d08679e405ed476c30c76cc Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 13 Jul 2026 10:45:45 +0530 Subject: [PATCH 01/17] chore: update Flutter SDK to 25.3.0 --- CHANGELOG.md | 8 + README.md | 2 +- example/README.md | 2 +- lib/appwrite.dart | 2 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/operator.dart | 11 +- lib/query.dart | 101 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1560 +++++----- lib/services/avatars.dart | 351 +-- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/presences.dart | 182 +- lib/services/storage.dart | 342 +-- lib/services/tables_db.dart | 547 ++-- lib/services/teams.dart | 421 ++- lib/src/client.dart | 9 +- lib/src/client_base.dart | 10 +- lib/src/client_browser.dart | 24 +- lib/src/client_io.dart | 24 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 97 +- lib/src/enums/timezone.dart | 848 +++--- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 194 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 176 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +-- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- pubspec.yaml | 2 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 + test/services/account_test.dart | 2691 +++++++++-------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 585 ++-- test/services/functions_test.dart | 188 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 253 +- test/services/messaging_test.dart | 122 +- test/services/presences_test.dart | 202 +- test/services/storage_test.dart | 341 ++- test/services/tables_db_test.dart | 585 ++-- test/services/teams_test.dart | 555 ++-- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 7 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 30 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 + test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 170 files changed, 8775 insertions(+), 8520 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3ee6d03..f492c6b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Change Log +## 25.3.0 + +* Added: `Client.setBearer()` method for OAuth access token authentication +* Added: `Query.vectorDot`, `Query.vectorCosine`, `Query.vectorEuclidean` vector similarity query methods +* Added: `appwrite` value to `OAuthProvider` enum +* Added: `Locale` model fields: `city`, `timeZone`, `postalCode`, `latitude`, `longitude`, ISP and connection details +* Updated: `Log` model docs now include `hidden` user type + ## 25.2.0 * Added: Realtime connections now authenticate with the configured JWT. diff --git a/README.md b/README.md index a4cf00a8..804fca53 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^25.2.0 + appwrite: ^25.3.0 ``` You can install packages from the command line: diff --git a/example/README.md b/example/README.md index d0cb0c2b..36537cbf 100644 --- a/example/README.md +++ b/example/README.md @@ -6,7 +6,7 @@ Init your Appwrite client: Client client = Client(); client - .setEndpoint('https://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('https://localhost:9521/v1') // Your Appwrite Endpoint .setProject('5e8cf4f46b5e8') // Your project ID .setSelfSigned() // Remove in production ; diff --git a/lib/appwrite.dart b/lib/appwrite.dart index ae51be5e..6615de8a 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/channel.dart b/lib/channel.dart index afc68efa..d511f5a4 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,33 +2,19 @@ part of appwrite; // Marker classes for type safety class _Root {} - class _Database {} - class _Collection {} - class _Document {} - class _TablesDB {} - class _Table {} - class _Row {} - class _Bucket {} - class _File {} - class _Func {} - class _Execution {} - class _Team {} - class _Membership {} - class _Presence {} - class _Resolved {} // Helper function for normalizing ID @@ -113,15 +99,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => - _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => _next<_Table>('tables', id); + Channel<_Table> table(String id) => + _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/operator.dart b/lib/operator.dart index 337dda30..9dd7f4c7 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if (values != null) { + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -147,7 +147,8 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => Operator._('arrayUnique', []).toString(); + static String arrayUnique() => + Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -172,7 +173,8 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => Operator._('toggle', []).toString(); + static String toggle() => + Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -183,5 +185,6 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => Operator._('dateSetNow', []).toString(); + static String dateSetNow() => + Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 3693dce6..2221a6e6 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if (attribute != null) { + + if(attribute != null) { result['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,46 +140,50 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => lessThan('\$createdAt', value); + static String createdBefore(String value) => + lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => greaterThan('\$createdAt', value); + static String createdAfter(String value) => + greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => lessThan('\$updatedAt', value); + static String updatedBefore(String value) => + lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => + greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -194,17 +198,18 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => Query._('orderRandom').toString(); + static String orderRandom() => + Query._('orderRandom').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(); /// 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) => @@ -214,43 +219,39 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceNotEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceLessThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); + + /// Filter resources using vector dot product similarity. + static String vectorDot(String attribute, List vector) => + Query._('vectorDot', attribute, [vector]).toString(); + + /// Filter resources using vector cosine similarity. + static String vectorCosine(String attribute, List vector) => + Query._('vectorCosine', attribute, [vector]).toString(); + + /// Filter resources using vector Euclidean distance. + static String vectorEuclidean(String attribute, List vector) => + Query._('vectorEuclidean', attribute, [vector]).toString(); /// Filter resources where [attribute] intersects with the given geometry. static String intersects(String attribute, List values) => 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..3f91a53a 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 48b60041..9c021e93 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; -/// The Account service allows you to authenticate and manage a user account. + /// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,17 +9,18 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -29,30 +30,29 @@ class Account extends Service { /// 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 { + Future create({required String userId, required String email, required String password, String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - if (name != null) 'name': name, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + 'password': password, + + if (name != null) 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Update currently logged in user account email address. After changing user @@ -62,65 +62,66 @@ class Account extends Service { /// 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 { + /// + Future updateEmail({required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities( - {List? queries, bool? total}) async { + Future listIdentities({List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); - return models.IdentityList.fromMap(res.data); } /// Delete an identity by its unique ID. Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -131,20 +132,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, - }; + final Map apiParams = { + if (duration != null) 'duration': duration, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); - return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -152,224 +153,212 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.LogList.fromMap(res.data); - return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - }; + final Map apiParams = { + 'mfa': mfa, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// 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); + Future createMFAAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } /// 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); + 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 apiParams = { - 'otp': otp, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// 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 String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -377,27 +366,26 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, + + 'otp': otp, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -405,83 +393,84 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge( - {required String challengeId, required String otp}) async { + Future updateMFAChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'otp': otp, - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -491,17 +480,18 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -509,23 +499,22 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -536,41 +525,40 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -580,62 +568,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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 { + Future updatePassword({required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, - if (oldPassword != null) 'oldPassword': oldPassword, - }; + final Map apiParams = { + 'password': password, + + if (oldPassword != null) 'oldPassword': oldPassword, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -643,42 +631,43 @@ class Account extends Service { /// 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 { + Future updatePhone({required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, - 'password': password, - }; + final Map apiParams = { + 'phone': phone, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'password': password, - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -687,20 +676,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, - }; + final Map apiParams = { + 'prefs': prefs, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -711,25 +700,25 @@ class Account extends Service { /// /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 { + Future createRecovery({required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - 'url': url, - }; + final Map apiParams = { + 'email': email, + + 'url': url, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -737,33 +726,32 @@ class Account extends Service { /// 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 { + Future updateRecovery({required String userId, required String secret, required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + 'password': password, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -771,17 +759,18 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.SessionList.fromMap(res.data); - return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -789,17 +778,18 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -812,216 +802,213 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession({required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + /// + 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 = { + + if (success != null) 'success': success, + + if (failure != null) 'failure': failure, + + if (scopes != null) '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); + } + } 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); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1030,20 +1017,20 @@ class Account extends Service { /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1052,18 +1039,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1071,28 +1058,27 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - if (providerId != null) 'providerId': providerId, - }; + final Map apiParams = { + 'targetId': targetId, + + 'identifier': identifier, + + if (providerId != null) 'providerId': providerId, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1100,45 +1086,43 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + 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 apiParams = { - 'identifier': identifier, - }; + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1150,31 +1134,32 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken({required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'email': email, - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + if (phrase != null) 'phrase': phrase, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1186,88 +1171,87 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (url != null) 'url': url, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + if (url != null) 'url': url, + + if (phrase != null) 'phrase': phrase, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + 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 = { + + if (success != null) 'success': success, + + if (failure != null) 'failure': failure, + + if (scopes != null) '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); + } + } 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); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1276,29 +1260,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken({required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; + final Map apiParams = { + 'userId': userId, + + 'phone': phone, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1310,29 +1294,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1344,83 +1328,81 @@ class Account extends Service { /// 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. - /// - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 updateEmailVerification( - {required String userId, required String secret}) async { + Future updateEmailVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1434,42 +1416,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } } diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index cdd93e6e..4dca3b16 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Avatars service aims to help you complete everyday tasks related to -/// your app image, icons, and avatars. + /// 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); @@ -11,134 +11,139 @@ class Avatars extends Service { /// /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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { final String apiPath = '/avatars/favicon'; - final Map params = { - 'url': url, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; + final Map params = { + + 'url': url, - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + Future getImage({required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map params = { - 'url': url, - if (width != null) 'width': width, - if (height != null) 'height': height, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'url': url, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to show your user initials avatar icon on your website or @@ -146,117 +151,125 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map params = { - if (name != null) 'name': name, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (background != null) 'background': background, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + if (name != null) 'name': name, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (background != null) 'background': background, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map params = { - 'text': text, - if (size != null) 'size': size, - if (margin != null) 'margin': margin, - if (download != null) 'download': download, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'text': text, + + if (size != null) 'size': size, + + if (margin != null) 'margin': margin, + + if (download != null) 'download': download, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot( - {required String url, - Map? headers, - int? viewportWidth, - int? viewportHeight, - double? scale, - enums.BrowserTheme? theme, - String? userAgent, - bool? fullpage, - String? locale, - enums.Timezone? timezone, - double? latitude, - double? longitude, - double? accuracy, - bool? touch, - List? permissions, - int? sleep, - int? width, - int? height, - int? quality, - enums.ImageFormat? output}) async { + Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map params = { - 'url': url, - if (headers != null) 'headers': headers, - if (viewportWidth != null) 'viewportWidth': viewportWidth, - if (viewportHeight != null) 'viewportHeight': viewportHeight, - if (scale != null) 'scale': scale, - if (theme != null) 'theme': theme.value, - if (userAgent != null) 'userAgent': userAgent, - if (fullpage != null) 'fullpage': fullpage, - if (locale != null) 'locale': locale, - if (timezone != null) 'timezone': timezone.value, - if (latitude != null) 'latitude': latitude, - if (longitude != null) 'longitude': longitude, - if (accuracy != null) 'accuracy': accuracy, - if (touch != null) 'touch': touch, - if (permissions != null) - 'permissions': permissions.map((e) => e.value).toList(), - if (sleep != null) 'sleep': sleep, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - if (output != null) 'output': output.value, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'url': url, + + if (headers != null) 'headers': headers, + + if (viewportWidth != null) 'viewportWidth': viewportWidth, + + if (viewportHeight != null) 'viewportHeight': viewportHeight, + + if (scale != null) 'scale': scale, + + if (theme != null) 'theme': theme.value, + + if (userAgent != null) 'userAgent': userAgent, + + if (fullpage != null) 'fullpage': fullpage, + + if (locale != null) 'locale': locale, + + if (timezone != null) 'timezone': timezone.value, + + if (latitude != null) 'latitude': latitude, + + if (longitude != null) 'longitude': longitude, + + if (accuracy != null) 'accuracy': accuracy, + + if (touch != null) 'touch': touch, + + if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), + + if (sleep != null) 'sleep': sleep, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + if (output != null) 'output': output.value, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + 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 0ff3fb72..0bfd935a 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,418 +1,339 @@ part of '../appwrite.dart'; -/// The Databases service allows you to create structured collections of -/// documents, query and filter lists of documents + /// 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 transactions across all databases. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions( - {List? queries}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions({List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction({required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + + 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Create or update a 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Delete a document by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + 'min': min, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Increment a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + 'max': max, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index ed97921b..0640f80f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,87 +1,82 @@ part of '../appwrite.dart'; -/// The Functions Service allows you view, create and manage your Cloud -/// Functions. + /// The Functions Service allows you view, create and manage your Cloud + /// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); + Future listExecutions({required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); - return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - if (xasync != null) 'async': xasync, - if (path != null) 'path': path, - if (method != null) 'method': method.value, - if (headers != null) 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); + 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 = { + if (body != null) 'body': body, + + if (xasync != null) 'async': xasync, + + if (path != null) 'path': path, + + if (method != null) 'method': method.value, + + if (headers != null) 'headers': headers, + + 'scheduledAt': scheduledAt, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Execution.fromMap(res.data); - return models.Execution.fromMap(res.data); } } diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index c86f3719..978331fa 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The GraphQL API allows you to query and mutate your Appwrite server using -/// GraphQL. + /// 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); @@ -10,41 +10,39 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 87ea162e..c45a1269 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Locale service allows you to customize your app based on your users' -/// location. + /// 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); @@ -10,22 +10,23 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all locale codes in [ISO @@ -33,17 +34,18 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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 of all continents. You can use the locale header to get the data in a @@ -51,17 +53,18 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.ContinentList.fromMap(res.data); - return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -69,17 +72,18 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries that are currently members of the EU. You can use the @@ -87,17 +91,18 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries phone codes. You can use the locale header to get the @@ -105,17 +110,18 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -124,17 +130,18 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -142,16 +149,17 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.LanguageList.fromMap(res.data); - return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 61ecefee..3dffe41b 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,54 +1,48 @@ part of '../appwrite.dart'; -/// The Messaging service allows you to send messages to any provider type -/// (SMTP, push notification, SMS, etc.). + /// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 1c9b651b..088700cb 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -5,127 +5,123 @@ class Presences extends Service { Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list( - {List? queries, bool? total, int? ttl}) async { + /// + Future list({List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.PresenceList.fromMap(res.data); - return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Presence.fromMap(res.data); - return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert( - {required String presenceId, - required String status, - List? permissions, - String? expiresAt, - Map? metadata}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - if (permissions != null) 'permissions': permissions, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + + if (permissions != null) 'permissions': permissions, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update( - {required String presenceId, - String? status, - String? expiresAt, - Map? metadata, - List? permissions, - bool? purge}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - if (permissions != null) 'permissions': permissions, - if (purge != null) 'purge': purge, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + if (permissions != null) 'permissions': permissions, + + if (purge != null) 'purge': purge, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/storage.dart b/lib/services/storage.dart index cdb626de..c9499a99 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,178 +1,166 @@ part of '../appwrite.dart'; -/// The Storage service allows you to manage your project files. + /// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, - bool? total}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); + Future listFiles({required String bucketId, List? queries, String? search, bool? total}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } /// 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, - if (permissions != null) 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', - 'accept': 'application/json', - }; - - 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); + /// + 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, + + if (permissions != null) 'permissions': permissions, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', 'accept': 'application/json', + }; + + 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 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); + 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 apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.File.fromMap(res.data); - return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); + 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 = { + if (name != null) 'name': name, + + 'permissions': permissions, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileDownload({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Get a file preview image. Currently, this method supports preview for image @@ -180,64 +168,60 @@ class Storage extends Service { /// 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, - String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (gravity != null) 'gravity': gravity.value, - if (quality != null) 'quality': quality, - if (borderWidth != null) 'borderWidth': borderWidth, - if (borderColor != null) 'borderColor': borderColor, - if (borderRadius != null) 'borderRadius': borderRadius, - if (opacity != null) 'opacity': opacity, - if (rotation != null) 'rotation': rotation, - if (background != null) 'background': background, - if (output != null) 'output': output.value, - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (gravity != null) 'gravity': gravity.value, + + if (quality != null) 'quality': quality, + + if (borderWidth != null) 'borderWidth': borderWidth, + + if (borderColor != null) 'borderColor': borderColor, + + if (borderRadius != null) 'borderRadius': borderRadius, + + if (opacity != null) 'opacity': opacity, + + if (rotation != null) 'rotation': rotation, + + if (background != null) 'background': background, + + if (output != null) 'output': output.value, + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileView({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 8b6284b3..42572021 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -5,382 +5,319 @@ class TablesDB extends Service { TablesDB(super.client); /// List transactions across all databases. - Future listTransactions( - {List? queries}) async { + Future listTransactions({List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future getTransaction({required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; - final Map apiParams = { - if (operations != null) 'operations': operations, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows( - {required String databaseId, - required String tableId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); + Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); + } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow( - {required String databaseId, - required String tableId, - required String rowId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + + 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow( - {required String databaseId, - required String tableId, - required String rowId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Delete a row by its unique ID. - Future deleteRow( - {required String databaseId, - required String tableId, - required String rowId, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + 'min': min, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Increment a specific column of a row by a given value. - Future incrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + 'max': max, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 1f4022f6..27bc561e 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,97 +1,98 @@ 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 + /// 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); /// 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, bool? total}) async { + Future list({List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (search != null) 'search': search, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); - return models.TeamList.fromMap(res.data); } /// 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 { + Future create({required String teamId, required String name, List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - 'name': name, - if (roles != null) 'roles': roles, - }; + final Map apiParams = { + 'teamId': teamId, + + 'name': name, + + if (roles != null) 'roles': roles, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// 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 apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { + Future updateName({required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -99,45 +100,44 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships( - {required String teamId, - List? queries, - String? search, - bool? total}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); + Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -146,199 +146,180 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - if (userId != null) 'userId': userId, - if (phone != null) 'phone': phone, - 'roles': roles, - if (url != null) 'url': url, - if (name != null) 'name': name, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + if (email != null) 'email': email, + + if (userId != null) 'userId': userId, + + if (phone != null) 'phone': phone, + + 'roles': roles, + + if (url != null) 'url': url, + + if (name != null) 'name': name, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); + 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 apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Membership.fromMap(res.data); - return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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 String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// 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); + 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 apiParams = { - 'prefs': prefs, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } } diff --git a/lib/src/client.dart b/lib/src/client.dart index cc077e56..c75dc37b 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -66,6 +65,11 @@ abstract class Client { /// Your secret JSON Web Token. Client setJWT(String value); + /// Set Bearer. + /// + /// The OAuth access token to authenticate with. + Client setBearer(String value); + /// Set Locale. Client setLocale(String value); @@ -108,6 +112,7 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); + /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index da1a5225..307da593 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -6,33 +6,29 @@ abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); + /// The OAuth access token to authenticate with + @override + ClientBase setBearer(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); - /// Your secret dev API key @override ClientBase setDevKey(value); - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBase setCookie(value); - /// Impersonate a user by ID @override ClientBase setImpersonateUserId(value); - /// Impersonate a user by email @override ClientBase setImpersonateUserEmail(value); - /// Impersonate a user by phone @override ClientBase setImpersonateUserPhone(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 32945efd..3fcfd567 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.2.0', + 'x-sdk-version': '25.3.0', 'X-Appwrite-Response-Format': '1.9.5', }; @@ -62,7 +62,6 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -70,14 +69,19 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - + /// The OAuth access token to authenticate with + @override + ClientBrowser setBearer(value) { + config['bearer'] = value; + addHeader('Authorization', 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) { @@ -85,7 +89,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -93,7 +96,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -101,7 +103,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -109,7 +110,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -117,7 +117,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -227,8 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk( - int index, int start, int end, String? id) async { + Future uploadChunk(int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -266,9 +264,7 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 78a368ae..3252ec0a 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -58,7 +58,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.2.0', + 'x-sdk-version': '25.3.0', 'X-Appwrite-Response-Format': '1.9.5', }; @@ -88,7 +88,6 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -96,14 +95,19 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - + /// The OAuth access token to authenticate with + @override + ClientIO setBearer(value) { + config['bearer'] = value; + addHeader('Authorization', 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) { @@ -111,7 +115,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -119,7 +122,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -127,7 +129,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -135,7 +136,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -143,7 +143,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -402,9 +401,7 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -428,8 +425,7 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = - file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 89aad359..40484946 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,6 +12,7 @@ mixin ClientMixin { required Map headers, required Map params, }) { + http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -127,13 +128,9 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response( - '', + return http.Response('', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index fb4983db..765b3e0c 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,30 +1,32 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({required this.value}); + const BrowserPermission({ + 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_theme.dart b/lib/src/enums/browser_theme.dart index 1e059c2c..e81a0f68 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,12 +1,14 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({required this.value}); + const BrowserTheme({ + 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 28c2a1b3..4d6bce3a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,27 +1,29 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 44de4907..6ad112fe 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index 7ea9865e..f54859c9 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({required this.value}); + const ExecutionStatus({ + 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_trigger.dart b/lib/src/enums/execution_trigger.dart index fb05eb7d..8a14ae60 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,13 +1,15 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({required this.value}); + const ExecutionTrigger({ + 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 55f4c5db..0f996ed9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 b88e0a55..77cad38c 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,53 +1,56 @@ 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index d5d8d94a..4a8de1ce 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,429 +1,431 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({required this.value}); + const Timezone({ + 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 c6974573..683e6387 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 344a8770..f80fa854 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 9909265e..c51da4bb 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 746fbd52..43523ab1 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index cab45e49..8562c4e3 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index a1648843..8e844839 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 33ef4a6f..5202db05 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 4984df75..3d08af9f 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index ec3c41be..930900bf 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index df28f04b..753bcacc 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3bcbb76d..c4838ba3 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 79cb1256..f363a54b 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 f2b18093..b6bb455f 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 6c39ae2e..eb2bad19 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 be08d599..0d1fdeb0 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 76a07309..0e30844a 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,33 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3629e1d6..3e767ca3 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,129 +2,125 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values - .firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values - .firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 63c2ad7e..45b60682 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 01cdcb3a..9e5f9eb1 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,101 +2,101 @@ 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; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - 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.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + 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.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 1157554a..84c54b2e 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa054420..bbccf88a 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index cc659043..7e90020c 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 a5d39ea0..d9cc09a2 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 cda66c70..2000acb6 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 87dc3606..1422d065 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 6198d61e..5d78a367 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 54dd0c29..926e352d 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,59 +2,125 @@ 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(), - ); - } - - @override - 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 21405aff..49ef3b0b 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 202355a4..a3a26b61 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 572cce50..ac4eacf3 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 3494b111..ebf593c2 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4d8a2f9b..4baffb71 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index cc664c9f..a0641a28 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa385541..3d2e2335 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 2777de7f..a7e5fefc 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 864a5db8..33036476 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index fe5327fc..05cab363 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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 60e2abd9..7ac578e2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 1a197fc7..9791d590 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3ca04118..b107afe5 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index d31911de..133fe66d 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index 3d010b1c..aebbe880 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: - List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index a825eab0..c5f233b4 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 5023c633..90efa95f 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 92e4034e..c37de95a 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 4ea12394..d823d0e6 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 450aafd1..850ab8d2 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 c2e8c4dc..742e7590 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 91b888b9..21e65e95 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 e8f1c621..ffca5e98 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b5ea87c8..b05320da 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index b0606dd8..e3f3e43d 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 7f321175..19ea651d 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from( - map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5a6cad30..e3b9536b 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 28e4c43d..7a5e6303 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..83f01b4c 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 72edf5ee..6cebb5b1 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,7 +58,9 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({"type": "ping"})); + _websok!.sink.add(jsonEncode({ + "type": "ping" + })); } }); } @@ -138,11 +140,9 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; + final subscriptions = (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? []; if (subscriptions.isEmpty) { break; @@ -209,15 +209,13 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = - "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -312,11 +310,9 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = - channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -333,7 +329,8 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update({List? channels, List? queries}) async { + Future update( + {List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -420,4 +417,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} +} \ No newline at end of file diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index b0356111..56e7669a 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/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..ce0b7e95 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', - ); + 'Cannot create a client without dart:html or dart:io.', +); diff --git a/pubspec.yaml b/pubspec.yaml index 1277dec1..7009bc3b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 25.2.0 +version: 25.3.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies 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/channel_test.dart b/test/channel_test.dart index 9e0e11d3..62031aec 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,22 +13,12 @@ void main() { }); test('returns database channel with action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -44,12 +34,7 @@ void main() { }); test('returns tablesdb channel with action', () { - expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), + expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -62,16 +47,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + expect(Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -98,30 +83,29 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index db7b9214..25388fad 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,3 +354,4 @@ void main() { expect(query['method'], 'between'); }); } + diff --git a/test/services/account_test.dart b/test/services/account_test.dart index d5d61fe7..bd65aa32 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,1356 +41,1540 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; + group('Account test', () { + late MockClient client; + late Account account; + + setUp(() { + client = MockClient(); + account = Account(client); + }); + + test('test method get()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.get( + ); + expect(response, isA()); - setUp(() { - client = MockClient(); - account = Account(client); - }); + }); + + test('test method create()', () async { - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.get(); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); - test('test method updateEmail()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method listIdentities()', () async { - final Map data = { - 'total': 5, - 'identities': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - final response = await account.listIdentities(); - expect(response, isA()); - }); + }); - test('test method deleteIdentity()', () async { - final data = ''; + test('test method updateEmail()', () async { - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - final response = await account.deleteIdentity( - identityId: '', - ); - }); - test('test method createJWT()', () async { - final Map data = { - 'jwt': - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.createJWT(); - expect(response, isA()); - }); + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - test('test method listLogs()', () async { - final Map data = { - 'total': 5, - 'logs': [], - }; + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listIdentities()', () async { - final response = await account.listLogs(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'identities': [],}; - test('test method updateMFA()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - }); - test('test method createMfaAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createMFAAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); - test('test method updateMfaAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); + final response = await account.listIdentities( + ); + expect(response, isA()); - test('test method updateMFAAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); + }); - test('test method deleteMfaAuthenticator()', () async { - final data = ''; + test('test method deleteIdentity()', () async { - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final data = ''; - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteMFAAuthenticator()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteIdentity( + identityId: '', + ); + }); - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + test('test method createJWT()', () async { - test('test method createMfaChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); + final Map data = { + 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',}; - test('test method createMFAChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); - test('test method updateMfaChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMFAChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); - test('test method listMfaFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final response = await account.createJWT( + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.listMfaFactors(); - expect(response, isA()); - }); + test('test method listLogs()', () async { - test('test method listMFAFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final Map data = { + 'total': 5, + 'logs': [],}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.listMFAFactors(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listLogs( + ); + expect(response, isA()); - final response = await account.getMfaRecoveryCodes(); - expect(response, isA()); - }); + }); - test('test method getMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + test('test method updateMFA()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - final response = await account.getMFARecoveryCodes(); - expect(response, isA()); - }); - test('test method createMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.createMfaRecoveryCodes(); - expect(response, isA()); - }); + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); - test('test method createMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method createMfaAuthenticator()', () async { - final response = await account.createMFARecoveryCodes(); - expect(response, isA()); - }); + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - test('test method updateMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.updateMfaRecoveryCodes(); - expect(response, isA()); - }); - test('test method updateMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.updateMFARecoveryCodes(); - expect(response, isA()); - }); + test('test method createMFAAuthenticator()', () async { - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - }); + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - test('test method updatePassword()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - }); - test('test method updatePhone()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method getPrefs()', () async { - final Map data = {}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); - final response = await account.getPrefs(); - expect(response, isA()); - }); + }); - test('test method updatePrefs()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - }); + test('test method updateMfaAuthenticator()', () async { - test('test method createRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method updateRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); - }); - test('test method listSessions()', () async { - final Map data = { - 'total': 5, - 'sessions': [], - }; + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.listSessions(); - expect(response, isA()); - }); + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); - test('test method deleteSessions()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFAAuthenticator()', () async { - final response = await account.deleteSessions(); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createAnonymousSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createAnonymousSession(); - expect(response, isA()); - }); - test('test method createEmailPasswordSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMagicURLSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); - test('test method createOAuth2Session()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); + }); - test('test method updatePhoneSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + test('test method deleteMfaAuthenticator()', () async { - test('test method createSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + final data = ''; - test('test method getSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - }); - test('test method deleteSession()', () async { - final data = ''; + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteMFAAuthenticator()', () async { - final response = await account.deleteSession( - sessionId: '', - ); - }); + final data = ''; - test('test method updateStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateStatus(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method createPushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); - test('test method updatePushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + + test('test method createMfaChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method createMFAChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method updateMfaChallenge()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method deletePushTarget()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.deletePushTarget( - targetId: '', - ); - }); - test('test method createEmailToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); - test('test method createMagicURLToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + }); - test('test method createOAuth2Token()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + test('test method updateMFAChallenge()', () async { - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createPhoneToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); - }); - test('test method createEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - test('test method createVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); - test('test method updateEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); - test('test method updateVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + }); - test('test method createPhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneVerification(); - expect(response, isA()); - }); + test('test method listMfaFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMfaFactors( + ); + expect(response, isA()); + + }); + + test('test method listMFAFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMFAFactors( + ); + expect(response, isA()); + + }); + + test('test method getMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method getMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + + }); + + test('test method updatePassword()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updatePhone()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getPrefs( + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + + }); + + test('test method createRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method listSessions()', () async { + + final Map data = { + 'total': 5, + 'sessions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listSessions( + ); + expect(response, isA()); + + }); + + test('test method deleteSessions()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSessions( + ); + }); + + test('test method createAnonymousSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createAnonymousSession( + ); + expect(response, isA()); + + }); + + test('test method createEmailPasswordSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updateMagicURLSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Session()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method updatePhoneSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSession()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSession( + sessionId: '', + ); + }); + + test('test method updateStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateStatus( + ); + expect(response, isA()); + + }); + + test('test method createPushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true,}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method updatePushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true,}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method deletePushTarget()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deletePushTarget( + targetId: '', + ); + }); + + test('test method createEmailToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createMagicURLToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Token()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method createPhoneToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + + }); + + test('test method createEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method createVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method updateVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createPhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneVerification( + ); + expect(response, isA()); + + }); + + test('test method updatePhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); - test('test method updatePhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 8d2c48fb..4bdb434d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,123 +41,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); - test('test method getBrowser()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getBrowser()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - }); - test('test method getCreditCard()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - }); + test('test method getCreditCard()', () async { +final Uint8List data = Uint8List.fromList([]); - test('test method getFavicon()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - }); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); - test('test method getFlag()', () async { - final Uint8List data = Uint8List.fromList([]); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFavicon()', () async { +final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getImage()', () async { - final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); - }); + }); - test('test method getInitials()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getFlag()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials(); - expect(response, isA()); - }); - test('test method getQR()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); + + test('test method getImage()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method getInitials()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getInitials( + ); + expect(response, isA()); + + }); + + test('test method getQR()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + + }); + + test('test method getScreenshot()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); - }); - test('test method getScreenshot()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a3807093..a4b0a6cc 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,337 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; + group('Databases test', () { + late MockClient client; + late Databases databases; - setUp(() { - client = MockClient(); - databases = Databases(client); - }); + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [],}; - final response = await databases.listTransactions(); - expect(response, isA()); - }); - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createTransaction(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + final response = await databases.listTransactions( + ); + expect(response, isA()); - test('test method deleteTransaction()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createTransaction()', () async { - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method listDocuments()', () async { - final Map data = { - 'total': 5, - 'documents': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method createDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + final response = await databases.createTransaction( + ); + expect(response, isA()); - test('test method upsertDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + test('test method getTransaction()', () async { - test('test method deleteDocument()', () async { - final data = ''; + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method decrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); - }); - test('test method incrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listDocuments()', () async { + + final Map data = { + 'total': 5, + 'documents': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + + }); + + test('test method createDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method updateDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteDocument()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); + + test('test method decrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); + + test('test method incrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); + }); - }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index c6e50a50..9b0d046f 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,100 +41,107 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; + group('Functions test', () { + late MockClient client; + late Functions functions; - setUp(() { - client = MockClient(); - functions = Functions(client); - }); + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - test('test method listExecutions()', () async { - final Map data = { - 'total': 5, - 'executions': [], - }; + test('test method listExecutions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'executions': [],}; - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - }); - test('test method createExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method createExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4,}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method getExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); + + }); - test('test method getExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 84b7de1c..c548e414 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,45 +41,47 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method query()', () async { - final data = ''; + test('test method query()', () async { - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final data = ''; - final response = await graphql.query( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await graphql.query( + query: {}, + ); + }); + + test('test method mutation()', () async { + + final data = ''; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method mutation()', () async { - final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); + }); - final response = await graphql.mutation( - query: {}, - ); }); - }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index f9f6489d..42faaf72 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,138 +41,168 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; + group('Locale test', () { + late MockClient client; + late Locale locale; - setUp(() { - client = MockClient(); - locale = Locale(client); - }); + setUp(() { + client = MockClient(); + locale = Locale(client); + }); - test('test method get()', () async { - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await locale.get(); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method listCodes()', () async { - final Map data = { - 'total': 5, - 'localeCodes': [], - }; + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD',}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCodes(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method listContinents()', () async { - final Map data = { - 'total': 5, - 'continents': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.get( + ); + expect(response, isA()); - final response = await locale.listContinents(); - expect(response, isA()); - }); + }); - test('test method listCountries()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + test('test method listCodes()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'localeCodes': [],}; - final response = await locale.listCountries(); - expect(response, isA()); - }); - test('test method listCountriesEU()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCountriesEU(); - expect(response, isA()); - }); + final response = await locale.listCodes( + ); + expect(response, isA()); - test('test method listCountriesPhones()', () async { - final Map data = { - 'total': 5, - 'phones': [], - }; + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listContinents()', () async { - final response = await locale.listCountriesPhones(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'continents': [],}; - test('test method listCurrencies()', () async { - final Map data = { - 'total': 5, - 'currencies': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listContinents( + ); + expect(response, isA()); + + }); + + test('test method listCountries()', () async { + + final Map data = { + 'total': 5, + 'countries': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountries( + ); + expect(response, isA()); + + }); + + test('test method listCountriesEU()', () async { + + final Map data = { + 'total': 5, + 'countries': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesEU( + ); + expect(response, isA()); + + }); + + test('test method listCountriesPhones()', () async { + + final Map data = { + 'total': 5, + 'phones': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesPhones( + ); + expect(response, isA()); + + }); + + test('test method listCurrencies()', () async { + + final Map data = { + 'total': 5, + 'currencies': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCurrencies( + ); + expect(response, isA()); + + }); + + test('test method listLanguages()', () async { + + final Map data = { + 'total': 5, + 'languages': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCurrencies(); - expect(response, isA()); - }); - test('test method listLanguages()', () async { - final Map data = { - 'total': 5, - 'languages': [], - }; + final response = await locale.listLanguages( + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await locale.listLanguages(); - expect(response, isA()); }); - }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 0c938eff..5899ace3 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,68 +41,71 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; + group('Messaging test', () { + late MockClient client; + late Messaging messaging; - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - test('test method createSubscriber()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - }); + test('test method createSubscriber()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSubscriber()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteSubscriber()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); + }); - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); }); - }); } diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7fed0439..7b99675f 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,108 +41,121 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; + group('Presences test', () { + late MockClient client; + late Presences presences; - setUp(() { - client = MockClient(); - presences = Presences(client); - }); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'presences': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'presences': [],}; - final response = await presences.list(); - expect(response, isA()); - }); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method upsert()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - }); - test('test method update()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); - }); + final response = await presences.list( + ); + expect(response, isA()); + + }); + + test('test method get()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method upsert()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + + }); + + test('test method update()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method delete()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); + }); - final response = await presences.delete( - presenceId: '', - ); }); - }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 55a42f94..2390bfdd 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,184 +41,202 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; + group('Storage test', () { + late MockClient client; + late Storage storage; + + setUp(() { + client = MockClient(); + storage = Storage(client); + }); + + test('test method listFiles()', () async { + + final Map data = { + 'total': 5, + 'files': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); + + }); + + test('test method createFile()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; + - setUp(() { - client = MockClient(); - storage = Storage(client); - }); + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); - test('test method listFiles()', () async { - final Map data = { - 'total': 5, - 'files': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + + }); - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - }); + test('test method getFile()', () async { - test('test method createFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; - test('test method getFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method updateFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteFile()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + }); - test('test method getFileDownload()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method updateFile()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method getFilePreview()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteFile()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + + test('test method getFileDownload()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFilePreview()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFileView()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + - test('test method getFileView()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index f318cad2..5219d2bf 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,337 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [],}; - final response = await tablesDB.listTransactions(); - expect(response, isA()); - }); - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createTransaction(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + final response = await tablesDB.listTransactions( + ); + expect(response, isA()); - test('test method deleteTransaction()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createTransaction()', () async { - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method listRows()', () async { - final Map data = { - 'total': 5, - 'rows': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method createRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + final response = await tablesDB.createTransaction( + ); + expect(response, isA()); - test('test method upsertRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + test('test method getTransaction()', () async { - test('test method deleteRow()', () async { - final data = ''; + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method decrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); - }); - test('test method incrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listRows()', () async { + + final Map data = { + 'total': 5, + 'rows': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + + }); + + test('test method createRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method updateRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteRow()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); + + test('test method decrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); + + test('test method incrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); + }); - }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index 83f2667b..ea72a432 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,288 +41,326 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; + group('Teams test', () { + late MockClient client; + late Teams teams; - setUp(() { - client = MockClient(); - teams = Teams(client); - }); + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'teams': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'teams': [],}; - final response = await teams.list(); - expect(response, isA()); - }); - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - }); - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - }); + final response = await teams.list( + ); + expect(response, isA()); - test('test method delete()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method create()', () async { - final response = await teams.delete( - teamId: '', - ); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; - test('test method listMemberships()', () async { - final Map data = { - 'total': 5, - 'memberships': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - }); - test('test method createMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - }); + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); - test('test method getMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method deleteMembership()', () async { - final data = ''; + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMembershipStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); - }); - test('test method getPrefs()', () async { - final Map data = {}; + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.delete( + teamId: '', + ); + }); + + test('test method listMemberships()', () async { + + final Map data = { + 'total': 5, + 'memberships': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method createMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method getMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + + }); + + test('test method updateMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method deleteMembership()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); + + test('test method updateMembershipStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); - }); - test('test method updatePrefs()', () async { - final Map data = {}; + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); }); - }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 261daa46..15e85f5a 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 3da36624..87a3ca3c 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index e58fa5b5..3b842e6c 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 3bcbb488..49b1e22c 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index b2084927..dd7fa8c3 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,18 +8,16 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index 8c131568..c7d9cdbf 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index d080569c..ae58b57e 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index e71dcae1..8de695b0 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index 85e559f5..d5242a4e 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 6df5c584..869f5db6 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index d5404a7f..bc66ab7b 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index d7410db8..09da675c 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 00e046c7..29890008 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index 217d37e8..f1a5b3cc 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 397b5fab..6c1fbb77 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index a3305e55..cb10c58e 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -1,4 +1,5 @@ import 'package:appwrite/models.dart'; +import 'package:appwrite/enums.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -12,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 80ef508a..6d9bf33c 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index 8e02f65e..d8e6c95c 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 7f132646..8a734a08 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -24,20 +24,20 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 9252b469..489891d4 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 8c35afec..65f562a7 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 525af4ea..708c8c60 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index 93376af1..e616a956 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,15 +5,13 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index a07c0b5f..94c1e33f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index 4a6c96c1..d4087d5e 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index 65b44ad1..b6de5137 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index 88cf157b..f0fcdbce 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 49cb1fc9..72102045 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index b07ca8ee..84c560c8 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index c8211d3b..1b463633 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index 4f30c48e..bb1f0946 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index b2b8bd3d..ab136c24 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 5d3febca..9410baa3 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index 64cc55e4..ed6467d3 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index 500913c8..fa097a49 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 81657394..3f45d288 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,16 +6,14 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index bf22a5c7..6ca46a63 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index f70db0e3..d0e5333b 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index 9db30b03..acde349c 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,6 +10,7 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); + }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 46f69af6..57a86348 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index ef2ebe31..edcfe5f5 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index 12693926..d4900dd4 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 564bf303..4e72a449 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index 708e0583..eaab249e 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 689e6048..0177e477 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 7445514c..94c6a502 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index 49f1e75e..a49f3def 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index fe2f4a85..a19b667d 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index f652f2c1..43b2e45c 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 8f0957c9..7ee4b268 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index a524ef71..68023e18 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 0169427f..723ebac2 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index 77c7dd97..c058ea26 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From e50fec6c973ac0c6430c13277a75e1b3c72d3b1a Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Mon, 13 Jul 2026 05:17:04 +0000 Subject: [PATCH 02/17] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/operator.dart | 11 +- lib/query.dart | 89 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1560 +++++----- lib/services/avatars.dart | 351 ++- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/presences.dart | 182 +- lib/services/storage.dart | 342 ++- lib/services/tables_db.dart | 547 ++-- lib/services/teams.dart | 421 +-- lib/src/client.dart | 4 +- lib/src/client_base.dart | 8 + lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 16 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 ++- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 98 +- lib/src/enums/timezone.dart | 848 +++--- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 194 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 243 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +-- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 - test/services/account_test.dart | 2691 ++++++++--------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 585 ++-- test/services/functions_test.dart | 188 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 253 +- test/services/messaging_test.dart | 122 +- test/services/presences_test.dart | 202 +- test/services/storage_test.dart | 341 +-- test/services/tables_db_test.dart | 585 ++-- test/services/teams_test.dart | 555 ++-- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 6 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 30 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 - test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 166 files changed, 8586 insertions(+), 8727 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index 6615de8a..ae51be5e 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/channel.dart b/lib/channel.dart index d511f5a4..afc68efa 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,19 +2,33 @@ part of appwrite; // Marker classes for type safety class _Root {} + class _Database {} + class _Collection {} + class _Document {} + class _TablesDB {} + class _Table {} + class _Row {} + class _Bucket {} + class _File {} + class _Func {} + class _Execution {} + class _Team {} + class _Membership {} + class _Presence {} + class _Resolved {} // Helper function for normalizing ID @@ -99,15 +113,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => + _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => - _next<_Table>('tables', id); + Channel<_Table> table(String id) => _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/operator.dart b/lib/operator.dart index 9dd7f4c7..337dda30 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if(values != null) { + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -147,8 +147,7 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => - Operator._('arrayUnique', []).toString(); + static String arrayUnique() => Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -173,8 +172,7 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => - Operator._('toggle', []).toString(); + static String toggle() => Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -185,6 +183,5 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => - Operator._('dateSetNow', []).toString(); + static String dateSetNow() => Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 2221a6e6..2772116a 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if(attribute != null) { + + if (attribute != null) { result['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,50 +140,46 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => - lessThan('\$createdAt', value); + static String createdBefore(String value) => lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => - greaterThan('\$createdAt', value); + static String createdAfter(String value) => greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => - lessThan('\$updatedAt', value); + static String updatedBefore(String value) => lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => - greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -198,18 +194,17 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => - Query._('orderRandom').toString(); + static String orderRandom() => Query._('orderRandom').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(); /// 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) => @@ -219,27 +214,43 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceNotEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceNotEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); + static String distanceGreaterThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); + static String distanceLessThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceLessThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources using vector dot product similarity. static String vectorDot(String attribute, List vector) => 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 3f91a53a..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 9c021e93..48b60041 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; - /// The Account service allows you to authenticate and manage a user account. +/// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,18 +9,17 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -30,29 +29,30 @@ class Account extends Service { /// 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 { + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - 'password': password, - - if (name != null) 'name': name, - - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + if (name != null) 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Update currently logged in user account email address. After changing user @@ -62,66 +62,65 @@ class Account extends Service { /// 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 { + /// + Future updateEmail( + {required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - - 'password': password, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'email': email, + 'password': password, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries, bool? total}) async { + Future listIdentities( + {List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.IdentityList.fromMap(res.data); } /// 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 String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -132,20 +131,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, + final Map apiParams = { + if (duration != null) 'duration': duration, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -153,212 +152,224 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'mfa': mfa, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// 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 = { - }; + Future createMFAAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); } /// 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, - - }; + Future updateMFAAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'otp': otp, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'factor': factor.value, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, + final Map apiParams = { + 'factor': factor.value, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -366,26 +377,27 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge({required String challengeId, required String otp}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - - 'otp': otp, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -393,84 +405,83 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge({required String challengeId, required String otp}) async { + Future updateMFAChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - 'otp': otp, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -480,18 +491,17 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -499,22 +509,23 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -525,40 +536,41 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -568,62 +580,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - - }; + final Map apiParams = { + 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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 { + Future updatePassword( + {required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, - - if (oldPassword != null) 'oldPassword': oldPassword, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'password': password, + if (oldPassword != null) 'oldPassword': oldPassword, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -631,43 +643,42 @@ class Account extends Service { /// 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 { + Future updatePhone( + {required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, + final Map apiParams = { + 'phone': phone, + 'password': password, + }; - 'password': password, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -676,20 +687,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, + final Map apiParams = { + 'prefs': prefs, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -700,25 +711,25 @@ class Account extends Service { /// /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 { + Future createRecovery( + {required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - - 'url': url, - - }; + final Map apiParams = { + 'email': email, + 'url': url, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -726,32 +737,33 @@ class Account extends Service { /// 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 { + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - 'password': password, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -759,18 +771,17 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.SessionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -778,18 +789,17 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -802,213 +812,216 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession( + {required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - - 'password': password, + final Map apiParams = { + 'email': email, + 'password': password, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + /// + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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); + } + } 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); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1017,20 +1030,20 @@ class Account extends Service { /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1039,18 +1052,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1058,27 +1071,28 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - - 'identifier': identifier, - - if (providerId != null) 'providerId': providerId, - - }; + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + if (providerId != null) 'providerId': providerId, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1086,43 +1100,45 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, + 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1134,32 +1150,31 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, + final Map apiParams = { + 'userId': userId, + 'email': email, + if (phrase != null) 'phrase': phrase, + }; - 'email': email, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - if (phrase != null) 'phrase': phrase, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1171,87 +1186,88 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - if (url != null) 'url': url, - - if (phrase != null) 'phrase': phrase, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + if (url != null) 'url': url, + if (phrase != null) 'phrase': phrase, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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); + } + } 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); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1260,29 +1276,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken( + {required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, - - 'phone': phone, + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1294,29 +1310,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'url': url, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1328,81 +1344,83 @@ class Account extends Service { /// 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. - /// - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, + final Map apiParams = { + 'url': url, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 updateEmailVerification({required String userId, required String secret}) async { + Future updateEmailVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1416,42 +1434,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + 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 4dca3b16..cdd93e6e 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Avatars service aims to help you complete everyday tasks related to - /// your app image, icons, and avatars. +/// 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); @@ -11,139 +11,134 @@ class Avatars extends Service { /// /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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { final String apiPath = '/avatars/favicon'; - final Map params = { - - 'url': url, + final Map params = { + 'url': url, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + Future getImage( + {required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map params = { - - 'url': url, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'url': url, + if (width != null) 'width': width, + if (height != null) 'height': height, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to show your user initials avatar icon on your website or @@ -151,125 +146,117 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map params = { - - if (name != null) 'name': name, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (background != null) 'background': background, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + if (name != null) 'name': name, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (background != null) 'background': background, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map params = { - - 'text': text, - - if (size != null) 'size': size, - - if (margin != null) 'margin': margin, - - if (download != null) 'download': download, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'text': text, + if (size != null) 'size': size, + if (margin != null) 'margin': margin, + if (download != null) 'download': download, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { + Future getScreenshot( + {required String url, + Map? headers, + int? viewportWidth, + int? viewportHeight, + double? scale, + enums.BrowserTheme? theme, + String? userAgent, + bool? fullpage, + String? locale, + enums.Timezone? timezone, + double? latitude, + double? longitude, + double? accuracy, + bool? touch, + List? permissions, + int? sleep, + int? width, + int? height, + int? quality, + enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map params = { - - 'url': url, - - if (headers != null) 'headers': headers, - - if (viewportWidth != null) 'viewportWidth': viewportWidth, - - if (viewportHeight != null) 'viewportHeight': viewportHeight, - - if (scale != null) 'scale': scale, - - if (theme != null) 'theme': theme.value, - - if (userAgent != null) 'userAgent': userAgent, - - if (fullpage != null) 'fullpage': fullpage, - - if (locale != null) 'locale': locale, - - if (timezone != null) 'timezone': timezone.value, - - if (latitude != null) 'latitude': latitude, - - if (longitude != null) 'longitude': longitude, - - if (accuracy != null) 'accuracy': accuracy, - - if (touch != null) 'touch': touch, - - if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), - - if (sleep != null) 'sleep': sleep, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - if (output != null) 'output': output.value, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'url': url, + if (headers != null) 'headers': headers, + if (viewportWidth != null) 'viewportWidth': viewportWidth, + if (viewportHeight != null) 'viewportHeight': viewportHeight, + if (scale != null) 'scale': scale, + if (theme != null) 'theme': theme.value, + if (userAgent != null) 'userAgent': userAgent, + if (fullpage != null) 'fullpage': fullpage, + if (locale != null) 'locale': locale, + if (timezone != null) 'timezone': timezone.value, + if (latitude != null) 'latitude': latitude, + if (longitude != null) 'longitude': longitude, + if (accuracy != null) 'accuracy': accuracy, + if (touch != null) 'touch': touch, + if (permissions != null) + 'permissions': permissions.map((e) => e.value).toList(), + if (sleep != null) 'sleep': sleep, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + if (output != null) 'output': output.value, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + 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 0bfd935a..0ff3fb72 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,339 +1,418 @@ part of '../appwrite.dart'; - /// The Databases service allows you to create structured collections of - /// documents, query and filter lists of documents +/// 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 transactions across all databases. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions({List? queries}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions( + {List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - - 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Create or update a 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Delete a document by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - 'min': min, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + 'min': min, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Increment a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - 'max': max, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + 'max': max, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 0640f80f..ed97921b 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,82 +1,87 @@ part of '../appwrite.dart'; - /// The Functions Service allows you view, create and manage your Cloud - /// Functions. +/// The Functions Service allows you view, create and manage your Cloud +/// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + Future listExecutions( + {required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - - if (xasync != null) 'async': xasync, - - if (path != null) 'path': path, - - if (method != null) 'method': method.value, - - if (headers != null) 'headers': headers, - - 'scheduledAt': scheduledAt, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - + 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 = { + if (body != null) 'body': body, + if (xasync != null) 'async': xasync, + if (path != null) 'path': path, + if (method != null) 'method': method.value, + if (headers != null) 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); } /// 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 = { - }; + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Execution.fromMap(res.data); + 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 978331fa..c86f3719 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The GraphQL API allows you to query and mutate your Appwrite server using - /// GraphQL. +/// 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); @@ -10,39 +10,41 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, + final Map apiParams = { + 'query': query, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'query': query, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + 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 c45a1269..87ea162e 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Locale service allows you to customize your app based on your users' - /// location. +/// 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); @@ -10,23 +10,22 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Locale.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Locale.fromMap(res.data); } /// List of all locale codes in [ISO @@ -34,18 +33,17 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); } /// List of all continents. You can use the locale header to get the data in a @@ -53,18 +51,17 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ContinentList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -72,18 +69,17 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all countries that are currently members of the EU. You can use the @@ -91,18 +87,17 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - 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 of all countries phone codes. You can use the locale header to get the @@ -110,18 +105,17 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.PhoneList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -130,18 +124,17 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -149,17 +142,16 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LanguageList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 3dffe41b..61ecefee 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,48 +1,54 @@ part of '../appwrite.dart'; - /// The Messaging service allows you to send messages to any provider type - /// (SMTP, push notification, SMS, etc.). +/// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); } /// 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 = { - }; + 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 apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 088700cb..1c9b651b 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -5,123 +5,127 @@ class Presences extends Service { Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list({List? queries, bool? total, int? ttl}) async { + /// + Future list( + {List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.PresenceList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - - if (permissions != null) 'permissions': permissions, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future upsert( + {required String presenceId, + required String status, + List? permissions, + String? expiresAt, + Map? metadata}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + if (permissions != null) 'permissions': permissions, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - if (permissions != null) 'permissions': permissions, - - if (purge != null) 'purge': purge, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future update( + {required String presenceId, + String? status, + String? expiresAt, + Map? metadata, + List? permissions, + bool? purge}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + if (permissions != null) 'permissions': permissions, + if (purge != null) 'purge': purge, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - }; + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + 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 c9499a99..cdb626de 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,166 +1,178 @@ part of '../appwrite.dart'; - /// The Storage service allows you to manage your project files. +/// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, bool? total}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - + Future listFiles( + {required String bucketId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); } /// 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, - - if (permissions != null) 'permissions': permissions, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', 'accept': 'application/json', - }; - - 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); - + /// + 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, + if (permissions != null) 'permissions': permissions, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + 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 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); + 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 apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - - 'permissions': permissions, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - + 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 = { + if (name != null) 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileDownload( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Get a file preview image. Currently, this method supports preview for image @@ -168,60 +180,64 @@ class Storage extends Service { /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (gravity != null) 'gravity': gravity.value, - - if (quality != null) 'quality': quality, - - if (borderWidth != null) 'borderWidth': borderWidth, - - if (borderColor != null) 'borderColor': borderColor, - - if (borderRadius != null) 'borderRadius': borderRadius, - - if (opacity != null) 'opacity': opacity, - - if (rotation != null) 'rotation': rotation, - - if (background != null) 'background': background, - - if (output != null) 'output': output.value, - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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, + String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (gravity != null) 'gravity': gravity.value, + if (quality != null) 'quality': quality, + if (borderWidth != null) 'borderWidth': borderWidth, + if (borderColor != null) 'borderColor': borderColor, + if (borderRadius != null) 'borderRadius': borderRadius, + if (opacity != null) 'opacity': opacity, + if (rotation != null) 'rotation': rotation, + if (background != null) 'background': background, + if (output != null) 'output': output.value, + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileView( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 42572021..8b6284b3 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -5,319 +5,382 @@ class TablesDB extends Service { TablesDB(super.client); /// List transactions across all databases. - Future listTransactions({List? queries}) async { + Future listTransactions( + {List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + if (operations != null) 'operations': operations, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); - + Future listRows( + {required String databaseId, + required String tableId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - - 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future createRow( + {required String databaseId, + required String tableId, + required String rowId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future getRow( + {required String databaseId, + required String tableId, + required String rowId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future upsertRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future updateRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Delete a row by its unique ID. - Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + Future deleteRow( + {required String databaseId, + required String tableId, + required String rowId, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - 'min': min, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future decrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + 'min': min, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Increment a specific column of a row by a given value. - Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - 'max': max, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future incrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + 'max': max, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 27bc561e..1f4022f6 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,98 +1,97 @@ 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 +/// 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); /// 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, bool? total}) async { + Future list( + {List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; - if (search != null) 'search': search, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TeamList.fromMap(res.data); } /// 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 { + Future create( + {required String teamId, + required String name, + List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - - 'name': name, - - if (roles != null) 'roles': roles, - - }; + final Map apiParams = { + 'teamId': teamId, + 'name': name, + if (roles != null) 'roles': roles, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { + Future updateName( + {required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, - - }; + final Map apiParams = { + 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -100,44 +99,45 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - + Future listMemberships( + {required String teamId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -146,180 +146,199 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - - if (userId != null) 'userId': userId, - - if (phone != null) 'phone': phone, - - 'roles': roles, - - if (url != null) 'url': url, - - if (name != null) 'name': name, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + if (email != null) 'email': email, + if (userId != null) 'userId': userId, + if (phone != null) 'phone': phone, + 'roles': roles, + if (url != null) 'url': url, + if (name != null) 'name': name, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + 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 apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 = { - }; + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// 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, - - }; + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'prefs': prefs, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + 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 c75dc37b..dbfe4bdf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,7 +27,8 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => + createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -112,7 +113,6 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); - /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 307da593..f10f0955 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -6,29 +6,37 @@ abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); + /// The OAuth access token to authenticate with @override ClientBase setBearer(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); + /// Your secret dev API key @override ClientBase setDevKey(value); + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBase setCookie(value); + /// Impersonate a user by ID @override ClientBase setImpersonateUserId(value); + /// Impersonate a user by email @override ClientBase setImpersonateUserEmail(value); + /// Impersonate a user by phone @override ClientBase setImpersonateUserPhone(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3fcfd567..4c4662e3 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -62,6 +62,7 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -69,6 +70,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientBrowser setBearer(value) { @@ -76,12 +78,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Authorization', 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) { @@ -89,6 +93,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -96,6 +101,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -103,6 +109,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -110,6 +117,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -117,6 +125,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -226,7 +235,8 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id) async { + Future uploadChunk( + int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -264,7 +274,9 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 3252ec0a..f95e4157 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -88,6 +88,7 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -95,6 +96,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientIO setBearer(value) { @@ -102,12 +104,14 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Authorization', 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) { @@ -115,6 +119,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -122,6 +127,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -129,6 +135,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -136,6 +143,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -143,6 +151,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -401,7 +410,9 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -425,7 +436,8 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = + file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 40484946..89aad359 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,7 +12,6 @@ mixin ClientMixin { required Map headers, required Map params, }) { - http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -128,9 +127,13 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response('', + return http.Response( + '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index 765b3e0c..fb4983db 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,32 +1,30 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({ - required this.value - }); + const BrowserPermission({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_theme.dart b/lib/src/enums/browser_theme.dart index e81a0f68..1e059c2c 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,14 +1,12 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({ - required this.value - }); + const BrowserTheme({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 4d6bce3a..28c2a1b3 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,29 +1,27 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 6ad112fe..44de4907 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index f54859c9..7ea9865e 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({ - required this.value - }); + const ExecutionStatus({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_trigger.dart b/lib/src/enums/execution_trigger.dart index 8a14ae60..fb05eb7d 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,15 +1,13 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({ - required this.value - }); + const ExecutionTrigger({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 0f996ed9..55f4c5db 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 77cad38c..6c8dbc70 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,56 +1,54 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index 4a8de1ce..d5d8d94a 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,431 +1,429 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({ - required this.value - }); + const Timezone({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 683e6387..c6974573 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 f80fa854..344a8770 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 c51da4bb..9909265e 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 43523ab1..746fbd52 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 8562c4e3..cab45e49 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 8e844839..a1648843 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 5202db05..33ef4a6f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 3d08af9f..4984df75 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 930900bf..ec3c41be 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index 753bcacc..df28f04b 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 c4838ba3..3bcbb76d 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index f363a54b..79cb1256 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b6bb455f..f2b18093 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 eb2bad19..6c39ae2e 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 0d1fdeb0..be08d599 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 0e30844a..76a07309 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,33 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3e767ca3..3629e1d6 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,125 +2,129 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values + .firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values + .firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 45b60682..63c2ad7e 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 9e5f9eb1..01cdcb3a 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,101 +2,101 @@ 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; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - 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.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + 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.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 84c54b2e..1157554a 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 bbccf88a..fa054420 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 7e90020c..cc659043 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 d9cc09a2..a5d39ea0 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 2000acb6..cda66c70 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 1422d065..87dc3606 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 5d78a367..6198d61e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 926e352d..c29b9e25 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,125 +2,126 @@ 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; - - /// City - final String? city; - - /// Name of timezone - final String? timeZone; - - /// Postal code - final String? postalCode; - - /// Latitude - final double? latitude; - - /// Longitude - final double? longitude; - - /// Autonomous System Number (ASN) of the IP - final String? autonomousSystemNumber; - - /// Organization that owns the ASN - final String? autonomousSystemOrganization; - - /// Internet service provider of the IP - final String? isp; - - /// Connection type of the IP (e.g. cable, cellular, corporate) - final String? connectionType; - - /// User type classification of the IP (e.g. residential, business, hosting) - final String? connectionUsageType; - - /// Registered organization of the IP - final String? connectionOrganization; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - this.city, - this.timeZone, - this.postalCode, - this.latitude, - this.longitude, - this.autonomousSystemNumber, - this.autonomousSystemOrganization, - this.isp, - this.connectionType, - this.connectionUsageType, - this.connectionOrganization, - }); - - 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(), - city: map['city']?.toString(), - timeZone: map['timeZone']?.toString(), - postalCode: map['postalCode']?.toString(), - latitude: map['latitude']?.toDouble(), - longitude: map['longitude']?.toDouble(), - autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), - autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), - isp: map['isp']?.toString(), - connectionType: map['connectionType']?.toString(), - connectionUsageType: map['connectionUsageType']?.toString(), - connectionOrganization: map['connectionOrganization']?.toString(), - ); - } - - @override - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - "city": city, - "timeZone": timeZone, - "postalCode": postalCode, - "latitude": latitude, - "longitude": longitude, - "autonomousSystemNumber": autonomousSystemNumber, - "autonomousSystemOrganization": autonomousSystemOrganization, - "isp": isp, - "connectionType": connectionType, - "connectionUsageType": connectionUsageType, - "connectionOrganization": connectionOrganization, - }; - } + /// 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: + map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 49ef3b0b..21405aff 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 a3a26b61..202355a4 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 ac4eacf3..d754130d 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 ebf593c2..3494b111 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4baffb71..4d8a2f9b 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index a0641a28..cc664c9f 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3d2e2335..fa385541 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 a7e5fefc..2777de7f 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 33036476..864a5db8 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 05cab363..fe5327fc 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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 7ac578e2..60e2abd9 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 9791d590..1a197fc7 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b107afe5..3ca04118 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index 133fe66d..d31911de 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index aebbe880..3d010b1c 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: + List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index c5f233b4..a825eab0 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 90efa95f..5023c633 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index c37de95a..92e4034e 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 d823d0e6..4ea12394 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 850ab8d2..450aafd1 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 742e7590..c2e8c4dc 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 21e65e95..91b888b9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 ffca5e98..e8f1c621 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b05320da..b5ea87c8 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index e3f3e43d..b0606dd8 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 19ea651d..7f321175 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from( + map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index e3b9536b..5a6cad30 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 7a5e6303..28e4c43d 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 83f01b4c..0ed367a6 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 6cebb5b1..72edf5ee 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,9 +58,7 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({ - "type": "ping" - })); + _websok!.sink.add(jsonEncode({"type": "ping"})); } }); } @@ -140,9 +138,11 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? []; + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; if (subscriptions.isEmpty) { break; @@ -209,13 +209,15 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = + "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse( + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -310,9 +312,11 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, + [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = + channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -329,8 +333,7 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update( - {List? channels, List? queries}) async { + Future update({List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -417,4 +420,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} \ No newline at end of file +} diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index 56e7669a..b0356111 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 diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index ce0b7e95..3aab4e03 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', -); + 'Cannot create a client without dart:html or dart:io.', + ); diff --git a/test/channel_test.dart b/test/channel_test.dart index 62031aec..9e0e11d3 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,12 +13,22 @@ void main() { }); test('returns database channel with action', () { - expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .create() + .toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .upsert() + .toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -34,7 +44,12 @@ void main() { }); test('returns tablesdb channel with action', () { - expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + expect( + Channel.tablesdb('db1') + .table('table1') + .row('row1') + .update() + .toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -47,16 +62,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect(Channel.bucket('bucket1').file().toString(), - 'buckets.bucket1.files'); + expect( + Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -83,29 +98,30 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), + 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index 25388fad..db7b9214 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,4 +354,3 @@ void main() { expect(query['method'], 'between'); }); } - diff --git a/test/services/account_test.dart b/test/services/account_test.dart index bd65aa32..d5d61fe7 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,1540 +40,1356 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; - - setUp(() { - client = MockClient(); - account = Account(client); - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.get( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updateEmail()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method listIdentities()', () async { - - final Map data = { - 'total': 5, - 'identities': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listIdentities( - ); - expect(response, isA()); - - }); - - test('test method deleteIdentity()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteIdentity( - identityId: '', - ); - }); - - test('test method createJWT()', () async { - - final Map data = { - 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createJWT( - ); - expect(response, isA()); - - }); - - test('test method listLogs()', () async { - - final Map data = { - 'total': 5, - 'logs': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listLogs( - ); - expect(response, isA()); - - }); - - test('test method updateMFA()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - - }); - - test('test method createMfaAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method createMFAAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method updateMfaAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method deleteMfaAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method deleteMFAAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method createMfaChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method createMFAChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method updateMfaChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method listMfaFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true,}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMfaFactors( - ); - expect(response, isA()); - - }); - - test('test method listMFAFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true,}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMFAFactors( - ); - expect(response, isA()); - - }); - - test('test method getMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method getMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - + group('Account test', () { + late MockClient client; + late Account account; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - - }); - - test('test method updatePassword()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updatePhone()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method getPrefs()', () async { - - final Map data = {}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getPrefs( - ); - expect(response, isA()); - - }); - - test('test method updatePrefs()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - - }); - - test('test method createRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method updateRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + account = Account(client); + }); + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.get(); + expect(response, isA()); + }); - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); - }); + test('test method updateEmail()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); - test('test method listSessions()', () async { - - final Map data = { - 'total': 5, - 'sessions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listSessions( - ); - expect(response, isA()); - - }); - - test('test method deleteSessions()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteSessions( - ); - }); - - test('test method createAnonymousSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createAnonymousSession( - ); - expect(response, isA()); - - }); - - test('test method createEmailPasswordSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updateMagicURLSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createOAuth2Session()', () async { - - - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); - - - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - - }); - - test('test method updatePhoneSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method getSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSession()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteSession( - sessionId: '', - ); - }); - - test('test method updateStatus()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + test('test method listIdentities()', () async { + final Map data = { + 'total': 5, + 'identities': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listIdentities(); + expect(response, isA()); + }); + test('test method deleteIdentity()', () async { + final data = ''; - final response = await account.updateStatus( - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteIdentity( + identityId: '', + ); + }); - test('test method createPushTarget()', () async { + test('test method createJWT()', () async { + final Map data = { + 'jwt': + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + }; - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true,}; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.createJWT(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method listLogs()', () async { + final Map data = { + 'total': 5, + 'logs': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + final response = await account.listLogs(); + expect(response, isA()); + }); - }); + test('test method updateMFA()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); + }); - test('test method updatePushTarget()', () async { + test('test method createMfaAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true,}; + test('test method createMFAAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); + test('test method updateMfaAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFAAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); + test('test method deleteMfaAuthenticator()', () async { + final data = ''; - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - test('test method deletePushTarget()', () async { + test('test method deleteMFAAuthenticator()', () async { + final data = ''; - final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + test('test method createMfaChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - final response = await account.deletePushTarget( - targetId: '', - ); - }); + test('test method createMFAChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - test('test method createEmailToken()', () async { + test('test method updateMfaChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updateMFAChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); + test('test method listMfaFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.listMfaFactors(); + expect(response, isA()); + }); - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + test('test method listMFAFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createMagicURLToken()', () async { + final response = await account.listMFAFactors(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method getMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.getMfaRecoveryCodes(); + expect(response, isA()); + }); + test('test method getMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.getMFARecoveryCodes(); + expect(response, isA()); + }); - test('test method createOAuth2Token()', () async { + test('test method createMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final response = await account.createMfaRecoveryCodes(); + expect(response, isA()); + }); + test('test method createMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.createMFARecoveryCodes(); + expect(response, isA()); + }); - test('test method createPhoneToken()', () async { + test('test method updateMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.updateMfaRecoveryCodes(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); + final response = await account.updateMFARecoveryCodes(); + expect(response, isA()); + }); - }); + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + }); - test('test method createEmailVerification()', () async { + test('test method updatePassword()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updatePhone()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + }); + test('test method getPrefs()', () async { + final Map data = {}; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.getPrefs(); + expect(response, isA()); + }); - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method updatePrefs()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + }); - }); + test('test method createRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + }); - test('test method createVerification()', () async { + test('test method updateRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method listSessions()', () async { + final Map data = { + 'total': 5, + 'sessions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listSessions(); + expect(response, isA()); + }); + test('test method deleteSessions()', () async { + final data = ''; - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteSessions(); + }); - test('test method updateEmailVerification()', () async { + test('test method createAnonymousSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createAnonymousSession(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method createEmailPasswordSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); + test('test method updateMagicURLSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createOAuth2Session()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updatePhoneSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - test('test method updateVerification()', () async { + test('test method getSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updateSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + }); + test('test method deleteSession()', () async { + final data = ''; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteSession( + sessionId: '', + ); + }); - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateStatus(); + expect(response, isA()); + }); - }); + test('test method createPushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); - test('test method createPhoneVerification()', () async { + test('test method updatePushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method deletePushTarget()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deletePushTarget( + targetId: '', + ); + }); + test('test method createEmailToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - final response = await account.createPhoneVerification( - ); - expect(response, isA()); + test('test method createMagicURLToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - }); + test('test method createOAuth2Token()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); - test('test method updatePhoneVerification()', () async { + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method createPhoneToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + }); + test('test method createEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method updateEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createPhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneVerification(); + expect(response, isA()); + }); + test('test method updatePhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 4bdb434d..8d2c48fb 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,138 +40,123 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; - - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); - - test('test method getBrowser()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - - }); - - test('test method getCreditCard()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - - }); - - test('test method getFavicon()', () async { -final Uint8List data = Uint8List.fromList([]); + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method getFlag()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); + test('test method getBrowser()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); + }); - test('test method getImage()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getCreditCard()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); + }); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getFavicon()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getInitials()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFlag()', () async { + final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials( - ); - expect(response, isA()); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); + }); - }); + test('test method getImage()', () async { + final Uint8List data = Uint8List.fromList([]); - test('test method getQR()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method getInitials()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getInitials(); + expect(response, isA()); + }); - test('test method getScreenshot()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getQR()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getScreenshot()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a4b0a6cc..a3807093 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,337 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; - - setUp(() { - client = MockClient(); - databases = Databases(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listDocuments()', () async { - - final Map data = { - 'total': 5, - 'documents': [],}; - + group('Databases test', () { + late MockClient client; + late Databases databases; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - - }); - - test('test method createDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method updateDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - test('test method deleteDocument()', () async { + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; - final data = ''; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await databases.listTransactions(); + expect(response, isA()); + }); + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createTransaction(); + expect(response, isA()); + }); - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - test('test method decrementDocumentAttribute()', () async { + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method deleteTransaction()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + test('test method listDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + }); - }); + test('test method createDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + }); - test('test method incrementDocumentAttribute()', () async { + test('test method getDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method upsertDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); + test('test method updateDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteDocument()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); - }); + test('test method decrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + }); + test('test method incrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 9b0d046f..c6e50a50 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,107 +40,100 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; - - setUp(() { - client = MockClient(); - functions = Functions(client); - }); - - test('test method listExecutions()', () async { - - final Map data = { - 'total': 5, - 'executions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method createExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4,}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method getExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4,}; + group('Functions test', () { + late MockClient client; + late Functions functions; + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listExecutions()', () async { + final Map data = { + 'total': 5, + 'executions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + }); - }); + test('test method createExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + }); + test('test method getExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index c548e414..84b7de1c 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,47 +40,45 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; - - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); - - test('test method query()', () async { - - final data = ''; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await graphql.query( - query: {}, - ); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method mutation()', () async { + test('test method query()', () async { + final data = ''; - final data = ''; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.query( + query: {}, + ); + }); + test('test method mutation()', () async { + final data = ''; - final response = await graphql.mutation( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); }); + }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index 42faaf72..f9f6489d 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,168 +40,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; - - setUp(() { - client = MockClient(); - locale = Locale(client); - }); - - test('test method get()', () async { - - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.get( - ); - expect(response, isA()); - - }); - - test('test method listCodes()', () async { - - final Map data = { - 'total': 5, - 'localeCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCodes( - ); - expect(response, isA()); - - }); - - test('test method listContinents()', () async { - - final Map data = { - 'total': 5, - 'continents': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listContinents( - ); - expect(response, isA()); + group('Locale test', () { + late MockClient client; + late Locale locale; - }); - - test('test method listCountries()', () async { - - final Map data = { - 'total': 5, - 'countries': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountries( - ); - expect(response, isA()); - - }); - - test('test method listCountriesEU()', () async { - - final Map data = { - 'total': 5, - 'countries': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountriesEU( - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + locale = Locale(client); + }); - test('test method listCountriesPhones()', () async { + test('test method get()', () async { + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await locale.get(); + expect(response, isA()); + }); - final Map data = { - 'total': 5, - 'phones': [],}; + test('test method listCodes()', () async { + final Map data = { + 'total': 5, + 'localeCodes': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCodes(); + expect(response, isA()); + }); + test('test method listContinents()', () async { + final Map data = { + 'total': 5, + 'continents': [], + }; - final response = await locale.listCountriesPhones( - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await locale.listContinents(); + expect(response, isA()); + }); - test('test method listCurrencies()', () async { + test('test method listCountries()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; - final Map data = { - 'total': 5, - 'currencies': [],}; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCountries(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listCountriesEU()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCurrencies( - ); - expect(response, isA()); + final response = await locale.listCountriesEU(); + expect(response, isA()); + }); - }); + test('test method listCountriesPhones()', () async { + final Map data = { + 'total': 5, + 'phones': [], + }; - test('test method listLanguages()', () async { + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final Map data = { - 'total': 5, - 'languages': [],}; + final response = await locale.listCountriesPhones(); + expect(response, isA()); + }); + test('test method listCurrencies()', () async { + final Map data = { + 'total': 5, + 'currencies': [], + }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCurrencies(); + expect(response, isA()); + }); - final response = await locale.listLanguages( - ); - expect(response, isA()); + test('test method listLanguages()', () async { + final Map data = { + 'total': 5, + 'languages': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listLanguages(); + expect(response, isA()); }); + }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 5899ace3..0c938eff 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,71 +40,68 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; - - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); - - test('test method createSubscriber()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + group('Messaging test', () { + late MockClient client; + late Messaging messaging; + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSubscriber()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createSubscriber()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + }); + test('test method deleteSubscriber()', () async { + final data = ''; - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); }); + }); } diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7b99675f..7fed0439 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,121 +40,108 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; - - setUp(() { - client = MockClient(); - presences = Presences(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'presences': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.list( - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - - }); + group('Presences test', () { + late MockClient client; + late Presences presences; - test('test method upsert()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - - }); - - test('test method update()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'presences': [], + }; - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await presences.list(); + expect(response, isA()); + }); - test('test method delete()', () async { + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + }); - final data = ''; + test('test method upsert()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method update()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + }); + test('test method delete()', () async { + final data = ''; - final response = await presences.delete( - presenceId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); }); + }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 2390bfdd..55a42f94 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,202 +40,184 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; - - setUp(() { - client = MockClient(); - storage = Storage(client); - }); - - test('test method listFiles()', () async { - - final Map data = { - 'total': 5, - 'files': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - - }); - - test('test method createFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - - }); - - test('test method getFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method updateFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - + group('Storage test', () { + late MockClient client; + late Storage storage; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteFile()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + storage = Storage(client); + }); + test('test method listFiles()', () async { + final Map data = { + 'total': 5, + 'files': [], + }; - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getFileDownload()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method createFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + test('test method getFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method updateFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - }); + test('test method deleteFile()', () async { + final data = ''; - test('test method getFilePreview()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + test('test method getFileDownload()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - test('test method getFileView()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getFilePreview()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method getFileView()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 5219d2bf..f318cad2 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,337 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; - - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listRows()', () async { - - final Map data = { - 'total': 5, - 'rows': [],}; - + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - - }); - - test('test method createRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method updateRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - test('test method deleteRow()', () async { + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; - final data = ''; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await tablesDB.listTransactions(); + expect(response, isA()); + }); + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createTransaction(); + expect(response, isA()); + }); - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - test('test method decrementRowColumn()', () async { + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method deleteTransaction()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + test('test method listRows()', () async { + final Map data = { + 'total': 5, + 'rows': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + }); - }); + test('test method createRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + }); - test('test method incrementRowColumn()', () async { + test('test method getRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method upsertRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); + test('test method updateRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteRow()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); - }); + test('test method decrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + }); + test('test method incrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index ea72a432..83f2667b 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,326 +40,288 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; - - setUp(() { - client = MockClient(); - teams = Teams(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'teams': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.list( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method delete()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.delete( - teamId: '', - ); - }); - - test('test method listMemberships()', () async { - - final Map data = { - 'total': 5, - 'memberships': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + group('Teams test', () { + late MockClient client; + late Teams teams; + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method createMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - - }); - - test('test method getMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - - }); - - test('test method updateMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); - - }); - - test('test method deleteMembership()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'teams': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + final response = await teams.list(); + expect(response, isA()); + }); - test('test method updateMembershipStatus()', () async { + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); + }); + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method delete()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); + final response = await teams.delete( + teamId: '', + ); + }); - }); + test('test method listMemberships()', () async { + final Map data = { + 'total': 5, + 'memberships': [], + }; - test('test method getPrefs()', () async { + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final Map data = {}; + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + }); + test('test method createMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + }); + test('test method updateMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + }); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); + test('test method deleteMembership()', () async { + final data = ''; - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updatePrefs()', () async { + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); - final Map data = {}; + test('test method updateMembershipStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + }); + test('test method getPrefs()', () async { + final Map data = {}; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); + test('test method updatePrefs()', () async { + final Map data = {}; - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); }); + }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 15e85f5a..261daa46 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 87a3ca3c..3da36624 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index 3b842e6c..e58fa5b5 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 49b1e22c..3bcbb488 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index dd7fa8c3..b2084927 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,16 +8,18 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index c7d9cdbf..8c131568 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index ae58b57e..d080569c 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index 8de695b0..e71dcae1 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index d5242a4e..85e559f5 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 869f5db6..6df5c584 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index bc66ab7b..d5404a7f 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index 09da675c..d7410db8 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 29890008..00e046c7 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index f1a5b3cc..217d37e8 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 6c1fbb77..397b5fab 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index cb10c58e..8d209722 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -13,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 6d9bf33c..80ef508a 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index d8e6c95c..8e02f65e 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 8a734a08..7f132646 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -24,20 +24,20 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 489891d4..9252b469 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 65f562a7..8c35afec 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 708c8c60..525af4ea 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index e616a956..93376af1 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,13 +5,15 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index 94c1e33f..a07c0b5f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index d4087d5e..4a6c96c1 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index b6de5137..65b44ad1 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index f0fcdbce..88cf157b 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 72102045..49cb1fc9 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index 84c560c8..b07ca8ee 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index 1b463633..c8211d3b 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index bb1f0946..4f30c48e 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index ab136c24..b2b8bd3d 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 9410baa3..5d3febca 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index ed6467d3..64cc55e4 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index fa097a49..500913c8 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 3f45d288..81657394 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,14 +6,16 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index 6ca46a63..bf22a5c7 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index d0e5333b..f70db0e3 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index acde349c..9db30b03 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,7 +10,6 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); - }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 57a86348..46f69af6 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index edcfe5f5..ef2ebe31 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index d4900dd4..12693926 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 4e72a449..564bf303 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index eaab249e..708e0583 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 0177e477..689e6048 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 94c6a502..7445514c 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index a49f3def..49f1e75e 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index a19b667d..fe2f4a85 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index 43b2e45c..f652f2c1 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 7ee4b268..8f0957c9 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index 68023e18..a524ef71 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 723ebac2..0169427f 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index c058ea26..77c7dd97 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From 1c0fb53fd8970f94aceab855be5c7ebc8489f27c Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 13 Jul 2026 12:09:30 +0530 Subject: [PATCH 03/17] chore: update Flutter SDK to 25.3.0 --- lib/appwrite.dart | 2 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/operator.dart | 11 +- lib/query.dart | 89 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1560 +++++----- lib/services/avatars.dart | 351 +-- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/presences.dart | 182 +- lib/services/storage.dart | 342 +-- lib/services/tables_db.dart | 547 ++-- lib/services/teams.dart | 421 ++- lib/src/client.dart | 4 +- lib/src/client_base.dart | 2 + lib/src/client_browser.dart | 18 +- lib/src/client_io.dart | 18 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 98 +- lib/src/enums/timezone.dart | 848 +++--- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 194 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 243 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +-- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 + test/services/account_test.dart | 2691 +++++++++-------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 585 ++-- test/services/functions_test.dart | 188 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 253 +- test/services/messaging_test.dart | 122 +- test/services/presences_test.dart | 202 +- test/services/storage_test.dart | 341 ++- test/services/tables_db_test.dart | 585 ++-- test/services/teams_test.dart | 555 ++-- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 6 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 30 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 + test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 166 files changed, 8731 insertions(+), 8580 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index ae51be5e..6615de8a 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/channel.dart b/lib/channel.dart index afc68efa..d511f5a4 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,33 +2,19 @@ part of appwrite; // Marker classes for type safety class _Root {} - class _Database {} - class _Collection {} - class _Document {} - class _TablesDB {} - class _Table {} - class _Row {} - class _Bucket {} - class _File {} - class _Func {} - class _Execution {} - class _Team {} - class _Membership {} - class _Presence {} - class _Resolved {} // Helper function for normalizing ID @@ -113,15 +99,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => - _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => _next<_Table>('tables', id); + Channel<_Table> table(String id) => + _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/operator.dart b/lib/operator.dart index 337dda30..9dd7f4c7 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if (values != null) { + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -147,7 +147,8 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => Operator._('arrayUnique', []).toString(); + static String arrayUnique() => + Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -172,7 +173,8 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => Operator._('toggle', []).toString(); + static String toggle() => + Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -183,5 +185,6 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => Operator._('dateSetNow', []).toString(); + static String dateSetNow() => + Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 2772116a..2221a6e6 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if (attribute != null) { + + if(attribute != null) { result['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,46 +140,50 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => lessThan('\$createdAt', value); + static String createdBefore(String value) => + lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => greaterThan('\$createdAt', value); + static String createdAfter(String value) => + greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => lessThan('\$updatedAt', value); + static String updatedBefore(String value) => + lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => + greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -194,17 +198,18 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => Query._('orderRandom').toString(); + static String orderRandom() => + Query._('orderRandom').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(); /// 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) => @@ -214,43 +219,27 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceNotEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceLessThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); /// Filter resources using vector dot product similarity. static String vectorDot(String attribute, List vector) => 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..3f91a53a 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 48b60041..9c021e93 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; -/// The Account service allows you to authenticate and manage a user account. + /// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,17 +9,18 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -29,30 +30,29 @@ class Account extends Service { /// 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 { + Future create({required String userId, required String email, required String password, String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - if (name != null) 'name': name, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + 'password': password, + + if (name != null) 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Update currently logged in user account email address. After changing user @@ -62,65 +62,66 @@ class Account extends Service { /// 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 { + /// + Future updateEmail({required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities( - {List? queries, bool? total}) async { + Future listIdentities({List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); - return models.IdentityList.fromMap(res.data); } /// Delete an identity by its unique ID. Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -131,20 +132,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, - }; + final Map apiParams = { + if (duration != null) 'duration': duration, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); - return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -152,224 +153,212 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.LogList.fromMap(res.data); - return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - }; + final Map apiParams = { + 'mfa': mfa, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// 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); + Future createMFAAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } /// 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); + 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 apiParams = { - 'otp': otp, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// 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 String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -377,27 +366,26 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, + + 'otp': otp, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -405,83 +393,84 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge( - {required String challengeId, required String otp}) async { + Future updateMFAChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'otp': otp, - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -491,17 +480,18 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -509,23 +499,22 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -536,41 +525,40 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -580,62 +568,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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 { + Future updatePassword({required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, - if (oldPassword != null) 'oldPassword': oldPassword, - }; + final Map apiParams = { + 'password': password, + + if (oldPassword != null) 'oldPassword': oldPassword, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -643,42 +631,43 @@ class Account extends Service { /// 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 { + Future updatePhone({required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, - 'password': password, - }; + final Map apiParams = { + 'phone': phone, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'password': password, - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -687,20 +676,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, - }; + final Map apiParams = { + 'prefs': prefs, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -711,25 +700,25 @@ class Account extends Service { /// /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 { + Future createRecovery({required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - 'url': url, - }; + final Map apiParams = { + 'email': email, + + 'url': url, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -737,33 +726,32 @@ class Account extends Service { /// 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 { + Future updateRecovery({required String userId, required String secret, required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + 'password': password, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -771,17 +759,18 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.SessionList.fromMap(res.data); - return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -789,17 +778,18 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -812,216 +802,213 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession({required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + /// + 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 = { + + if (success != null) 'success': success, + + if (failure != null) 'failure': failure, + + if (scopes != null) '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); + } + } 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); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1030,20 +1017,20 @@ class Account extends Service { /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1052,18 +1039,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1071,28 +1058,27 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - if (providerId != null) 'providerId': providerId, - }; + final Map apiParams = { + 'targetId': targetId, + + 'identifier': identifier, + + if (providerId != null) 'providerId': providerId, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1100,45 +1086,43 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + 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 apiParams = { - 'identifier': identifier, - }; + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1150,31 +1134,32 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken({required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'email': email, - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + if (phrase != null) 'phrase': phrase, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1186,88 +1171,87 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (url != null) 'url': url, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + if (url != null) 'url': url, + + if (phrase != null) 'phrase': phrase, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + 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 = { + + if (success != null) 'success': success, + + if (failure != null) 'failure': failure, + + if (scopes != null) '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); + } + } 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); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1276,29 +1260,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken({required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; + final Map apiParams = { + 'userId': userId, + + 'phone': phone, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1310,29 +1294,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1344,83 +1328,81 @@ class Account extends Service { /// 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. - /// - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 updateEmailVerification( - {required String userId, required String secret}) async { + Future updateEmailVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1434,42 +1416,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } } diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index cdd93e6e..4dca3b16 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Avatars service aims to help you complete everyday tasks related to -/// your app image, icons, and avatars. + /// 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); @@ -11,134 +11,139 @@ class Avatars extends Service { /// /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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { final String apiPath = '/avatars/favicon'; - final Map params = { - 'url': url, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; + final Map params = { + + 'url': url, - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + Future getImage({required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map params = { - 'url': url, - if (width != null) 'width': width, - if (height != null) 'height': height, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'url': url, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to show your user initials avatar icon on your website or @@ -146,117 +151,125 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map params = { - if (name != null) 'name': name, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (background != null) 'background': background, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + if (name != null) 'name': name, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (background != null) 'background': background, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map params = { - 'text': text, - if (size != null) 'size': size, - if (margin != null) 'margin': margin, - if (download != null) 'download': download, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'text': text, + + if (size != null) 'size': size, + + if (margin != null) 'margin': margin, + + if (download != null) 'download': download, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot( - {required String url, - Map? headers, - int? viewportWidth, - int? viewportHeight, - double? scale, - enums.BrowserTheme? theme, - String? userAgent, - bool? fullpage, - String? locale, - enums.Timezone? timezone, - double? latitude, - double? longitude, - double? accuracy, - bool? touch, - List? permissions, - int? sleep, - int? width, - int? height, - int? quality, - enums.ImageFormat? output}) async { + Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map params = { - 'url': url, - if (headers != null) 'headers': headers, - if (viewportWidth != null) 'viewportWidth': viewportWidth, - if (viewportHeight != null) 'viewportHeight': viewportHeight, - if (scale != null) 'scale': scale, - if (theme != null) 'theme': theme.value, - if (userAgent != null) 'userAgent': userAgent, - if (fullpage != null) 'fullpage': fullpage, - if (locale != null) 'locale': locale, - if (timezone != null) 'timezone': timezone.value, - if (latitude != null) 'latitude': latitude, - if (longitude != null) 'longitude': longitude, - if (accuracy != null) 'accuracy': accuracy, - if (touch != null) 'touch': touch, - if (permissions != null) - 'permissions': permissions.map((e) => e.value).toList(), - if (sleep != null) 'sleep': sleep, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - if (output != null) 'output': output.value, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + + 'url': url, + + if (headers != null) 'headers': headers, + + if (viewportWidth != null) 'viewportWidth': viewportWidth, + + if (viewportHeight != null) 'viewportHeight': viewportHeight, + + if (scale != null) 'scale': scale, + + if (theme != null) 'theme': theme.value, + + if (userAgent != null) 'userAgent': userAgent, + + if (fullpage != null) 'fullpage': fullpage, + + if (locale != null) 'locale': locale, + + if (timezone != null) 'timezone': timezone.value, + + if (latitude != null) 'latitude': latitude, + + if (longitude != null) 'longitude': longitude, + + if (accuracy != null) 'accuracy': accuracy, + + if (touch != null) 'touch': touch, + + if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), + + if (sleep != null) 'sleep': sleep, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + if (output != null) 'output': output.value, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + 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 0ff3fb72..0bfd935a 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,418 +1,339 @@ part of '../appwrite.dart'; -/// The Databases service allows you to create structured collections of -/// documents, query and filter lists of documents + /// 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 transactions across all databases. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions( - {List? queries}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions({List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction({required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + + 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Create or update a 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Delete a document by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + 'min': min, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Increment a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + 'max': max, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index ed97921b..0640f80f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,87 +1,82 @@ part of '../appwrite.dart'; -/// The Functions Service allows you view, create and manage your Cloud -/// Functions. + /// The Functions Service allows you view, create and manage your Cloud + /// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); + Future listExecutions({required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); - return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - if (xasync != null) 'async': xasync, - if (path != null) 'path': path, - if (method != null) 'method': method.value, - if (headers != null) 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); + 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 = { + if (body != null) 'body': body, + + if (xasync != null) 'async': xasync, + + if (path != null) 'path': path, + + if (method != null) 'method': method.value, + + if (headers != null) 'headers': headers, + + 'scheduledAt': scheduledAt, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Execution.fromMap(res.data); - return models.Execution.fromMap(res.data); } } diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index c86f3719..978331fa 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The GraphQL API allows you to query and mutate your Appwrite server using -/// GraphQL. + /// 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); @@ -10,41 +10,39 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 87ea162e..c45a1269 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Locale service allows you to customize your app based on your users' -/// location. + /// 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); @@ -10,22 +10,23 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all locale codes in [ISO @@ -33,17 +34,18 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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 of all continents. You can use the locale header to get the data in a @@ -51,17 +53,18 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.ContinentList.fromMap(res.data); - return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -69,17 +72,18 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries that are currently members of the EU. You can use the @@ -87,17 +91,18 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries phone codes. You can use the locale header to get the @@ -105,17 +110,18 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -124,17 +130,18 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -142,16 +149,17 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.LanguageList.fromMap(res.data); - return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 61ecefee..3dffe41b 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,54 +1,48 @@ part of '../appwrite.dart'; -/// The Messaging service allows you to send messages to any provider type -/// (SMTP, push notification, SMS, etc.). + /// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 1c9b651b..088700cb 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -5,127 +5,123 @@ class Presences extends Service { Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list( - {List? queries, bool? total, int? ttl}) async { + /// + Future list({List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.PresenceList.fromMap(res.data); - return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Presence.fromMap(res.data); - return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert( - {required String presenceId, - required String status, - List? permissions, - String? expiresAt, - Map? metadata}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - if (permissions != null) 'permissions': permissions, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + + if (permissions != null) 'permissions': permissions, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update( - {required String presenceId, - String? status, - String? expiresAt, - Map? metadata, - List? permissions, - bool? purge}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - if (permissions != null) 'permissions': permissions, - if (purge != null) 'purge': purge, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + if (permissions != null) 'permissions': permissions, + + if (purge != null) 'purge': purge, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/storage.dart b/lib/services/storage.dart index cdb626de..c9499a99 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,178 +1,166 @@ part of '../appwrite.dart'; -/// The Storage service allows you to manage your project files. + /// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, - bool? total}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); + Future listFiles({required String bucketId, List? queries, String? search, bool? total}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } /// 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, - if (permissions != null) 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', - 'accept': 'application/json', - }; - - 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); + /// + 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, + + if (permissions != null) 'permissions': permissions, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', 'accept': 'application/json', + }; + + 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 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); + 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 apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.File.fromMap(res.data); - return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); + 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 = { + if (name != null) 'name': name, + + 'permissions': permissions, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileDownload({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Get a file preview image. Currently, this method supports preview for image @@ -180,64 +168,60 @@ class Storage extends Service { /// 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, - String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (gravity != null) 'gravity': gravity.value, - if (quality != null) 'quality': quality, - if (borderWidth != null) 'borderWidth': borderWidth, - if (borderColor != null) 'borderColor': borderColor, - if (borderRadius != null) 'borderRadius': borderRadius, - if (opacity != null) 'opacity': opacity, - if (rotation != null) 'rotation': rotation, - if (background != null) 'background': background, - if (output != null) 'output': output.value, - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (gravity != null) 'gravity': gravity.value, + + if (quality != null) 'quality': quality, + + if (borderWidth != null) 'borderWidth': borderWidth, + + if (borderColor != null) 'borderColor': borderColor, + + if (borderRadius != null) 'borderRadius': borderRadius, + + if (opacity != null) 'opacity': opacity, + + if (rotation != null) 'rotation': rotation, + + if (background != null) 'background': background, + + if (output != null) 'output': output.value, + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileView({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + if (token != null) 'token': token, + + + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 8b6284b3..42572021 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -5,382 +5,319 @@ class TablesDB extends Service { TablesDB(super.client); /// List transactions across all databases. - Future listTransactions( - {List? queries}) async { + Future listTransactions({List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future getTransaction({required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; - final Map apiParams = { - if (operations != null) 'operations': operations, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows( - {required String databaseId, - required String tableId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); + Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); + } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow( - {required String databaseId, - required String tableId, - required String rowId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + + 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow( - {required String databaseId, - required String tableId, - required String rowId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + 'permissions': permissions, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Delete a row by its unique ID. - Future deleteRow( - {required String databaseId, - required String tableId, - required String rowId, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + 'min': min, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Increment a specific column of a row by a given value. - Future incrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + 'max': max, + + 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 1f4022f6..27bc561e 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,97 +1,98 @@ 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 + /// 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); /// 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, bool? total}) async { + Future list({List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (search != null) 'search': search, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); - return models.TeamList.fromMap(res.data); } /// 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 { + Future create({required String teamId, required String name, List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - 'name': name, - if (roles != null) 'roles': roles, - }; + final Map apiParams = { + 'teamId': teamId, + + 'name': name, + + if (roles != null) 'roles': roles, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// 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 apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { + Future updateName({required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -99,45 +100,44 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships( - {required String teamId, - List? queries, - String? search, - bool? total}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); + Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -146,199 +146,180 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - if (userId != null) 'userId': userId, - if (phone != null) 'phone': phone, - 'roles': roles, - if (url != null) 'url': url, - if (name != null) 'name': name, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + if (email != null) 'email': email, + + if (userId != null) 'userId': userId, + + if (phone != null) 'phone': phone, + + 'roles': roles, + + if (url != null) 'url': url, + + if (name != null) 'name': name, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); + 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 apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Membership.fromMap(res.data); - return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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 String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// 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); + 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 apiParams = { - 'prefs': prefs, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } } diff --git a/lib/src/client.dart b/lib/src/client.dart index dbfe4bdf..c75dc37b 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -113,6 +112,7 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); + /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f10f0955..6794a5a2 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -14,6 +14,7 @@ abstract class ClientBase implements Client { /// The OAuth access token to authenticate with @override ClientBase setBearer(value); + @override ClientBase setLocale(value); @@ -41,6 +42,7 @@ abstract class ClientBase implements Client { @override ClientBase setImpersonateUserPhone(value); + @override ClientBase setSelfSigned({bool status = true}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 4c4662e3..350b5cab 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -62,7 +62,6 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -70,22 +69,19 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - /// The OAuth access token to authenticate with @override ClientBrowser setBearer(value) { config['bearer'] = value; - addHeader('Authorization', value); + addHeader('Authorization', 'Bearer $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) { @@ -93,7 +89,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -101,7 +96,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -109,7 +103,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -117,7 +110,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -125,7 +117,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -235,8 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk( - int index, int start, int end, String? id) async { + Future uploadChunk(int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -274,9 +264,7 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f95e4157..d8cb8e7f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -88,7 +88,6 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -96,22 +95,19 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - /// The OAuth access token to authenticate with @override ClientIO setBearer(value) { config['bearer'] = value; - addHeader('Authorization', value); + addHeader('Authorization', 'Bearer $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) { @@ -119,7 +115,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -127,7 +122,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -135,7 +129,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -143,7 +136,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -151,7 +143,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -410,9 +401,7 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -436,8 +425,7 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = - file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 89aad359..40484946 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,6 +12,7 @@ mixin ClientMixin { required Map headers, required Map params, }) { + http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -127,13 +128,9 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response( - '', + return http.Response('', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index fb4983db..765b3e0c 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,30 +1,32 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({required this.value}); + const BrowserPermission({ + 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_theme.dart b/lib/src/enums/browser_theme.dart index 1e059c2c..e81a0f68 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,12 +1,14 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({required this.value}); + const BrowserTheme({ + 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 28c2a1b3..4d6bce3a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,27 +1,29 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 44de4907..6ad112fe 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index 7ea9865e..f54859c9 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({required this.value}); + const ExecutionStatus({ + 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_trigger.dart b/lib/src/enums/execution_trigger.dart index fb05eb7d..8a14ae60 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,13 +1,15 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({required this.value}); + const ExecutionTrigger({ + 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 55f4c5db..0f996ed9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 6c8dbc70..77cad38c 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,54 +1,56 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index d5d8d94a..4a8de1ce 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,429 +1,431 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({required this.value}); + const Timezone({ + 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 c6974573..683e6387 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 344a8770..f80fa854 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 9909265e..c51da4bb 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 746fbd52..43523ab1 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index cab45e49..8562c4e3 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index a1648843..8e844839 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 33ef4a6f..5202db05 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 4984df75..3d08af9f 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index ec3c41be..930900bf 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index df28f04b..753bcacc 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3bcbb76d..c4838ba3 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 79cb1256..f363a54b 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 f2b18093..b6bb455f 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 6c39ae2e..eb2bad19 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 be08d599..0d1fdeb0 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 76a07309..0e30844a 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,33 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3629e1d6..3e767ca3 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,129 +2,125 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values - .firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values - .firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 63c2ad7e..45b60682 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 01cdcb3a..9e5f9eb1 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,101 +2,101 @@ 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; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - 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.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + 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.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 1157554a..84c54b2e 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa054420..bbccf88a 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index cc659043..7e90020c 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 a5d39ea0..d9cc09a2 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 cda66c70..2000acb6 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 87dc3606..1422d065 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 6198d61e..5d78a367 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 c29b9e25..926e352d 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,126 +2,125 @@ 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; - - /// City - final String? city; - - /// Name of timezone - final String? timeZone; - - /// Postal code - final String? postalCode; - - /// Latitude - final double? latitude; - - /// Longitude - final double? longitude; - - /// Autonomous System Number (ASN) of the IP - final String? autonomousSystemNumber; - - /// Organization that owns the ASN - final String? autonomousSystemOrganization; - - /// Internet service provider of the IP - final String? isp; - - /// Connection type of the IP (e.g. cable, cellular, corporate) - final String? connectionType; - - /// User type classification of the IP (e.g. residential, business, hosting) - final String? connectionUsageType; - - /// Registered organization of the IP - final String? connectionOrganization; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - this.city, - this.timeZone, - this.postalCode, - this.latitude, - this.longitude, - this.autonomousSystemNumber, - this.autonomousSystemOrganization, - this.isp, - this.connectionType, - this.connectionUsageType, - this.connectionOrganization, - }); - - 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(), - city: map['city']?.toString(), - timeZone: map['timeZone']?.toString(), - postalCode: map['postalCode']?.toString(), - latitude: map['latitude']?.toDouble(), - longitude: map['longitude']?.toDouble(), - autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), - autonomousSystemOrganization: - map['autonomousSystemOrganization']?.toString(), - isp: map['isp']?.toString(), - connectionType: map['connectionType']?.toString(), - connectionUsageType: map['connectionUsageType']?.toString(), - connectionOrganization: map['connectionOrganization']?.toString(), - ); - } - - @override - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - "city": city, - "timeZone": timeZone, - "postalCode": postalCode, - "latitude": latitude, - "longitude": longitude, - "autonomousSystemNumber": autonomousSystemNumber, - "autonomousSystemOrganization": autonomousSystemOrganization, - "isp": isp, - "connectionType": connectionType, - "connectionUsageType": connectionUsageType, - "connectionOrganization": connectionOrganization, - }; - } + /// 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 21405aff..49ef3b0b 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 202355a4..a3a26b61 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 d754130d..ac4eacf3 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 3494b111..ebf593c2 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4d8a2f9b..4baffb71 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index cc664c9f..a0641a28 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa385541..3d2e2335 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 2777de7f..a7e5fefc 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 864a5db8..33036476 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index fe5327fc..05cab363 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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 60e2abd9..7ac578e2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 1a197fc7..9791d590 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3ca04118..b107afe5 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index d31911de..133fe66d 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index 3d010b1c..aebbe880 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: - List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index a825eab0..c5f233b4 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 5023c633..90efa95f 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 92e4034e..c37de95a 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 4ea12394..d823d0e6 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 450aafd1..850ab8d2 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 c2e8c4dc..742e7590 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 91b888b9..21e65e95 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 e8f1c621..ffca5e98 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b5ea87c8..b05320da 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index b0606dd8..e3f3e43d 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 7f321175..19ea651d 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from( - map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5a6cad30..e3b9536b 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 28e4c43d..7a5e6303 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..83f01b4c 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 72edf5ee..6cebb5b1 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,7 +58,9 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({"type": "ping"})); + _websok!.sink.add(jsonEncode({ + "type": "ping" + })); } }); } @@ -138,11 +140,9 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; + final subscriptions = (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? []; if (subscriptions.isEmpty) { break; @@ -209,15 +209,13 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = - "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -312,11 +310,9 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = - channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -333,7 +329,8 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update({List? channels, List? queries}) async { + Future update( + {List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -420,4 +417,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} +} \ No newline at end of file diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index b0356111..56e7669a 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/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..ce0b7e95 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', - ); + 'Cannot create a client without dart:html or dart:io.', +); diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..62031aec 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,22 +13,12 @@ void main() { }); test('returns database channel with action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -44,12 +34,7 @@ void main() { }); test('returns tablesdb channel with action', () { - expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), + expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -62,16 +47,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + expect(Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -98,30 +83,29 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index db7b9214..25388fad 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,3 +354,4 @@ void main() { expect(query['method'], 'between'); }); } + diff --git a/test/services/account_test.dart b/test/services/account_test.dart index d5d61fe7..bd65aa32 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,1356 +41,1540 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; + group('Account test', () { + late MockClient client; + late Account account; + + setUp(() { + client = MockClient(); + account = Account(client); + }); + + test('test method get()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.get( + ); + expect(response, isA()); - setUp(() { - client = MockClient(); - account = Account(client); - }); + }); + + test('test method create()', () async { - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.get(); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); - test('test method updateEmail()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method listIdentities()', () async { - final Map data = { - 'total': 5, - 'identities': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - final response = await account.listIdentities(); - expect(response, isA()); - }); + }); - test('test method deleteIdentity()', () async { - final data = ''; + test('test method updateEmail()', () async { - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - final response = await account.deleteIdentity( - identityId: '', - ); - }); - test('test method createJWT()', () async { - final Map data = { - 'jwt': - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.createJWT(); - expect(response, isA()); - }); + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - test('test method listLogs()', () async { - final Map data = { - 'total': 5, - 'logs': [], - }; + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listIdentities()', () async { - final response = await account.listLogs(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'identities': [],}; - test('test method updateMFA()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - }); - test('test method createMfaAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createMFAAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); - test('test method updateMfaAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); + final response = await account.listIdentities( + ); + expect(response, isA()); - test('test method updateMFAAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); + }); - test('test method deleteMfaAuthenticator()', () async { - final data = ''; + test('test method deleteIdentity()', () async { - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final data = ''; - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteMFAAuthenticator()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteIdentity( + identityId: '', + ); + }); - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + test('test method createJWT()', () async { - test('test method createMfaChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); + final Map data = { + 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',}; - test('test method createMFAChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); - test('test method updateMfaChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMFAChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); - test('test method listMfaFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final response = await account.createJWT( + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.listMfaFactors(); - expect(response, isA()); - }); + test('test method listLogs()', () async { - test('test method listMFAFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final Map data = { + 'total': 5, + 'logs': [],}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.listMFAFactors(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listLogs( + ); + expect(response, isA()); - final response = await account.getMfaRecoveryCodes(); - expect(response, isA()); - }); + }); - test('test method getMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + test('test method updateMFA()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - final response = await account.getMFARecoveryCodes(); - expect(response, isA()); - }); - test('test method createMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.createMfaRecoveryCodes(); - expect(response, isA()); - }); + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); - test('test method createMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method createMfaAuthenticator()', () async { - final response = await account.createMFARecoveryCodes(); - expect(response, isA()); - }); + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - test('test method updateMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.updateMfaRecoveryCodes(); - expect(response, isA()); - }); - test('test method updateMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.updateMFARecoveryCodes(); - expect(response, isA()); - }); + test('test method createMFAAuthenticator()', () async { - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - }); + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - test('test method updatePassword()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - }); - test('test method updatePhone()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method getPrefs()', () async { - final Map data = {}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); - final response = await account.getPrefs(); - expect(response, isA()); - }); + }); - test('test method updatePrefs()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - }); + test('test method updateMfaAuthenticator()', () async { - test('test method createRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method updateRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); - }); - test('test method listSessions()', () async { - final Map data = { - 'total': 5, - 'sessions': [], - }; + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.listSessions(); - expect(response, isA()); - }); + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); - test('test method deleteSessions()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFAAuthenticator()', () async { - final response = await account.deleteSessions(); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createAnonymousSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createAnonymousSession(); - expect(response, isA()); - }); - test('test method createEmailPasswordSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMagicURLSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); - test('test method createOAuth2Session()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); + }); - test('test method updatePhoneSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + test('test method deleteMfaAuthenticator()', () async { - test('test method createSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + final data = ''; - test('test method getSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - }); - test('test method deleteSession()', () async { - final data = ''; + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteMFAAuthenticator()', () async { - final response = await account.deleteSession( - sessionId: '', - ); - }); + final data = ''; - test('test method updateStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateStatus(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method createPushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); - test('test method updatePushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + + test('test method createMfaChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method createMFAChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method updateMfaChallenge()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method deletePushTarget()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.deletePushTarget( - targetId: '', - ); - }); - test('test method createEmailToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); - test('test method createMagicURLToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + }); - test('test method createOAuth2Token()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + test('test method updateMFAChallenge()', () async { - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createPhoneToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); - }); - test('test method createEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - test('test method createVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); - test('test method updateEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); - test('test method updateVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + }); - test('test method createPhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneVerification(); - expect(response, isA()); - }); + test('test method listMfaFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMfaFactors( + ); + expect(response, isA()); + + }); + + test('test method listMFAFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMFAFactors( + ); + expect(response, isA()); + + }); + + test('test method getMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method getMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + + }); + + test('test method updatePassword()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updatePhone()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getPrefs( + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + + }); + + test('test method createRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method listSessions()', () async { + + final Map data = { + 'total': 5, + 'sessions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listSessions( + ); + expect(response, isA()); + + }); + + test('test method deleteSessions()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSessions( + ); + }); + + test('test method createAnonymousSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createAnonymousSession( + ); + expect(response, isA()); + + }); + + test('test method createEmailPasswordSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updateMagicURLSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Session()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method updatePhoneSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSession()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSession( + sessionId: '', + ); + }); + + test('test method updateStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateStatus( + ); + expect(response, isA()); + + }); + + test('test method createPushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true,}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method updatePushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true,}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method deletePushTarget()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deletePushTarget( + targetId: '', + ); + }); + + test('test method createEmailToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createMagicURLToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Token()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method createPhoneToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + + }); + + test('test method createEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method createVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method updateVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createPhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneVerification( + ); + expect(response, isA()); + + }); + + test('test method updatePhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); - test('test method updatePhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 8d2c48fb..4bdb434d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,123 +41,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); - test('test method getBrowser()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getBrowser()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - }); - test('test method getCreditCard()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - }); + test('test method getCreditCard()', () async { +final Uint8List data = Uint8List.fromList([]); - test('test method getFavicon()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - }); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); - test('test method getFlag()', () async { - final Uint8List data = Uint8List.fromList([]); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFavicon()', () async { +final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getImage()', () async { - final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); - }); + }); - test('test method getInitials()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getFlag()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials(); - expect(response, isA()); - }); - test('test method getQR()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); + + test('test method getImage()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method getInitials()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getInitials( + ); + expect(response, isA()); + + }); + + test('test method getQR()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + + }); + + test('test method getScreenshot()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); - }); - test('test method getScreenshot()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a3807093..a4b0a6cc 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,337 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; + group('Databases test', () { + late MockClient client; + late Databases databases; - setUp(() { - client = MockClient(); - databases = Databases(client); - }); + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [],}; - final response = await databases.listTransactions(); - expect(response, isA()); - }); - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createTransaction(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + final response = await databases.listTransactions( + ); + expect(response, isA()); - test('test method deleteTransaction()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createTransaction()', () async { - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method listDocuments()', () async { - final Map data = { - 'total': 5, - 'documents': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method createDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + final response = await databases.createTransaction( + ); + expect(response, isA()); - test('test method upsertDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + test('test method getTransaction()', () async { - test('test method deleteDocument()', () async { - final data = ''; + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method decrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); - }); - test('test method incrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listDocuments()', () async { + + final Map data = { + 'total': 5, + 'documents': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + + }); + + test('test method createDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method updateDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteDocument()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); + + test('test method decrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); + + test('test method incrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); + }); - }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index c6e50a50..9b0d046f 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,100 +41,107 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; + group('Functions test', () { + late MockClient client; + late Functions functions; - setUp(() { - client = MockClient(); - functions = Functions(client); - }); + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - test('test method listExecutions()', () async { - final Map data = { - 'total': 5, - 'executions': [], - }; + test('test method listExecutions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'executions': [],}; - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - }); - test('test method createExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method createExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4,}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method getExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4,}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); + + }); - test('test method getExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 84b7de1c..c548e414 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,45 +41,47 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method query()', () async { - final data = ''; + test('test method query()', () async { - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final data = ''; - final response = await graphql.query( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await graphql.query( + query: {}, + ); + }); + + test('test method mutation()', () async { + + final data = ''; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method mutation()', () async { - final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); + }); - final response = await graphql.mutation( - query: {}, - ); }); - }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index f9f6489d..42faaf72 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,138 +41,168 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; + group('Locale test', () { + late MockClient client; + late Locale locale; - setUp(() { - client = MockClient(); - locale = Locale(client); - }); + setUp(() { + client = MockClient(); + locale = Locale(client); + }); - test('test method get()', () async { - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await locale.get(); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method listCodes()', () async { - final Map data = { - 'total': 5, - 'localeCodes': [], - }; + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD',}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCodes(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method listContinents()', () async { - final Map data = { - 'total': 5, - 'continents': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.get( + ); + expect(response, isA()); - final response = await locale.listContinents(); - expect(response, isA()); - }); + }); - test('test method listCountries()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + test('test method listCodes()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'localeCodes': [],}; - final response = await locale.listCountries(); - expect(response, isA()); - }); - test('test method listCountriesEU()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCountriesEU(); - expect(response, isA()); - }); + final response = await locale.listCodes( + ); + expect(response, isA()); - test('test method listCountriesPhones()', () async { - final Map data = { - 'total': 5, - 'phones': [], - }; + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listContinents()', () async { - final response = await locale.listCountriesPhones(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'continents': [],}; - test('test method listCurrencies()', () async { - final Map data = { - 'total': 5, - 'currencies': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listContinents( + ); + expect(response, isA()); + + }); + + test('test method listCountries()', () async { + + final Map data = { + 'total': 5, + 'countries': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountries( + ); + expect(response, isA()); + + }); + + test('test method listCountriesEU()', () async { + + final Map data = { + 'total': 5, + 'countries': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesEU( + ); + expect(response, isA()); + + }); + + test('test method listCountriesPhones()', () async { + + final Map data = { + 'total': 5, + 'phones': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesPhones( + ); + expect(response, isA()); + + }); + + test('test method listCurrencies()', () async { + + final Map data = { + 'total': 5, + 'currencies': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCurrencies( + ); + expect(response, isA()); + + }); + + test('test method listLanguages()', () async { + + final Map data = { + 'total': 5, + 'languages': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCurrencies(); - expect(response, isA()); - }); - test('test method listLanguages()', () async { - final Map data = { - 'total': 5, - 'languages': [], - }; + final response = await locale.listLanguages( + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await locale.listLanguages(); - expect(response, isA()); }); - }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 0c938eff..5899ace3 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,68 +41,71 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; + group('Messaging test', () { + late MockClient client; + late Messaging messaging; - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - test('test method createSubscriber()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - }); + test('test method createSubscriber()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSubscriber()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteSubscriber()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); + }); - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); }); - }); } diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7fed0439..7b99675f 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,108 +41,121 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; + group('Presences test', () { + late MockClient client; + late Presences presences; - setUp(() { - client = MockClient(); - presences = Presences(client); - }); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'presences': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'presences': [],}; - final response = await presences.list(); - expect(response, isA()); - }); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method upsert()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - }); - test('test method update()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); - }); + final response = await presences.list( + ); + expect(response, isA()); + + }); + + test('test method get()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method upsert()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + + }); + + test('test method update()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method delete()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); + }); - final response = await presences.delete( - presenceId: '', - ); }); - }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 55a42f94..2390bfdd 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,184 +41,202 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; + group('Storage test', () { + late MockClient client; + late Storage storage; + + setUp(() { + client = MockClient(); + storage = Storage(client); + }); + + test('test method listFiles()', () async { + + final Map data = { + 'total': 5, + 'files': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); + + }); + + test('test method createFile()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; + - setUp(() { - client = MockClient(); - storage = Storage(client); - }); + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); - test('test method listFiles()', () async { - final Map data = { - 'total': 5, - 'files': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + + }); - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - }); + test('test method getFile()', () async { - test('test method createFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; - test('test method getFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method updateFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteFile()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + }); - test('test method getFileDownload()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method updateFile()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip',}; - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method getFilePreview()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteFile()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + + test('test method getFileDownload()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFilePreview()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFileView()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + - test('test method getFileView()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index f318cad2..5219d2bf 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,337 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [],}; - final response = await tablesDB.listTransactions(); - expect(response, isA()); - }); - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createTransaction(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + final response = await tablesDB.listTransactions( + ); + expect(response, isA()); - test('test method deleteTransaction()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createTransaction()', () async { - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method listRows()', () async { - final Map data = { - 'total': 5, - 'rows': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method createRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + final response = await tablesDB.createTransaction( + ); + expect(response, isA()); - test('test method upsertRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + test('test method getTransaction()', () async { - test('test method deleteRow()', () async { - final data = ''; + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method decrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); - }); - test('test method incrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listRows()', () async { + + final Map data = { + 'total': 5, + 'rows': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + + }); + + test('test method createRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method updateRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteRow()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); + + test('test method decrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); + + test('test method incrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); + }); - }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index 83f2667b..ea72a432 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,288 +41,326 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; + group('Teams test', () { + late MockClient client; + late Teams teams; - setUp(() { - client = MockClient(); - teams = Teams(client); - }); + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'teams': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'teams': [],}; - final response = await teams.list(); - expect(response, isA()); - }); - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - }); - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - }); + final response = await teams.list( + ); + expect(response, isA()); - test('test method delete()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method create()', () async { - final response = await teams.delete( - teamId: '', - ); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; - test('test method listMemberships()', () async { - final Map data = { - 'total': 5, - 'memberships': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - }); - test('test method createMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - }); + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); - test('test method getMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - }); + }); - test('test method updateMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method deleteMembership()', () async { - final data = ''; + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMembershipStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); - }); - test('test method getPrefs()', () async { - final Map data = {}; + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {},}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.delete( + teamId: '', + ); + }); + + test('test method listMemberships()', () async { + + final Map data = { + 'total': 5, + 'memberships': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method createMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method getMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + + }); + + test('test method updateMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method deleteMembership()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); + + test('test method updateMembershipStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [],}; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = {}; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); - }); - test('test method updatePrefs()', () async { - final Map data = {}; + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); }); - }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 261daa46..15e85f5a 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 3da36624..87a3ca3c 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index e58fa5b5..3b842e6c 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 3bcbb488..49b1e22c 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index b2084927..dd7fa8c3 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,18 +8,16 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index 8c131568..c7d9cdbf 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index d080569c..ae58b57e 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index e71dcae1..8de695b0 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index 85e559f5..d5242a4e 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 6df5c584..869f5db6 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index d5404a7f..bc66ab7b 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index d7410db8..09da675c 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 00e046c7..29890008 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index 217d37e8..f1a5b3cc 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 397b5fab..6c1fbb77 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index 8d209722..cb10c58e 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -13,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 80ef508a..6d9bf33c 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index 8e02f65e..d8e6c95c 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 7f132646..8a734a08 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -24,20 +24,20 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 9252b469..489891d4 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 8c35afec..65f562a7 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 525af4ea..708c8c60 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index 93376af1..e616a956 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,15 +5,13 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index a07c0b5f..94c1e33f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index 4a6c96c1..d4087d5e 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index 65b44ad1..b6de5137 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index 88cf157b..f0fcdbce 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 49cb1fc9..72102045 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index b07ca8ee..84c560c8 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index c8211d3b..1b463633 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index 4f30c48e..bb1f0946 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index b2b8bd3d..ab136c24 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 5d3febca..9410baa3 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index 64cc55e4..ed6467d3 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index 500913c8..fa097a49 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 81657394..3f45d288 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,16 +6,14 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index bf22a5c7..6ca46a63 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index f70db0e3..d0e5333b 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index 9db30b03..acde349c 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,6 +10,7 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); + }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 46f69af6..57a86348 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index ef2ebe31..edcfe5f5 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index 12693926..d4900dd4 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 564bf303..4e72a449 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index 708e0583..eaab249e 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 689e6048..0177e477 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 7445514c..94c6a502 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index 49f1e75e..a49f3def 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index fe2f4a85..a19b667d 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index f652f2c1..43b2e45c 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 8f0957c9..7ee4b268 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index a524ef71..68023e18 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 0169427f..723ebac2 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index 77c7dd97..c058ea26 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From 4f7e2d4e37be648863632ed2263efcc99e41a416 Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Mon, 13 Jul 2026 06:40:57 +0000 Subject: [PATCH 04/17] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/operator.dart | 11 +- lib/query.dart | 89 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1560 +++++----- lib/services/avatars.dart | 351 ++- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/presences.dart | 182 +- lib/services/storage.dart | 342 ++- lib/services/tables_db.dart | 547 ++-- lib/services/teams.dart | 421 +-- lib/src/client.dart | 4 +- lib/src/client_base.dart | 1 - lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 16 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 ++- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 98 +- lib/src/enums/timezone.dart | 848 +++--- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 194 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 243 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +-- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 - test/services/account_test.dart | 2691 ++++++++--------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 585 ++-- test/services/functions_test.dart | 188 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 253 +- test/services/messaging_test.dart | 122 +- test/services/presences_test.dart | 202 +- test/services/storage_test.dart | 341 +-- test/services/tables_db_test.dart | 585 ++-- test/services/teams_test.dart | 555 ++-- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 6 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 30 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 - test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 166 files changed, 8578 insertions(+), 8728 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index 6615de8a..ae51be5e 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/channel.dart b/lib/channel.dart index d511f5a4..afc68efa 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,19 +2,33 @@ part of appwrite; // Marker classes for type safety class _Root {} + class _Database {} + class _Collection {} + class _Document {} + class _TablesDB {} + class _Table {} + class _Row {} + class _Bucket {} + class _File {} + class _Func {} + class _Execution {} + class _Team {} + class _Membership {} + class _Presence {} + class _Resolved {} // Helper function for normalizing ID @@ -99,15 +113,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => + _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => - _next<_Table>('tables', id); + Channel<_Table> table(String id) => _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/operator.dart b/lib/operator.dart index 9dd7f4c7..337dda30 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if(values != null) { + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -147,8 +147,7 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => - Operator._('arrayUnique', []).toString(); + static String arrayUnique() => Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -173,8 +172,7 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => - Operator._('toggle', []).toString(); + static String toggle() => Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -185,6 +183,5 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => - Operator._('dateSetNow', []).toString(); + static String dateSetNow() => Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 2221a6e6..2772116a 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if(attribute != null) { + + if (attribute != null) { result['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,50 +140,46 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => - lessThan('\$createdAt', value); + static String createdBefore(String value) => lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => - greaterThan('\$createdAt', value); + static String createdAfter(String value) => greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => - lessThan('\$updatedAt', value); + static String updatedBefore(String value) => lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => - greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -198,18 +194,17 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => - Query._('orderRandom').toString(); + static String orderRandom() => Query._('orderRandom').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(); /// 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) => @@ -219,27 +214,43 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceNotEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceNotEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); + static String distanceGreaterThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); + static String distanceLessThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceLessThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources using vector dot product similarity. static String vectorDot(String attribute, List vector) => 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 3f91a53a..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 9c021e93..48b60041 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; - /// The Account service allows you to authenticate and manage a user account. +/// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,18 +9,17 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -30,29 +29,30 @@ class Account extends Service { /// 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 { + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - 'password': password, - - if (name != null) 'name': name, - - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + if (name != null) 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Update currently logged in user account email address. After changing user @@ -62,66 +62,65 @@ class Account extends Service { /// 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 { + /// + Future updateEmail( + {required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - - 'password': password, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'email': email, + 'password': password, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries, bool? total}) async { + Future listIdentities( + {List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.IdentityList.fromMap(res.data); } /// 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 String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -132,20 +131,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, + final Map apiParams = { + if (duration != null) 'duration': duration, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -153,212 +152,224 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'mfa': mfa, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// 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 = { - }; + Future createMFAAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); } /// 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, - - }; + Future updateMFAAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'otp': otp, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'factor': factor.value, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, + final Map apiParams = { + 'factor': factor.value, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -366,26 +377,27 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge({required String challengeId, required String otp}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - - 'otp': otp, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -393,84 +405,83 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge({required String challengeId, required String otp}) async { + Future updateMFAChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - 'otp': otp, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -480,18 +491,17 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -499,22 +509,23 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -525,40 +536,41 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -568,62 +580,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - - }; + final Map apiParams = { + 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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 { + Future updatePassword( + {required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, - - if (oldPassword != null) 'oldPassword': oldPassword, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'password': password, + if (oldPassword != null) 'oldPassword': oldPassword, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -631,43 +643,42 @@ class Account extends Service { /// 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 { + Future updatePhone( + {required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, + final Map apiParams = { + 'phone': phone, + 'password': password, + }; - 'password': password, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -676,20 +687,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, + final Map apiParams = { + 'prefs': prefs, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -700,25 +711,25 @@ class Account extends Service { /// /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 { + Future createRecovery( + {required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - - 'url': url, - - }; + final Map apiParams = { + 'email': email, + 'url': url, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -726,32 +737,33 @@ class Account extends Service { /// 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 { + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - 'password': password, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -759,18 +771,17 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.SessionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -778,18 +789,17 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -802,213 +812,216 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession( + {required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - - 'password': password, + final Map apiParams = { + 'email': email, + 'password': password, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + /// + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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); + } + } 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); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1017,20 +1030,20 @@ class Account extends Service { /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1039,18 +1052,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1058,27 +1071,28 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - - 'identifier': identifier, - - if (providerId != null) 'providerId': providerId, - - }; + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + if (providerId != null) 'providerId': providerId, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1086,43 +1100,45 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, + 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1134,32 +1150,31 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, + final Map apiParams = { + 'userId': userId, + 'email': email, + if (phrase != null) 'phrase': phrase, + }; - 'email': email, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - if (phrase != null) 'phrase': phrase, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1171,87 +1186,88 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - if (url != null) 'url': url, - - if (phrase != null) 'phrase': phrase, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + if (url != null) 'url': url, + if (phrase != null) 'phrase': phrase, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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); + } + } 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); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1260,29 +1276,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken( + {required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, - - 'phone': phone, + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1294,29 +1310,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'url': url, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1328,81 +1344,83 @@ class Account extends Service { /// 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. - /// - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, + final Map apiParams = { + 'url': url, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 updateEmailVerification({required String userId, required String secret}) async { + Future updateEmailVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1416,42 +1434,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + 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 4dca3b16..cdd93e6e 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Avatars service aims to help you complete everyday tasks related to - /// your app image, icons, and avatars. +/// 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); @@ -11,139 +11,134 @@ class Avatars extends Service { /// /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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { final String apiPath = '/avatars/favicon'; - final Map params = { - - 'url': url, + final Map params = { + 'url': url, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + Future getImage( + {required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map params = { - - 'url': url, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'url': url, + if (width != null) 'width': width, + if (height != null) 'height': height, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to show your user initials avatar icon on your website or @@ -151,125 +146,117 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map params = { - - if (name != null) 'name': name, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (background != null) 'background': background, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + if (name != null) 'name': name, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (background != null) 'background': background, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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 { + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map params = { - - 'text': text, - - if (size != null) 'size': size, - - if (margin != null) 'margin': margin, - - if (download != null) 'download': download, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'text': text, + if (size != null) 'size': size, + if (margin != null) 'margin': margin, + if (download != null) 'download': download, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { + Future getScreenshot( + {required String url, + Map? headers, + int? viewportWidth, + int? viewportHeight, + double? scale, + enums.BrowserTheme? theme, + String? userAgent, + bool? fullpage, + String? locale, + enums.Timezone? timezone, + double? latitude, + double? longitude, + double? accuracy, + bool? touch, + List? permissions, + int? sleep, + int? width, + int? height, + int? quality, + enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map params = { - - 'url': url, - - if (headers != null) 'headers': headers, - - if (viewportWidth != null) 'viewportWidth': viewportWidth, - - if (viewportHeight != null) 'viewportHeight': viewportHeight, - - if (scale != null) 'scale': scale, - - if (theme != null) 'theme': theme.value, - - if (userAgent != null) 'userAgent': userAgent, - - if (fullpage != null) 'fullpage': fullpage, - - if (locale != null) 'locale': locale, - - if (timezone != null) 'timezone': timezone.value, - - if (latitude != null) 'latitude': latitude, - - if (longitude != null) 'longitude': longitude, - - if (accuracy != null) 'accuracy': accuracy, - - if (touch != null) 'touch': touch, - - if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), - - if (sleep != null) 'sleep': sleep, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - if (output != null) 'output': output.value, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map params = { + 'url': url, + if (headers != null) 'headers': headers, + if (viewportWidth != null) 'viewportWidth': viewportWidth, + if (viewportHeight != null) 'viewportHeight': viewportHeight, + if (scale != null) 'scale': scale, + if (theme != null) 'theme': theme.value, + if (userAgent != null) 'userAgent': userAgent, + if (fullpage != null) 'fullpage': fullpage, + if (locale != null) 'locale': locale, + if (timezone != null) 'timezone': timezone.value, + if (latitude != null) 'latitude': latitude, + if (longitude != null) 'longitude': longitude, + if (accuracy != null) 'accuracy': accuracy, + if (touch != null) 'touch': touch, + if (permissions != null) + 'permissions': permissions.map((e) => e.value).toList(), + if (sleep != null) 'sleep': sleep, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + if (output != null) 'output': output.value, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + 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 0bfd935a..0ff3fb72 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,339 +1,418 @@ part of '../appwrite.dart'; - /// The Databases service allows you to create structured collections of - /// documents, query and filter lists of documents +/// 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 transactions across all databases. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions({List? queries}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions( + {List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - - 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Create or update a 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Delete a document by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - 'min': min, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + 'min': min, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Increment a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - 'max': max, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + 'max': max, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 0640f80f..ed97921b 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,82 +1,87 @@ part of '../appwrite.dart'; - /// The Functions Service allows you view, create and manage your Cloud - /// Functions. +/// The Functions Service allows you view, create and manage your Cloud +/// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + Future listExecutions( + {required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - - if (xasync != null) 'async': xasync, - - if (path != null) 'path': path, - - if (method != null) 'method': method.value, - - if (headers != null) 'headers': headers, - - 'scheduledAt': scheduledAt, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - + 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 = { + if (body != null) 'body': body, + if (xasync != null) 'async': xasync, + if (path != null) 'path': path, + if (method != null) 'method': method.value, + if (headers != null) 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); } /// 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 = { - }; + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Execution.fromMap(res.data); + 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 978331fa..c86f3719 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The GraphQL API allows you to query and mutate your Appwrite server using - /// GraphQL. +/// 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); @@ -10,39 +10,41 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, + final Map apiParams = { + 'query': query, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'query': query, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + 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 c45a1269..87ea162e 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Locale service allows you to customize your app based on your users' - /// location. +/// 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); @@ -10,23 +10,22 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Locale.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Locale.fromMap(res.data); } /// List of all locale codes in [ISO @@ -34,18 +33,17 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); } /// List of all continents. You can use the locale header to get the data in a @@ -53,18 +51,17 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ContinentList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -72,18 +69,17 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all countries that are currently members of the EU. You can use the @@ -91,18 +87,17 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - 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 of all countries phone codes. You can use the locale header to get the @@ -110,18 +105,17 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.PhoneList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -130,18 +124,17 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -149,17 +142,16 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LanguageList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 3dffe41b..61ecefee 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,48 +1,54 @@ part of '../appwrite.dart'; - /// The Messaging service allows you to send messages to any provider type - /// (SMTP, push notification, SMS, etc.). +/// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); } /// 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 = { - }; + 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 apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 088700cb..1c9b651b 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -5,123 +5,127 @@ class Presences extends Service { Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list({List? queries, bool? total, int? ttl}) async { + /// + Future list( + {List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.PresenceList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - - if (permissions != null) 'permissions': permissions, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future upsert( + {required String presenceId, + required String status, + List? permissions, + String? expiresAt, + Map? metadata}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + if (permissions != null) 'permissions': permissions, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - if (permissions != null) 'permissions': permissions, - - if (purge != null) 'purge': purge, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future update( + {required String presenceId, + String? status, + String? expiresAt, + Map? metadata, + List? permissions, + bool? purge}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + if (permissions != null) 'permissions': permissions, + if (purge != null) 'purge': purge, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - }; + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + 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 c9499a99..cdb626de 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,166 +1,178 @@ part of '../appwrite.dart'; - /// The Storage service allows you to manage your project files. +/// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, bool? total}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - + Future listFiles( + {required String bucketId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); } /// 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, - - if (permissions != null) 'permissions': permissions, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', 'accept': 'application/json', - }; - - 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); - + /// + 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, + if (permissions != null) 'permissions': permissions, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + 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 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); + 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 apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - - 'permissions': permissions, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - + 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 = { + if (name != null) 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileDownload( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// Get a file preview image. Currently, this method supports preview for image @@ -168,60 +180,64 @@ class Storage extends Service { /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (gravity != null) 'gravity': gravity.value, - - if (quality != null) 'quality': quality, - - if (borderWidth != null) 'borderWidth': borderWidth, - - if (borderColor != null) 'borderColor': borderColor, - - if (borderRadius != null) 'borderRadius': borderRadius, - - if (opacity != null) 'opacity': opacity, - - if (rotation != null) 'rotation': rotation, - - if (background != null) 'background': background, - - if (output != null) 'output': output.value, - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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, + String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (gravity != null) 'gravity': gravity.value, + if (quality != null) 'quality': quality, + if (borderWidth != null) 'borderWidth': borderWidth, + if (borderColor != null) 'borderColor': borderColor, + if (borderRadius != null) 'borderRadius': borderRadius, + if (opacity != null) 'opacity': opacity, + if (rotation != null) 'rotation': rotation, + if (background != null) 'background': background, + if (output != null) 'output': output.value, + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - if (token != null) 'token': token, - - - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileView( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + if (token != null) 'token': token, + 'project': client.config['project'], + 'impersonateuserid': client.config['impersonateuserid'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 42572021..8b6284b3 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -5,319 +5,382 @@ class TablesDB extends Service { TablesDB(super.client); /// List transactions across all databases. - Future listTransactions({List? queries}) async { + Future listTransactions( + {List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + if (operations != null) 'operations': operations, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); - + Future listRows( + {required String databaseId, + required String tableId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - - 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future createRow( + {required String databaseId, + required String tableId, + required String rowId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future getRow( + {required String databaseId, + required String tableId, + required String rowId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future upsertRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - 'permissions': permissions, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future updateRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + 'permissions': permissions, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Delete a row by its unique ID. - Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + Future deleteRow( + {required String databaseId, + required String tableId, + required String rowId, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - 'min': min, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future decrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + 'min': min, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Increment a specific column of a row by a given value. - Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - 'max': max, - - 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future incrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + 'max': max, + 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 27bc561e..1f4022f6 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,98 +1,97 @@ 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 +/// 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); /// 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, bool? total}) async { + Future list( + {List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; - if (search != null) 'search': search, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TeamList.fromMap(res.data); } /// 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 { + Future create( + {required String teamId, + required String name, + List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - - 'name': name, - - if (roles != null) 'roles': roles, - - }; + final Map apiParams = { + 'teamId': teamId, + 'name': name, + if (roles != null) 'roles': roles, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { + Future updateName( + {required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, - - }; + final Map apiParams = { + 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -100,44 +99,45 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - + Future listMemberships( + {required String teamId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -146,180 +146,199 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - - if (userId != null) 'userId': userId, - - if (phone != null) 'phone': phone, - - 'roles': roles, - - if (url != null) 'url': url, - - if (name != null) 'name': name, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + if (email != null) 'email': email, + if (userId != null) 'userId': userId, + if (phone != null) 'phone': phone, + 'roles': roles, + if (url != null) 'url': url, + if (name != null) 'name': name, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + 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 apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 = { - }; + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// 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, - - }; + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'prefs': prefs, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + 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 c75dc37b..dbfe4bdf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,7 +27,8 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => + createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -112,7 +113,6 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); - /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 6794a5a2..9e6cf566 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -42,7 +42,6 @@ abstract class ClientBase implements Client { @override ClientBase setImpersonateUserPhone(value); - @override ClientBase setSelfSigned({bool status = true}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 350b5cab..38cee6bb 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -62,6 +62,7 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -69,6 +70,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientBrowser setBearer(value) { @@ -76,12 +78,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -89,6 +93,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -96,6 +101,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -103,6 +109,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -110,6 +117,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -117,6 +125,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -226,7 +235,8 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id) async { + Future uploadChunk( + int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -264,7 +274,9 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index d8cb8e7f..a4cae30f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -88,6 +88,7 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -95,6 +96,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientIO setBearer(value) { @@ -102,12 +104,14 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -115,6 +119,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -122,6 +127,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -129,6 +135,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -136,6 +143,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -143,6 +151,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -401,7 +410,9 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -425,7 +436,8 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = + file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 40484946..89aad359 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,7 +12,6 @@ mixin ClientMixin { required Map headers, required Map params, }) { - http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -128,9 +127,13 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response('', + return http.Response( + '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index 765b3e0c..fb4983db 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,32 +1,30 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({ - required this.value - }); + const BrowserPermission({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_theme.dart b/lib/src/enums/browser_theme.dart index e81a0f68..1e059c2c 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,14 +1,12 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({ - required this.value - }); + const BrowserTheme({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 4d6bce3a..28c2a1b3 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,29 +1,27 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 6ad112fe..44de4907 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index f54859c9..7ea9865e 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({ - required this.value - }); + const ExecutionStatus({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_trigger.dart b/lib/src/enums/execution_trigger.dart index 8a14ae60..fb05eb7d 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,15 +1,13 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({ - required this.value - }); + const ExecutionTrigger({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 0f996ed9..55f4c5db 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 77cad38c..6c8dbc70 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,56 +1,54 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index 4a8de1ce..d5d8d94a 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,431 +1,429 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({ - required this.value - }); + const Timezone({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 683e6387..c6974573 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 f80fa854..344a8770 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 c51da4bb..9909265e 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 43523ab1..746fbd52 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 8562c4e3..cab45e49 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 8e844839..a1648843 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 5202db05..33ef4a6f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 3d08af9f..4984df75 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 930900bf..ec3c41be 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index 753bcacc..df28f04b 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 c4838ba3..3bcbb76d 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index f363a54b..79cb1256 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b6bb455f..f2b18093 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 eb2bad19..6c39ae2e 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 0d1fdeb0..be08d599 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 0e30844a..76a07309 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,33 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3e767ca3..3629e1d6 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,125 +2,129 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values + .firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values + .firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 45b60682..63c2ad7e 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 9e5f9eb1..01cdcb3a 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,101 +2,101 @@ 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; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - 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.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + 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.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 84c54b2e..1157554a 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 bbccf88a..fa054420 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 7e90020c..cc659043 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 d9cc09a2..a5d39ea0 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 2000acb6..cda66c70 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 1422d065..87dc3606 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 5d78a367..6198d61e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 926e352d..c29b9e25 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,125 +2,126 @@ 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; - - /// City - final String? city; - - /// Name of timezone - final String? timeZone; - - /// Postal code - final String? postalCode; - - /// Latitude - final double? latitude; - - /// Longitude - final double? longitude; - - /// Autonomous System Number (ASN) of the IP - final String? autonomousSystemNumber; - - /// Organization that owns the ASN - final String? autonomousSystemOrganization; - - /// Internet service provider of the IP - final String? isp; - - /// Connection type of the IP (e.g. cable, cellular, corporate) - final String? connectionType; - - /// User type classification of the IP (e.g. residential, business, hosting) - final String? connectionUsageType; - - /// Registered organization of the IP - final String? connectionOrganization; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - this.city, - this.timeZone, - this.postalCode, - this.latitude, - this.longitude, - this.autonomousSystemNumber, - this.autonomousSystemOrganization, - this.isp, - this.connectionType, - this.connectionUsageType, - this.connectionOrganization, - }); - - 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(), - city: map['city']?.toString(), - timeZone: map['timeZone']?.toString(), - postalCode: map['postalCode']?.toString(), - latitude: map['latitude']?.toDouble(), - longitude: map['longitude']?.toDouble(), - autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), - autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), - isp: map['isp']?.toString(), - connectionType: map['connectionType']?.toString(), - connectionUsageType: map['connectionUsageType']?.toString(), - connectionOrganization: map['connectionOrganization']?.toString(), - ); - } - - @override - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - "city": city, - "timeZone": timeZone, - "postalCode": postalCode, - "latitude": latitude, - "longitude": longitude, - "autonomousSystemNumber": autonomousSystemNumber, - "autonomousSystemOrganization": autonomousSystemOrganization, - "isp": isp, - "connectionType": connectionType, - "connectionUsageType": connectionUsageType, - "connectionOrganization": connectionOrganization, - }; - } + /// 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: + map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 49ef3b0b..21405aff 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 a3a26b61..202355a4 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 ac4eacf3..d754130d 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 ebf593c2..3494b111 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4baffb71..4d8a2f9b 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index a0641a28..cc664c9f 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3d2e2335..fa385541 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 a7e5fefc..2777de7f 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 33036476..864a5db8 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 05cab363..fe5327fc 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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 7ac578e2..60e2abd9 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 9791d590..1a197fc7 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b107afe5..3ca04118 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index 133fe66d..d31911de 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index aebbe880..3d010b1c 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: + List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index c5f233b4..a825eab0 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 90efa95f..5023c633 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index c37de95a..92e4034e 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 d823d0e6..4ea12394 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 850ab8d2..450aafd1 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 742e7590..c2e8c4dc 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 21e65e95..91b888b9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 ffca5e98..e8f1c621 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b05320da..b5ea87c8 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index e3f3e43d..b0606dd8 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 19ea651d..7f321175 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from( + map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index e3b9536b..5a6cad30 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 7a5e6303..28e4c43d 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 83f01b4c..0ed367a6 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 6cebb5b1..72edf5ee 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,9 +58,7 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({ - "type": "ping" - })); + _websok!.sink.add(jsonEncode({"type": "ping"})); } }); } @@ -140,9 +138,11 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? []; + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; if (subscriptions.isEmpty) { break; @@ -209,13 +209,15 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = + "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse( + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -310,9 +312,11 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, + [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = + channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -329,8 +333,7 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update( - {List? channels, List? queries}) async { + Future update({List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -417,4 +420,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} \ No newline at end of file +} diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index 56e7669a..b0356111 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 diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index ce0b7e95..3aab4e03 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', -); + 'Cannot create a client without dart:html or dart:io.', + ); diff --git a/test/channel_test.dart b/test/channel_test.dart index 62031aec..9e0e11d3 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,12 +13,22 @@ void main() { }); test('returns database channel with action', () { - expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .create() + .toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .upsert() + .toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -34,7 +44,12 @@ void main() { }); test('returns tablesdb channel with action', () { - expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + expect( + Channel.tablesdb('db1') + .table('table1') + .row('row1') + .update() + .toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -47,16 +62,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect(Channel.bucket('bucket1').file().toString(), - 'buckets.bucket1.files'); + expect( + Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -83,29 +98,30 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), + 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index 25388fad..db7b9214 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,4 +354,3 @@ void main() { expect(query['method'], 'between'); }); } - diff --git a/test/services/account_test.dart b/test/services/account_test.dart index bd65aa32..d5d61fe7 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,1540 +40,1356 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; - - setUp(() { - client = MockClient(); - account = Account(client); - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.get( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updateEmail()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method listIdentities()', () async { - - final Map data = { - 'total': 5, - 'identities': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listIdentities( - ); - expect(response, isA()); - - }); - - test('test method deleteIdentity()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteIdentity( - identityId: '', - ); - }); - - test('test method createJWT()', () async { - - final Map data = { - 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createJWT( - ); - expect(response, isA()); - - }); - - test('test method listLogs()', () async { - - final Map data = { - 'total': 5, - 'logs': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listLogs( - ); - expect(response, isA()); - - }); - - test('test method updateMFA()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - - }); - - test('test method createMfaAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method createMFAAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method updateMfaAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method deleteMfaAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method deleteMFAAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method createMfaChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method createMFAChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method updateMfaChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method listMfaFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true,}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMfaFactors( - ); - expect(response, isA()); - - }); - - test('test method listMFAFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true,}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMFAFactors( - ); - expect(response, isA()); - - }); - - test('test method getMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method getMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - + group('Account test', () { + late MockClient client; + late Account account; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - - }); - - test('test method updatePassword()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updatePhone()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method getPrefs()', () async { - - final Map data = {}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getPrefs( - ); - expect(response, isA()); - - }); - - test('test method updatePrefs()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - - }); - - test('test method createRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method updateRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + account = Account(client); + }); + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.get(); + expect(response, isA()); + }); - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); - }); + test('test method updateEmail()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); - test('test method listSessions()', () async { - - final Map data = { - 'total': 5, - 'sessions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listSessions( - ); - expect(response, isA()); - - }); - - test('test method deleteSessions()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteSessions( - ); - }); - - test('test method createAnonymousSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createAnonymousSession( - ); - expect(response, isA()); - - }); - - test('test method createEmailPasswordSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updateMagicURLSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createOAuth2Session()', () async { - - - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); - - - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - - }); - - test('test method updatePhoneSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method getSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSession()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteSession( - sessionId: '', - ); - }); - - test('test method updateStatus()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00',}; + test('test method listIdentities()', () async { + final Map data = { + 'total': 5, + 'identities': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listIdentities(); + expect(response, isA()); + }); + test('test method deleteIdentity()', () async { + final data = ''; - final response = await account.updateStatus( - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteIdentity( + identityId: '', + ); + }); - test('test method createPushTarget()', () async { + test('test method createJWT()', () async { + final Map data = { + 'jwt': + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + }; - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true,}; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.createJWT(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method listLogs()', () async { + final Map data = { + 'total': 5, + 'logs': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + final response = await account.listLogs(); + expect(response, isA()); + }); - }); + test('test method updateMFA()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); + }); - test('test method updatePushTarget()', () async { + test('test method createMfaAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true,}; + test('test method createMFAAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); + test('test method updateMfaAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFAAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); + test('test method deleteMfaAuthenticator()', () async { + final data = ''; - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - test('test method deletePushTarget()', () async { + test('test method deleteMFAAuthenticator()', () async { + final data = ''; - final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + test('test method createMfaChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - final response = await account.deletePushTarget( - targetId: '', - ); - }); + test('test method createMFAChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - test('test method createEmailToken()', () async { + test('test method updateMfaChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updateMFAChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); + test('test method listMfaFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.listMfaFactors(); + expect(response, isA()); + }); - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + test('test method listMFAFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createMagicURLToken()', () async { + final response = await account.listMFAFactors(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method getMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.getMfaRecoveryCodes(); + expect(response, isA()); + }); + test('test method getMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.getMFARecoveryCodes(); + expect(response, isA()); + }); - test('test method createOAuth2Token()', () async { + test('test method createMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final response = await account.createMfaRecoveryCodes(); + expect(response, isA()); + }); + test('test method createMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.createMFARecoveryCodes(); + expect(response, isA()); + }); - test('test method createPhoneToken()', () async { + test('test method updateMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.updateMfaRecoveryCodes(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); + final response = await account.updateMFARecoveryCodes(); + expect(response, isA()); + }); - }); + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + }); - test('test method createEmailVerification()', () async { + test('test method updatePassword()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updatePhone()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + }); + test('test method getPrefs()', () async { + final Map data = {}; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.getPrefs(); + expect(response, isA()); + }); - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method updatePrefs()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + }); - }); + test('test method createRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + }); - test('test method createVerification()', () async { + test('test method updateRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method listSessions()', () async { + final Map data = { + 'total': 5, + 'sessions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listSessions(); + expect(response, isA()); + }); + test('test method deleteSessions()', () async { + final data = ''; - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteSessions(); + }); - test('test method updateEmailVerification()', () async { + test('test method createAnonymousSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createAnonymousSession(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method createEmailPasswordSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); + test('test method updateMagicURLSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createOAuth2Session()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updatePhoneSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - test('test method updateVerification()', () async { + test('test method getSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method updateSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + }); + test('test method deleteSession()', () async { + final data = ''; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteSession( + sessionId: '', + ); + }); - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateStatus(); + expect(response, isA()); + }); - }); + test('test method createPushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); - test('test method createPhoneVerification()', () async { + test('test method updatePushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method deletePushTarget()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deletePushTarget( + targetId: '', + ); + }); + test('test method createEmailToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - final response = await account.createPhoneVerification( - ); - expect(response, isA()); + test('test method createMagicURLToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - }); + test('test method createOAuth2Token()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); - test('test method updatePhoneVerification()', () async { + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox',}; + test('test method createPhoneToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + }); + test('test method createEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method updateEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createPhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneVerification(); + expect(response, isA()); + }); + test('test method updatePhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 4bdb434d..8d2c48fb 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,138 +40,123 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; - - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); - - test('test method getBrowser()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - - }); - - test('test method getCreditCard()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - - }); - - test('test method getFavicon()', () async { -final Uint8List data = Uint8List.fromList([]); + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method getFlag()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); + test('test method getBrowser()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); + }); - test('test method getImage()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getCreditCard()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); + }); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getFavicon()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getInitials()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFlag()', () async { + final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials( - ); - expect(response, isA()); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); + }); - }); + test('test method getImage()', () async { + final Uint8List data = Uint8List.fromList([]); - test('test method getQR()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method getInitials()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getInitials(); + expect(response, isA()); + }); - test('test method getScreenshot()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getQR()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getScreenshot()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a4b0a6cc..a3807093 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,337 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; - - setUp(() { - client = MockClient(); - databases = Databases(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listDocuments()', () async { - - final Map data = { - 'total': 5, - 'documents': [],}; - + group('Databases test', () { + late MockClient client; + late Databases databases; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - - }); - - test('test method createDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method updateDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - test('test method deleteDocument()', () async { + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; - final data = ''; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await databases.listTransactions(); + expect(response, isA()); + }); + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createTransaction(); + expect(response, isA()); + }); - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - test('test method decrementDocumentAttribute()', () async { + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method deleteTransaction()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + test('test method listDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + }); - }); + test('test method createDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + }); - test('test method incrementDocumentAttribute()', () async { + test('test method getDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method upsertDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); + test('test method updateDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteDocument()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); - }); + test('test method decrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + }); + test('test method incrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 9b0d046f..c6e50a50 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,107 +40,100 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; - - setUp(() { - client = MockClient(); - functions = Functions(client); - }); - - test('test method listExecutions()', () async { - - final Map data = { - 'total': 5, - 'executions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method createExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4,}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method getExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4,}; + group('Functions test', () { + late MockClient client; + late Functions functions; + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listExecutions()', () async { + final Map data = { + 'total': 5, + 'executions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + }); - }); + test('test method createExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + }); + test('test method getExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index c548e414..84b7de1c 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,47 +40,45 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; - - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); - - test('test method query()', () async { - - final data = ''; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await graphql.query( - query: {}, - ); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method mutation()', () async { + test('test method query()', () async { + final data = ''; - final data = ''; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.query( + query: {}, + ); + }); + test('test method mutation()', () async { + final data = ''; - final response = await graphql.mutation( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); }); + }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index 42faaf72..f9f6489d 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,168 +40,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; - - setUp(() { - client = MockClient(); - locale = Locale(client); - }); - - test('test method get()', () async { - - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.get( - ); - expect(response, isA()); - - }); - - test('test method listCodes()', () async { - - final Map data = { - 'total': 5, - 'localeCodes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCodes( - ); - expect(response, isA()); - - }); - - test('test method listContinents()', () async { - - final Map data = { - 'total': 5, - 'continents': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listContinents( - ); - expect(response, isA()); + group('Locale test', () { + late MockClient client; + late Locale locale; - }); - - test('test method listCountries()', () async { - - final Map data = { - 'total': 5, - 'countries': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountries( - ); - expect(response, isA()); - - }); - - test('test method listCountriesEU()', () async { - - final Map data = { - 'total': 5, - 'countries': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountriesEU( - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + locale = Locale(client); + }); - test('test method listCountriesPhones()', () async { + test('test method get()', () async { + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await locale.get(); + expect(response, isA()); + }); - final Map data = { - 'total': 5, - 'phones': [],}; + test('test method listCodes()', () async { + final Map data = { + 'total': 5, + 'localeCodes': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCodes(); + expect(response, isA()); + }); + test('test method listContinents()', () async { + final Map data = { + 'total': 5, + 'continents': [], + }; - final response = await locale.listCountriesPhones( - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await locale.listContinents(); + expect(response, isA()); + }); - test('test method listCurrencies()', () async { + test('test method listCountries()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; - final Map data = { - 'total': 5, - 'currencies': [],}; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCountries(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listCountriesEU()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCurrencies( - ); - expect(response, isA()); + final response = await locale.listCountriesEU(); + expect(response, isA()); + }); - }); + test('test method listCountriesPhones()', () async { + final Map data = { + 'total': 5, + 'phones': [], + }; - test('test method listLanguages()', () async { + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final Map data = { - 'total': 5, - 'languages': [],}; + final response = await locale.listCountriesPhones(); + expect(response, isA()); + }); + test('test method listCurrencies()', () async { + final Map data = { + 'total': 5, + 'currencies': [], + }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCurrencies(); + expect(response, isA()); + }); - final response = await locale.listLanguages( - ); - expect(response, isA()); + test('test method listLanguages()', () async { + final Map data = { + 'total': 5, + 'languages': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listLanguages(); + expect(response, isA()); }); + }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 5899ace3..0c938eff 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,71 +40,68 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; - - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); - - test('test method createSubscriber()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + group('Messaging test', () { + late MockClient client; + late Messaging messaging; + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSubscriber()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createSubscriber()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + }); + test('test method deleteSubscriber()', () async { + final data = ''; - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); }); + }); } diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7b99675f..7fed0439 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,121 +40,108 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; - - setUp(() { - client = MockClient(); - presences = Presences(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'presences': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.list( - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - - }); + group('Presences test', () { + late MockClient client; + late Presences presences; - test('test method upsert()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - - }); - - test('test method update()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'presences': [], + }; - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await presences.list(); + expect(response, isA()); + }); - test('test method delete()', () async { + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + }); - final data = ''; + test('test method upsert()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method update()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + }); + test('test method delete()', () async { + final data = ''; - final response = await presences.delete( - presenceId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); }); + }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 2390bfdd..55a42f94 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,202 +40,184 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; - - setUp(() { - client = MockClient(); - storage = Storage(client); - }); - - test('test method listFiles()', () async { - - final Map data = { - 'total': 5, - 'files': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - - }); - - test('test method createFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - - }); - - test('test method getFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method updateFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip',}; - + group('Storage test', () { + late MockClient client; + late Storage storage; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteFile()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + storage = Storage(client); + }); + test('test method listFiles()', () async { + final Map data = { + 'total': 5, + 'files': [], + }; - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getFileDownload()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method createFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + test('test method getFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method updateFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - }); + test('test method deleteFile()', () async { + final data = ''; - test('test method getFilePreview()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + test('test method getFileDownload()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - test('test method getFileView()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getFilePreview()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method getFileView()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 5219d2bf..f318cad2 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,337 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; - - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00',}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listRows()', () async { - - final Map data = { - 'total': 5, - 'rows': [],}; - + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - - }); - - test('test method createRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method updateRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - test('test method deleteRow()', () async { + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; - final data = ''; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await tablesDB.listTransactions(); + expect(response, isA()); + }); + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createTransaction(); + expect(response, isA()); + }); - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - test('test method decrementRowColumn()', () async { + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method deleteTransaction()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + test('test method listRows()', () async { + final Map data = { + 'total': 5, + 'rows': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + }); - }); + test('test method createRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + }); - test('test method incrementRowColumn()', () async { + test('test method getRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [],}; + test('test method upsertRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); + test('test method updateRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteRow()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); - }); + test('test method decrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + }); + test('test method incrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index ea72a432..83f2667b 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,326 +40,288 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; - - setUp(() { - client = MockClient(); - teams = Teams(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'teams': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.list( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {},}; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method delete()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.delete( - teamId: '', - ); - }); - - test('test method listMemberships()', () async { - - final Map data = { - 'total': 5, - 'memberships': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + group('Teams test', () { + late MockClient client; + late Teams teams; + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method createMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - - }); - - test('test method getMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - - }); - - test('test method updateMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); - - }); - - test('test method deleteMembership()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'teams': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + final response = await teams.list(); + expect(response, isA()); + }); - test('test method updateMembershipStatus()', () async { + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [],}; + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); + }); + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method delete()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); + final response = await teams.delete( + teamId: '', + ); + }); - }); + test('test method listMemberships()', () async { + final Map data = { + 'total': 5, + 'memberships': [], + }; - test('test method getPrefs()', () async { + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final Map data = {}; + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + }); + test('test method createMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + }); + test('test method updateMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + }); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); + test('test method deleteMembership()', () async { + final data = ''; - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updatePrefs()', () async { + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); - final Map data = {}; + test('test method updateMembershipStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + }); + test('test method getPrefs()', () async { + final Map data = {}; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); + test('test method updatePrefs()', () async { + final Map data = {}; - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); }); + }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 15e85f5a..261daa46 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 87a3ca3c..3da36624 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index 3b842e6c..e58fa5b5 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 49b1e22c..3bcbb488 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index dd7fa8c3..b2084927 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,16 +8,18 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index c7d9cdbf..8c131568 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index ae58b57e..d080569c 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index 8de695b0..e71dcae1 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index d5242a4e..85e559f5 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 869f5db6..6df5c584 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index bc66ab7b..d5404a7f 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index 09da675c..d7410db8 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 29890008..00e046c7 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index f1a5b3cc..217d37e8 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 6c1fbb77..397b5fab 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index cb10c58e..8d209722 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -13,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 6d9bf33c..80ef508a 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index d8e6c95c..8e02f65e 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 8a734a08..7f132646 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -24,20 +24,20 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 489891d4..9252b469 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 65f562a7..8c35afec 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 708c8c60..525af4ea 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index e616a956..93376af1 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,13 +5,15 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index 94c1e33f..a07c0b5f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index d4087d5e..4a6c96c1 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index b6de5137..65b44ad1 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index f0fcdbce..88cf157b 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 72102045..49cb1fc9 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index 84c560c8..b07ca8ee 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index 1b463633..c8211d3b 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index bb1f0946..4f30c48e 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index ab136c24..b2b8bd3d 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 9410baa3..5d3febca 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index ed6467d3..64cc55e4 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index fa097a49..500913c8 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 3f45d288..81657394 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,14 +6,16 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index 6ca46a63..bf22a5c7 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index d0e5333b..f70db0e3 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index acde349c..9db30b03 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,7 +10,6 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); - }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 57a86348..46f69af6 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index edcfe5f5..ef2ebe31 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index d4900dd4..12693926 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 4e72a449..564bf303 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index eaab249e..708e0583 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 0177e477..689e6048 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 94c6a502..7445514c 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index a49f3def..49f1e75e 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index a19b667d..fe2f4a85 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index 43b2e45c..f652f2c1 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 7ee4b268..8f0957c9 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index 68023e18..a524ef71 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 723ebac2..0169427f 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index c058ea26..77c7dd97 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From 70716163746a697dcfb56dcd28c9f314e70ccc6b Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Wed, 5 Aug 2026 11:27:31 +0530 Subject: [PATCH 05/17] chore: update Flutter SDK to 25.4.0 --- .github/workflows/format.yml | 6 +- .github/workflows/publish.yml | 4 +- .github/workflows/test.yml | 4 +- CHANGELOG.md | 10 + README.md | 2 +- docs/examples/account/delete-consent-token.md | 14 + docs/examples/account/delete-consent.md | 13 + docs/examples/account/get-consent-token.md | 14 + docs/examples/account/get-consent.md | 13 + docs/examples/account/list-consent-tokens.md | 15 + docs/examples/account/list-consents.md | 14 + .../organization/create-installation.md | 14 + .../organization/delete-installation.md | 13 + .../examples/organization/get-installation.md | 13 + .../organization/list-installations.md | 14 + .../organization/update-installation.md | 14 + docs/examples/storage/create-file.md | 1 + docs/examples/teams/create-installation.md | 15 + docs/examples/teams/delete-installation.md | 14 + docs/examples/teams/get-installation.md | 14 + docs/examples/teams/list-installations.md | 15 + docs/examples/teams/update-installation.md | 15 + lib/appwrite.dart | 3 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/models.dart | 6 + lib/operator.dart | 11 +- lib/query.dart | 89 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1673 +++++----- lib/services/avatars.dart | 367 ++- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/organization.dart | 116 + lib/services/presences.dart | 184 +- lib/services/storage.dart | 350 +- lib/services/tables_db.dart | 549 ++-- lib/services/teams.dart | 530 +-- lib/src/client.dart | 4 +- lib/src/client_base.dart | 1 + lib/src/client_browser.dart | 20 +- lib/src/client_io.dart | 20 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 98 +- lib/src/enums/timezone.dart | 848 ++--- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/app_installation.dart | 78 + lib/src/models/app_installation_list.dart | 30 + lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 206 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 243 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/oauth2_consent.dart | 78 + lib/src/models/oauth2_consent_list.dart | 30 + lib/src/models/oauth2_consent_token.dart | 84 + lib/src/models/oauth2_consent_token_list.dart | 30 + lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- pubspec.yaml | 2 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 + test/services/account_test.dart | 2921 ++++++++++------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 609 ++-- test/services/functions_test.dart | 194 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 269 +- test/services/messaging_test.dart | 124 +- test/services/organization_test.dart | 177 + test/services/presences_test.dart | 210 +- test/services/storage_test.dart | 355 +- test/services/tables_db_test.dart | 609 ++-- test/services/teams_test.dart | 700 ++-- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- .../models/app_installation_list_test.dart | 19 + test/src/models/app_installation_test.dart | 33 + test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 6 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 34 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/oauth2_consent_list_test.dart | 19 + test/src/models/oauth2_consent_test.dart | 35 + .../oauth2_consent_token_list_test.dart | 19 + .../src/models/oauth2_consent_token_test.dart | 37 + test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 + test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 204 files changed, 10509 insertions(+), 8585 deletions(-) create mode 100644 docs/examples/account/delete-consent-token.md create mode 100644 docs/examples/account/delete-consent.md create mode 100644 docs/examples/account/get-consent-token.md create mode 100644 docs/examples/account/get-consent.md create mode 100644 docs/examples/account/list-consent-tokens.md create mode 100644 docs/examples/account/list-consents.md create mode 100644 docs/examples/organization/create-installation.md create mode 100644 docs/examples/organization/delete-installation.md create mode 100644 docs/examples/organization/get-installation.md create mode 100644 docs/examples/organization/list-installations.md create mode 100644 docs/examples/organization/update-installation.md create mode 100644 docs/examples/teams/create-installation.md create mode 100644 docs/examples/teams/delete-installation.md create mode 100644 docs/examples/teams/get-installation.md create mode 100644 docs/examples/teams/list-installations.md create mode 100644 docs/examples/teams/update-installation.md create mode 100644 lib/services/organization.dart create mode 100644 lib/src/models/app_installation.dart create mode 100644 lib/src/models/app_installation_list.dart create mode 100644 lib/src/models/oauth2_consent.dart create mode 100644 lib/src/models/oauth2_consent_list.dart create mode 100644 lib/src/models/oauth2_consent_token.dart create mode 100644 lib/src/models/oauth2_consent_token_list.dart create mode 100644 test/services/organization_test.dart create mode 100644 test/src/models/app_installation_list_test.dart create mode 100644 test/src/models/app_installation_test.dart create mode 100644 test/src/models/oauth2_consent_list_test.dart create mode 100644 test/src/models/oauth2_consent_test.dart create mode 100644 test/src/models/oauth2_consent_token_list_test.dart create mode 100644 test/src/models/oauth2_consent_token_test.dart diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 5127d8be..0e4bf293 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -13,13 +13,13 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: true ref: ${{ github.event.pull_request.head.ref }} - name: Install Flutter - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 + uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: channel: stable @@ -33,7 +33,7 @@ jobs: run: git config --global --add safe.directory /__w/sdk-for-flutter/sdk-for-flutter # required to fix dubious ownership - name: Add & Commit - uses: EndBug/add-and-commit@a94899bca583c204427a224a7af87c02f9b325d5 # v9.1.4 + uses: EndBug/add-and-commit@290ea2c423ad77ca9c62ae0f5b224379612c0321 # v10.0.0 with: add: '["lib", "test"]' diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 045dcbaf..aefb3e10 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,9 +11,9 @@ jobs: id-token: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Flutter - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 + uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: channel: stable - name: Install dependencies diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 56f26a0d..a84bb7b9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,9 +6,9 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Flutter - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 + uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: channel: stable - run: flutter pub get diff --git a/CHANGELOG.md b/CHANGELOG.md index f492c6b8..99ca59f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 25.4.0 + +* Added: `Organization` service for managing app installations +* Added: app installation management methods to the `Teams` service +* Added: account OAuth2 consent methods `listConsents`, `getConsent`, `deleteConsent` +* Added: account consent token methods `listConsentTokens`, `getConsentToken`, `deleteConsentToken` +* Added: `folder` parameter to `storage.createFile`, and `folder` and `key` to `File` +* Fixed: Null optional parameters are no longer sent in request bodies +* Fixed: Binary endpoints now authenticate with headers, not query parameters + ## 25.3.0 * Added: `Client.setBearer()` method for OAuth access token authentication diff --git a/README.md b/README.md index 804fca53..d65b5309 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^25.3.0 + appwrite: ^25.4.0 ``` You can install packages from the command line: diff --git a/docs/examples/account/delete-consent-token.md b/docs/examples/account/delete-consent-token.md new file mode 100644 index 00000000..9c877479 --- /dev/null +++ b/docs/examples/account/delete-consent-token.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +await account.deleteConsentToken( + consentId: '', + tokenId: '', +); +``` diff --git a/docs/examples/account/delete-consent.md b/docs/examples/account/delete-consent.md new file mode 100644 index 00000000..78799117 --- /dev/null +++ b/docs/examples/account/delete-consent.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +await account.deleteConsent( + consentId: '', +); +``` diff --git a/docs/examples/account/get-consent-token.md b/docs/examples/account/get-consent-token.md new file mode 100644 index 00000000..67a0d842 --- /dev/null +++ b/docs/examples/account/get-consent-token.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Oauth2ConsentToken result = await account.getConsentToken( + consentId: '', + tokenId: '', +); +``` diff --git a/docs/examples/account/get-consent.md b/docs/examples/account/get-consent.md new file mode 100644 index 00000000..aff62725 --- /dev/null +++ b/docs/examples/account/get-consent.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Oauth2Consent result = await account.getConsent( + consentId: '', +); +``` diff --git a/docs/examples/account/list-consent-tokens.md b/docs/examples/account/list-consent-tokens.md new file mode 100644 index 00000000..835c7775 --- /dev/null +++ b/docs/examples/account/list-consent-tokens.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Oauth2ConsentTokenList result = await account.listConsentTokens( + consentId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/account/list-consents.md b/docs/examples/account/list-consents.md new file mode 100644 index 00000000..d39f0547 --- /dev/null +++ b/docs/examples/account/list-consents.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Oauth2ConsentList result = await account.listConsents( + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/organization/create-installation.md b/docs/examples/organization/create-installation.md new file mode 100644 index 00000000..d28dacfc --- /dev/null +++ b/docs/examples/organization/create-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Organization organization = Organization(client); + +AppInstallation result = await organization.createInstallation( + appId: '', + authorizationDetails: '', // optional +); +``` diff --git a/docs/examples/organization/delete-installation.md b/docs/examples/organization/delete-installation.md new file mode 100644 index 00000000..3142e245 --- /dev/null +++ b/docs/examples/organization/delete-installation.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Organization organization = Organization(client); + +await organization.deleteInstallation( + installationId: '', +); +``` diff --git a/docs/examples/organization/get-installation.md b/docs/examples/organization/get-installation.md new file mode 100644 index 00000000..dd2d7ac7 --- /dev/null +++ b/docs/examples/organization/get-installation.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Organization organization = Organization(client); + +AppInstallation result = await organization.getInstallation( + installationId: '', +); +``` diff --git a/docs/examples/organization/list-installations.md b/docs/examples/organization/list-installations.md new file mode 100644 index 00000000..bdecb108 --- /dev/null +++ b/docs/examples/organization/list-installations.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Organization organization = Organization(client); + +AppInstallationList result = await organization.listInstallations( + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/organization/update-installation.md b/docs/examples/organization/update-installation.md new file mode 100644 index 00000000..fa834d49 --- /dev/null +++ b/docs/examples/organization/update-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Organization organization = Organization(client); + +AppInstallation result = await organization.updateInstallation( + installationId: '', + authorizationDetails: '', // optional +); +``` diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 8f904801..007abee4 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -15,5 +15,6 @@ File result = await storage.createFile( fileId: '', file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), permissions: [Permission.read(Role.any())], // optional + folder: '', // optional ); ``` diff --git a/docs/examples/teams/create-installation.md b/docs/examples/teams/create-installation.md new file mode 100644 index 00000000..4ad63b8d --- /dev/null +++ b/docs/examples/teams/create-installation.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Teams teams = Teams(client); + +AppInstallation result = await teams.createInstallation( + teamId: '', + appId: '', + authorizationDetails: '', // optional +); +``` diff --git a/docs/examples/teams/delete-installation.md b/docs/examples/teams/delete-installation.md new file mode 100644 index 00000000..4c872cec --- /dev/null +++ b/docs/examples/teams/delete-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Teams teams = Teams(client); + +await teams.deleteInstallation( + teamId: '', + installationId: '', +); +``` diff --git a/docs/examples/teams/get-installation.md b/docs/examples/teams/get-installation.md new file mode 100644 index 00000000..eec87662 --- /dev/null +++ b/docs/examples/teams/get-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Teams teams = Teams(client); + +AppInstallation result = await teams.getInstallation( + teamId: '', + installationId: '', +); +``` diff --git a/docs/examples/teams/list-installations.md b/docs/examples/teams/list-installations.md new file mode 100644 index 00000000..9c3aa852 --- /dev/null +++ b/docs/examples/teams/list-installations.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Teams teams = Teams(client); + +AppInstallationList result = await teams.listInstallations( + teamId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/teams/update-installation.md b/docs/examples/teams/update-installation.md new file mode 100644 index 00000000..e9e8ba4b --- /dev/null +++ b/docs/examples/teams/update-installation.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Teams teams = Teams(client); + +AppInstallation result = await teams.updateInstallation( + teamId: '', + installationId: '', + authorizationDetails: '', // optional +); +``` diff --git a/lib/appwrite.dart b/lib/appwrite.dart index ae51be5e..bc955b6c 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; @@ -39,6 +39,7 @@ part 'services/functions.dart'; part 'services/graphql.dart'; part 'services/locale.dart'; part 'services/messaging.dart'; +part 'services/organization.dart'; part 'services/presences.dart'; part 'services/storage.dart'; part 'services/tables_db.dart'; diff --git a/lib/channel.dart b/lib/channel.dart index afc68efa..d511f5a4 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,33 +2,19 @@ part of appwrite; // Marker classes for type safety class _Root {} - class _Database {} - class _Collection {} - class _Document {} - class _TablesDB {} - class _Table {} - class _Row {} - class _Bucket {} - class _File {} - class _Func {} - class _Execution {} - class _Team {} - class _Membership {} - class _Presence {} - class _Resolved {} // Helper function for normalizing ID @@ -113,15 +99,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => - _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => _next<_Table>('tables', id); + Channel<_Table> table(String id) => + _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/models.dart b/lib/models.dart index fb5d3f8d..d6ee0466 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -57,3 +57,9 @@ part 'src/models/mfa_factors.dart'; part 'src/models/transaction.dart'; part 'src/models/subscriber.dart'; part 'src/models/target.dart'; +part 'src/models/app_installation.dart'; +part 'src/models/oauth2_consent.dart'; +part 'src/models/oauth2_consent_token.dart'; +part 'src/models/oauth2_consent_list.dart'; +part 'src/models/oauth2_consent_token_list.dart'; +part 'src/models/app_installation_list.dart'; diff --git a/lib/operator.dart b/lib/operator.dart index 337dda30..9dd7f4c7 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if (values != null) { + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -147,7 +147,8 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => Operator._('arrayUnique', []).toString(); + static String arrayUnique() => + Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -172,7 +173,8 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => Operator._('toggle', []).toString(); + static String toggle() => + Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -183,5 +185,6 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => Operator._('dateSetNow', []).toString(); + static String dateSetNow() => + Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 2772116a..2221a6e6 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if (attribute != null) { + + if(attribute != null) { result['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,46 +140,50 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => lessThan('\$createdAt', value); + static String createdBefore(String value) => + lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => greaterThan('\$createdAt', value); + static String createdAfter(String value) => + greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => lessThan('\$updatedAt', value); + static String updatedBefore(String value) => + lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => + greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -194,17 +198,18 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => Query._('orderRandom').toString(); + static String orderRandom() => + Query._('orderRandom').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(); /// 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) => @@ -214,43 +219,27 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceNotEqual', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan( - String attribute, List values, num distance, - [bool meters = true]) => - Query._('distanceLessThan', attribute, [ - [values, distance, meters] - ]).toString(); + static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => + Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); /// Filter resources using vector dot product similarity. static String vectorDot(String attribute, List vector) => 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..3f91a53a 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 48b60041..8f8238ae 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; -/// The Account service allows you to authenticate and manage a user account. + /// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,17 +9,18 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -29,30 +30,154 @@ class Account extends Service { /// 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 { + Future create({required String userId, required String email, required String password, String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - if (name != null) 'name': name, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + 'password': password, + + if (name != null) 'name': name, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get a list of the OAuth2 consents the current user has given to third-party + /// apps. + Future listConsents({List? queries, bool? total}) async { + final String apiPath = '/account/consents'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Oauth2ConsentList.fromMap(res.data); + + } + + /// Get an OAuth2 consent the current user has given to a third-party app by + /// its unique ID. + Future getConsent({required String consentId}) async { + final String apiPath = '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Oauth2Consent.fromMap(res.data); + + } + + /// Delete an OAuth2 consent by its unique ID. All token families issued under + /// the consent are revoked, and the app must ask for consent again to regain + /// access. + Future deleteConsent({required String consentId}) async { + final String apiPath = '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get a list of the token families issued under an OAuth2 consent. Each entry + /// represents one authorized device or session; the token secrets themselves + /// are never returned. + Future listConsentTokens({required String consentId, List? queries, bool? total}) async { + final String apiPath = '/account/consents/{consentId}/tokens'.replaceAll('{consentId}', consentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Oauth2ConsentTokenList.fromMap(res.data); + + } + + /// Get a token family issued under an OAuth2 consent by its unique ID. The + /// token secrets themselves are never returned. + Future getConsentToken({required String consentId, required String tokenId}) async { + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}'.replaceAll('{consentId}', consentId).replaceAll('{tokenId}', tokenId); + + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Oauth2ConsentToken.fromMap(res.data); + + } + + /// Delete a token family issued under an OAuth2 consent by its unique ID. The + /// access and refresh tokens of the family stop working immediately; other + /// token families and the consent itself are unaffected. + Future deleteConsentToken({required String consentId, required String tokenId}) async { + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}'.replaceAll('{consentId}', consentId).replaceAll('{tokenId}', tokenId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return models.User.fromMap(res.data); } /// Update currently logged in user account email address. After changing user @@ -62,65 +187,66 @@ class Account extends Service { /// 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 { + /// + Future updateEmail({required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities( - {List? queries, bool? total}) async { + Future listIdentities({List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); - return models.IdentityList.fromMap(res.data); } /// Delete an identity by its unique ID. Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -131,20 +257,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, - }; + final Map apiParams = { + if (duration != null) 'duration': duration, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Jwt.fromMap(res.data); - return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -152,224 +278,212 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); - return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - }; + final Map apiParams = { + 'mfa': mfa, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// 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); + Future createMFAAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); - return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 apiParams = { - 'otp': otp, - }; + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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); + 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 apiParams = { - 'otp': otp, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// 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 String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge({required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - }; + final Map apiParams = { + 'factor': factor.value, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); - return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -377,27 +491,26 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, + + 'otp': otp, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -405,83 +518,84 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge( - {required String challengeId, required String otp}) async { + Future updateMFAChallenge({required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; + final Map apiParams = { + 'challengeId': challengeId, + + 'otp': otp, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaFactors.fromMap(res.data); - return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -491,17 +605,18 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -509,23 +624,22 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -536,41 +650,40 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -580,62 +693,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); - return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// 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 { + Future updatePassword({required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, - if (oldPassword != null) 'oldPassword': oldPassword, - }; + final Map apiParams = { + 'password': password, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + if (oldPassword != null) 'oldPassword': oldPassword, - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -643,42 +756,43 @@ class Account extends Service { /// 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 { + Future updatePhone({required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, - 'password': password, - }; + final Map apiParams = { + 'phone': phone, + + 'password': password, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -687,20 +801,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, - }; + final Map apiParams = { + 'prefs': prefs, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -711,25 +825,25 @@ class Account extends Service { /// /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 { + Future createRecovery({required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - 'url': url, - }; + final Map apiParams = { + 'email': email, + + 'url': url, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -737,33 +851,32 @@ class Account extends Service { /// 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 { + Future updateRecovery({required String userId, required String secret, required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + 'password': password, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -771,17 +884,18 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.SessionList.fromMap(res.data); - return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -789,17 +903,18 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -812,216 +927,213 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession({required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - 'password': password, - }; + final Map apiParams = { + 'email': email, + + 'password': password, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'secret': secret, - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) '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)}'); - } - }); + /// + 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 = { + + if (success != null) 'success': success, - 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('&')); + if (failure != null) 'failure': failure, - return client.webAuth(url, callbackUrlScheme: success); + if (scopes != null) '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); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 { + Future createSession({required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); - return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1030,20 +1142,20 @@ class Account extends Service { /// 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 String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1052,18 +1164,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); - return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1071,28 +1183,27 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - if (providerId != null) 'providerId': providerId, - }; + final Map apiParams = { + 'targetId': targetId, + + 'identifier': identifier, + + if (providerId != null) 'providerId': providerId, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1100,45 +1211,43 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + 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 apiParams = { - 'identifier': identifier, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); - return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1150,31 +1259,32 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken({required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + if (phrase != null) 'phrase': phrase, - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1186,88 +1296,87 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - 'email': email, - if (url != null) 'url': url, - if (phrase != null) 'phrase': phrase, - }; + final Map apiParams = { + 'userId': userId, + + 'email': email, + + if (url != null) 'url': url, + + if (phrase != null) 'phrase': phrase, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - if (success != null) 'success': success, - if (failure != null) 'failure': failure, - if (scopes != null) '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)}'); - } - }); + 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 = { + + if (success != null) 'success': success, - 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('&')); + if (failure != null) 'failure': failure, - return client.webAuth(url, callbackUrlScheme: success); + if (scopes != null) '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); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1276,29 +1385,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken({required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; + final Map apiParams = { + 'userId': userId, + + 'phone': phone, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1310,29 +1419,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1344,83 +1453,81 @@ class Account extends Service { /// 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. - /// - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - }; + final Map apiParams = { + 'url': url, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 updateEmailVerification( - {required String userId, required String secret}) async { + Future updateEmailVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + 'secret': secret, - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification( - {required String userId, required String secret}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1434,42 +1541,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification({required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; + final Map apiParams = { + 'userId': userId, + + 'secret': secret, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); - return models.Token.fromMap(res.data); } } diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index cdd93e6e..e422f227 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Avatars service aims to help you complete everyday tasks related to -/// your app image, icons, and avatars. + /// 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); @@ -11,134 +11,149 @@ class Avatars extends Service { /// /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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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 apiParams = { + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 apiParams = { + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// 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 { final String apiPath = '/avatars/favicon'; - final Map params = { - 'url': url, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; + final Map apiParams = { + 'url': url, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; } /// 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 = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + /// + 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 apiParams = { + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// 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 { + Future getImage({required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map params = { - 'url': url, - if (width != null) 'width': width, - if (height != null) 'height': height, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map apiParams = { + 'url': url, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// Use this endpoint to show your user initials avatar icon on your website or @@ -146,117 +161,131 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map params = { - if (name != null) 'name': name, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (background != null) 'background': background, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map apiParams = { + if (name != null) 'name': name, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (background != null) 'background': background, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// 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 { + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map params = { - 'text': text, - if (size != null) 'size': size, - if (margin != null) 'margin': margin, - if (download != null) 'download': download, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map apiParams = { + 'text': text, + + if (size != null) 'size': size, + + if (margin != null) 'margin': margin, + + if (download != null) 'download': download, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot( - {required String url, - Map? headers, - int? viewportWidth, - int? viewportHeight, - double? scale, - enums.BrowserTheme? theme, - String? userAgent, - bool? fullpage, - String? locale, - enums.Timezone? timezone, - double? latitude, - double? longitude, - double? accuracy, - bool? touch, - List? permissions, - int? sleep, - int? width, - int? height, - int? quality, - enums.ImageFormat? output}) async { + Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map params = { - 'url': url, - if (headers != null) 'headers': headers, - if (viewportWidth != null) 'viewportWidth': viewportWidth, - if (viewportHeight != null) 'viewportHeight': viewportHeight, - if (scale != null) 'scale': scale, - if (theme != null) 'theme': theme.value, - if (userAgent != null) 'userAgent': userAgent, - if (fullpage != null) 'fullpage': fullpage, - if (locale != null) 'locale': locale, - if (timezone != null) 'timezone': timezone.value, - if (latitude != null) 'latitude': latitude, - if (longitude != null) 'longitude': longitude, - if (accuracy != null) 'accuracy': accuracy, - if (touch != null) 'touch': touch, - if (permissions != null) - 'permissions': permissions.map((e) => e.value).toList(), - if (sleep != null) 'sleep': sleep, - if (width != null) 'width': width, - if (height != null) 'height': height, - if (quality != null) 'quality': quality, - if (output != null) 'output': output.value, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + final Map apiParams = { + 'url': url, + + if (headers != null) 'headers': headers, + + if (viewportWidth != null) 'viewportWidth': viewportWidth, + + if (viewportHeight != null) 'viewportHeight': viewportHeight, + + if (scale != null) 'scale': scale, + + if (theme != null) 'theme': theme.value, + + if (userAgent != null) 'userAgent': userAgent, + + if (fullpage != null) 'fullpage': fullpage, + + if (locale != null) 'locale': locale, + + if (timezone != null) 'timezone': timezone.value, + + if (latitude != null) 'latitude': latitude, + + if (longitude != null) 'longitude': longitude, + + if (accuracy != null) 'accuracy': accuracy, + + if (touch != null) 'touch': touch, + + if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), + + if (sleep != null) 'sleep': sleep, + + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (quality != null) 'quality': quality, + + if (output != null) 'output': output.value, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } } diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 0ff3fb72..c791ea0e 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,418 +1,339 @@ part of '../appwrite.dart'; -/// The Databases service allows you to create structured collections of -/// documents, query and filter lists of documents + /// 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 transactions across all databases. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions( - {List? queries}) async { + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions({List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction({required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } /// 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + + 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Create or update a 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. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Delete a document by its unique ID. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + if (min != null) 'min': min, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } /// Increment a specific attribute of a document by a given value. - @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); + @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + + if (max != null) 'max': max, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index ed97921b..49236018 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,87 +1,82 @@ part of '../appwrite.dart'; -/// The Functions Service allows you view, create and manage your Cloud -/// Functions. + /// The Functions Service allows you view, create and manage your Cloud + /// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); + Future listExecutions({required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); - return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - if (xasync != null) 'async': xasync, - if (path != null) 'path': path, - if (method != null) 'method': method.value, - if (headers != null) 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); + 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 = { + if (body != null) 'body': body, + + if (xasync != null) 'async': xasync, + + if (path != null) 'path': path, + + if (method != null) 'method': method.value, + + if (headers != null) 'headers': headers, + + if (scheduledAt != null) 'scheduledAt': scheduledAt, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Execution.fromMap(res.data); - return models.Execution.fromMap(res.data); } } diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index c86f3719..978331fa 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The GraphQL API allows you to query and mutate your Appwrite server using -/// GraphQL. + /// 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); @@ -10,41 +10,39 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - }; + final Map apiParams = { + 'query': query, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 87ea162e..c45a1269 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; -/// The Locale service allows you to customize your app based on your users' -/// location. + /// 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); @@ -10,22 +10,23 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all locale codes in [ISO @@ -33,17 +34,18 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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 of all continents. You can use the locale header to get the data in a @@ -51,17 +53,18 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.ContinentList.fromMap(res.data); - return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -69,17 +72,18 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries that are currently members of the EU. You can use the @@ -87,17 +91,18 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CountryList.fromMap(res.data); } /// List of all countries phone codes. You can use the locale header to get the @@ -105,17 +110,18 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -124,17 +130,18 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -142,16 +149,17 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.LanguageList.fromMap(res.data); - return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 61ecefee..3dffe41b 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,54 +1,48 @@ part of '../appwrite.dart'; -/// The Messaging service allows you to send messages to any provider type -/// (SMTP, push notification, SMS, etc.). + /// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } /// 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/organization.dart b/lib/services/organization.dart new file mode 100644 index 00000000..f0ad5cfd --- /dev/null +++ b/lib/services/organization.dart @@ -0,0 +1,116 @@ +part of '../appwrite.dart'; + + /// The Organization service allows you to manage organization-level projects. +class Organization extends Service { + /// Initializes a [Organization] service + Organization(super.client); + + /// List app installations on the organization. Any organization member can + /// read installations. + Future listInstallations({List? queries, bool? total}) async { + final String apiPath = '/organization/installations'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallationList.fromMap(res.data); + + } + + /// Install an app on the organization. Only organization members with the + /// owner role can install apps. The installation is granted the scopes the app + /// currently requests. + Future createInstallation({required String appId, String? authorizationDetails}) async { + final String apiPath = '/organization/installations'; + + final Map apiParams = { + 'appId': appId, + + if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); + + } + + /// Get an app installation on the organization by its unique ID. Any + /// organization member can read installations. + Future getInstallation({required String installationId}) async { + final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); + + } + + /// Update an app installation on the organization. Only organization members + /// with the owner role can update installations. The installation's granted + /// scopes are refreshed to the scopes the app currently requests; previously + /// issued installation access tokens are revoked. + Future updateInstallation({required String installationId, String? authorizationDetails}) async { + final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); + + final Map apiParams = { + if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); + + } + + /// Uninstall an app from the organization by its installation ID. Only + /// organization members with the owner role can remove installations. + /// Previously issued installation access tokens are revoked. + Future deleteInstallation({required String installationId}) async { + final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 1c9b651b..4e0803d8 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -1,131 +1,129 @@ part of '../appwrite.dart'; + /// The Presences service allows you to track and manage real-time user + /// presence in your project. class Presences extends Service { /// Initializes a [Presences] service Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list( - {List? queries, bool? total, int? ttl}) async { + /// + Future list({List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (total != null) 'total': total, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.PresenceList.fromMap(res.data); - return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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.Presence.fromMap(res.data); - return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert( - {required String presenceId, - required String status, - List? permissions, - String? expiresAt, - Map? metadata}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - if (permissions != null) 'permissions': permissions, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + + if (permissions != null) 'permissions': permissions, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update( - {required String presenceId, - String? status, - String? expiresAt, - Map? metadata, - List? permissions, - bool? purge}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - if (expiresAt != null) 'expiresAt': expiresAt, - if (metadata != null) 'metadata': metadata, - if (permissions != null) 'permissions': permissions, - if (purge != null) 'purge': purge, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + /// + Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + + if (expiresAt != null) 'expiresAt': expiresAt, + + if (metadata != null) 'metadata': metadata, + + if (permissions != null) 'permissions': permissions, + + if (purge != null) 'purge': purge, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); + } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } } diff --git a/lib/services/storage.dart b/lib/services/storage.dart index cdb626de..fc609bb6 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,178 +1,170 @@ part of '../appwrite.dart'; -/// The Storage service allows you to manage your project files. + /// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, - bool? total}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); + Future listFiles({required String bucketId, List? queries, String? search, bool? total}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } /// 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, - if (permissions != null) 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', - 'accept': 'application/json', - }; - - 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); + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, String? folder, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + + 'file': file, + + if (permissions != null) 'permissions': permissions, + + if (folder != null) 'folder': folder, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', 'accept': 'application/json', + }; + + 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 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); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.File.fromMap(res.data); - return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); + 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 = { + if (name != null) 'name': name, + + if (permissions != null) 'permissions': permissions, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileDownload({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (token != null) 'token': token, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '*/*', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// Get a file preview image. Currently, this method supports preview for image @@ -180,64 +172,64 @@ class Storage extends Service { /// 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, - String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (width != null) 'width': width, - if (height != null) 'height': height, - if (gravity != null) 'gravity': gravity.value, - if (quality != null) 'quality': quality, - if (borderWidth != null) 'borderWidth': borderWidth, - if (borderColor != null) 'borderColor': borderColor, - if (borderRadius != null) 'borderRadius': borderRadius, - if (opacity != null) 'opacity': opacity, - if (rotation != null) 'rotation': rotation, - if (background != null) 'background': background, - if (output != null) 'output': output.value, - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + 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, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (width != null) 'width': width, + + if (height != null) 'height': height, + + if (gravity != null) 'gravity': gravity.value, + + if (quality != null) 'quality': quality, + + if (borderWidth != null) 'borderWidth': borderWidth, + + if (borderColor != null) 'borderColor': borderColor, + + if (borderRadius != null) 'borderRadius': borderRadius, + + if (opacity != null) 'opacity': opacity, + + if (rotation != null) 'rotation': rotation, + + if (background != null) 'background': background, + + if (output != null) 'output': output.value, + + if (token != null) 'token': token, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - if (token != null) 'token': token, - 'project': client.config['project'], - 'impersonateuserid': client.config['impersonateuserid'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; + Future getFileView({required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (token != null) 'token': token, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '*/*', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); + return res.data; + } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 8b6284b3..93a5c190 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -1,386 +1,325 @@ part of '../appwrite.dart'; + /// The TablesDB service allows you to create structured tables of columns, + /// query and filter lists of rows class TablesDB extends Service { /// Initializes a [TablesDB] service TablesDB(super.client); /// List transactions across all databases. - Future listTransactions( - {List? queries}) async { + Future listTransactions({List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TransactionList.fromMap(res.data); - return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future getTransaction({required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - if (rollback != null) 'rollback': rollback, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + + if (rollback != null) 'rollback': rollback, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); + } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; - return res.data; } /// Create multiple operations in a single transaction. - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); + Future createOperations({required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + + }; - final Map apiParams = { - if (operations != null) 'operations': operations, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); - return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows( - {required String databaseId, - required String tableId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - if (total != null) 'total': total, - if (ttl != null) 'ttl': ttl, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); + Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + if (total != null) 'total': total, + + if (ttl != null) 'ttl': ttl, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); + } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow( - {required String databaseId, - required String tableId, - required String rowId, - required Map data, - List? permissions, - String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + + 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow( - {required String databaseId, - required String tableId, - required String rowId, - List? queries, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - 'permissions': permissions, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + + if (permissions != null) 'permissions': permissions, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Delete a row by its unique ID. - Future deleteRow( - {required String databaseId, - required String tableId, - required String rowId, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? min, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'min': min, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + if (min != null) 'min': min, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } /// Increment a specific column of a row by a given value. - Future incrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? max, - String? transactionId}) async { - final String apiPath = - '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - 'max': max, - 'transactionId': transactionId, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); + Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + + if (max != null) 'max': max, + + if (transactionId != null) 'transactionId': transactionId, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); + } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 1f4022f6..a3a0cea4 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,97 +1,98 @@ 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 + /// 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); /// 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, bool? total}) async { + Future list({List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; + final Map apiParams = { + if (queries != null) 'queries': queries, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + if (search != null) 'search': search, - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); - return models.TeamList.fromMap(res.data); } /// 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 { + Future create({required String teamId, required String name, List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - 'name': name, - if (roles != null) 'roles': roles, - }; + final Map apiParams = { + 'teamId': teamId, + + 'name': name, + + if (roles != null) 'roles': roles, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// 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 apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { + Future updateName({required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, - }; + final Map apiParams = { + 'name': name, - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); - return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -99,45 +100,153 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = {}; + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List app installations on a team. Any team member can read installations. + Future listInstallations({required String teamId, List? queries, bool? total}) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallationList.fromMap(res.data); + + } + + /// Install an app on a team. When authenticated as a user, only team members + /// with the owner role can install apps. Requests using an API key or in admin + /// mode can install apps on any team. The installation is granted the scopes + /// the app currently requests. + Future createInstallation({required String teamId, required String appId, String? authorizationDetails}) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'appId': appId, + + if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); + + } + + /// Get an app installation on a team by its unique ID. Any team member can + /// read installations. + Future getInstallation({required String teamId, required String installationId}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); + + } + + /// Update an app installation on a team. Only team members with the owner role + /// can update installations. The installation's granted scopes are refreshed + /// to the scopes the app currently requests; previously issued installation + /// access tokens are revoked. + Future updateInstallation({required String teamId, required String installationId, String? authorizationDetails}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); + + final Map apiParams = { + if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallation.fromMap(res.data); + + } + + /// Uninstall an app from a team by its installation ID. Only team members with + /// the owner role can remove installations. Previously issued installation + /// access tokens are revoked. + Future deleteInstallation({required String teamId, required String installationId}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships( - {required String teamId, - List? queries, - String? search, - bool? total}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (search != null) 'search': search, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); + Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + + if (search != null) 'search': search, + + if (total != null) 'total': total, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -146,199 +255,180 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - if (userId != null) 'userId': userId, - if (phone != null) 'phone': phone, - 'roles': roles, - if (url != null) 'url': url, - if (name != null) 'name': name, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + if (email != null) 'email': email, + + if (userId != null) 'userId': userId, + + if (phone != null) 'phone': phone, + + 'roles': roles, + + if (url != null) 'url': url, + + if (name != null) 'name': name, + + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); + 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 apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Membership.fromMap(res.data); - return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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); + 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 apiParams = { + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; - return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } /// 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 String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '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.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } /// 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); + 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 apiParams = { - 'prefs': prefs, - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); - return models.Preferences.fromMap(res.data); } } diff --git a/lib/src/client.dart b/lib/src/client.dart index dbfe4bdf..c75dc37b 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -113,6 +112,7 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); + /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 9e6cf566..6794a5a2 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -42,6 +42,7 @@ abstract class ClientBase implements Client { @override ClientBase setImpersonateUserPhone(value); + @override ClientBase setSelfSigned({bool status = true}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 38cee6bb..56c7a549 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,8 +40,8 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.3.0', - 'X-Appwrite-Response-Format': '1.9.5', + 'x-sdk-version': '25.4.0', + 'X-Appwrite-Response-Format': '1.9.6', }; config = {}; @@ -62,7 +62,6 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -70,7 +69,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - /// The OAuth access token to authenticate with @override ClientBrowser setBearer(value) { @@ -78,14 +76,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -93,7 +89,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -101,7 +96,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -109,7 +103,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -117,7 +110,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -125,7 +117,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -235,8 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk( - int index, int start, int end, String? id) async { + Future uploadChunk(int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -274,9 +264,7 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index a4cae30f..d4bcece8 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -58,8 +58,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.3.0', - 'X-Appwrite-Response-Format': '1.9.5', + 'x-sdk-version': '25.4.0', + 'X-Appwrite-Response-Format': '1.9.6', }; config = {}; @@ -88,7 +88,6 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } - /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -96,7 +95,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - /// The OAuth access token to authenticate with @override ClientIO setBearer(value) { @@ -104,14 +102,12 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -119,7 +115,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } - /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -127,7 +122,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -135,7 +129,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } - /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -143,7 +136,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } - /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -151,7 +143,6 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } - /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -410,9 +401,7 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && - chunksTotal is num && - chunksUploaded >= chunksTotal; + return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -436,8 +425,7 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = - file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 89aad359..40484946 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,6 +12,7 @@ mixin ClientMixin { required Map headers, required Map params, }) { + http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -127,13 +128,9 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response( - '', + return http.Response('', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index fb4983db..765b3e0c 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,30 +1,32 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({required this.value}); + const BrowserPermission({ + 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_theme.dart b/lib/src/enums/browser_theme.dart index 1e059c2c..e81a0f68 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,12 +1,14 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({required this.value}); + const BrowserTheme({ + 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 28c2a1b3..4d6bce3a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,27 +1,29 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 44de4907..6ad112fe 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index 7ea9865e..f54859c9 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({required this.value}); + const ExecutionStatus({ + 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_trigger.dart b/lib/src/enums/execution_trigger.dart index fb05eb7d..8a14ae60 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,13 +1,15 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({required this.value}); + const ExecutionTrigger({ + 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 55f4c5db..0f996ed9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,19 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 6c8dbc70..77cad38c 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,54 +1,56 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index d5d8d94a..4a8de1ce 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,429 +1,431 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({required this.value}); + const Timezone({ + 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 c6974573..683e6387 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 344a8770..f80fa854 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 9909265e..c51da4bb 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 746fbd52..43523ab1 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index cab45e49..8562c4e3 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index a1648843..8e844839 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 33ef4a6f..5202db05 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 4984df75..3d08af9f 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/app_installation.dart b/lib/src/models/app_installation.dart new file mode 100644 index 00000000..ec5d9b2f --- /dev/null +++ b/lib/src/models/app_installation.dart @@ -0,0 +1,78 @@ +part of '../../models.dart'; + +/// AppInstallation +class AppInstallation implements Model { + /// Installation ID. + final String $id; + + /// Installation creation time in ISO 8601 format. + final String $createdAt; + + /// Installation update time in ISO 8601 format. + final String $updatedAt; + + /// ID of the installed application. + final String appId; + + /// ID of the team the application is installed on. + final String teamId; + + /// Scopes granted to the application. Snapshot of the application's installation scopes taken when the installation was created or last updated. + final List scopes; + + /// Authorization details granted to the application. Rich authorization request (RFC 9396) style entries; the Appwrite Console stores authorized project IDs here. + final Map authorizationDetails; + + /// ID of the user who created the installation. + final String createdById; + + /// Name of the user who created the installation. + final String createdByName; + + /// Time an access token was last issued for the installation in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppInstallation({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.teamId, + required this.scopes, + required this.authorizationDetails, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + + factory AppInstallation.fromMap(Map map) { + return AppInstallation( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + teamId: map['teamId'].toString(), + scopes: List.from(map['scopes'] ?? []), + authorizationDetails: map['authorizationDetails'], + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "teamId": teamId, + "scopes": scopes, + "authorizationDetails": authorizationDetails, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_installation_list.dart b/lib/src/models/app_installation_list.dart new file mode 100644 index 00000000..f9484c53 --- /dev/null +++ b/lib/src/models/app_installation_list.dart @@ -0,0 +1,30 @@ +part of '../../models.dart'; + +/// App installations list +class AppInstallationList implements Model { + /// Total number of installations that matched your query. + final int total; + + /// List of installations. + final List installations; + + AppInstallationList({ + required this.total, + required this.installations, + }); + + factory AppInstallationList.fromMap(Map map) { + return AppInstallationList( + total: map['total'], + installations: List.from(map['installations'].map((p) => AppInstallation.fromMap(p))), + ); + } + + @override + Map toMap() { + return { + "total": total, + "installations": installations.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index ec3c41be..930900bf 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index df28f04b..753bcacc 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3bcbb76d..c4838ba3 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 79cb1256..f363a54b 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 f2b18093..b6bb455f 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 6c39ae2e..eb2bad19 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 be08d599..0d1fdeb0 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 76a07309..0e30844a 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,33 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3629e1d6..3e767ca3 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,129 +2,125 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values - .firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values - .firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 63c2ad7e..45b60682 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 01cdcb3a..f70fdcd4 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,101 +2,113 @@ 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; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - 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.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// Virtual folder containing the file, with a trailing slash. Empty for the bucket root. + final String folder; + + /// Full virtual path of the file: the folder followed by the file name. + final String key; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.folder, + required this.key, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + folder: map['folder'].toString(), + key: map['key'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "folder": folder, + "key": key, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 1157554a..84c54b2e 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa054420..bbccf88a 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index cc659043..7e90020c 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 a5d39ea0..d9cc09a2 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 cda66c70..2000acb6 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 87dc3606..1422d065 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 6198d61e..5d78a367 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 c29b9e25..926e352d 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,126 +2,125 @@ 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; - - /// City - final String? city; - - /// Name of timezone - final String? timeZone; - - /// Postal code - final String? postalCode; - - /// Latitude - final double? latitude; - - /// Longitude - final double? longitude; - - /// Autonomous System Number (ASN) of the IP - final String? autonomousSystemNumber; - - /// Organization that owns the ASN - final String? autonomousSystemOrganization; - - /// Internet service provider of the IP - final String? isp; - - /// Connection type of the IP (e.g. cable, cellular, corporate) - final String? connectionType; - - /// User type classification of the IP (e.g. residential, business, hosting) - final String? connectionUsageType; - - /// Registered organization of the IP - final String? connectionOrganization; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - this.city, - this.timeZone, - this.postalCode, - this.latitude, - this.longitude, - this.autonomousSystemNumber, - this.autonomousSystemOrganization, - this.isp, - this.connectionType, - this.connectionUsageType, - this.connectionOrganization, - }); - - 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(), - city: map['city']?.toString(), - timeZone: map['timeZone']?.toString(), - postalCode: map['postalCode']?.toString(), - latitude: map['latitude']?.toDouble(), - longitude: map['longitude']?.toDouble(), - autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), - autonomousSystemOrganization: - map['autonomousSystemOrganization']?.toString(), - isp: map['isp']?.toString(), - connectionType: map['connectionType']?.toString(), - connectionUsageType: map['connectionUsageType']?.toString(), - connectionOrganization: map['connectionOrganization']?.toString(), - ); - } - - @override - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - "city": city, - "timeZone": timeZone, - "postalCode": postalCode, - "latitude": latitude, - "longitude": longitude, - "autonomousSystemNumber": autonomousSystemNumber, - "autonomousSystemOrganization": autonomousSystemOrganization, - "isp": isp, - "connectionType": connectionType, - "connectionUsageType": connectionUsageType, - "connectionOrganization": connectionOrganization, - }; - } + /// 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 21405aff..49ef3b0b 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 202355a4..a3a26b61 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 d754130d..ac4eacf3 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 3494b111..ebf593c2 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4d8a2f9b..4baffb71 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index cc664c9f..a0641a28 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 fa385541..3d2e2335 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 2777de7f..a7e5fefc 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 864a5db8..33036476 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index fe5327fc..05cab363 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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/oauth2_consent.dart b/lib/src/models/oauth2_consent.dart new file mode 100644 index 00000000..d927fe3b --- /dev/null +++ b/lib/src/models/oauth2_consent.dart @@ -0,0 +1,78 @@ +part of '../../models.dart'; + +/// OAuth2 Consent +class Oauth2Consent implements Model { + /// Consent ID. + final String $id; + + /// Consent creation time in ISO 8601 format. + final String $createdAt; + + /// Consent update date in ISO 8601 format. + final String $updatedAt; + + /// ID of the user the consent belongs to. + final String userId; + + /// ID of the registered app the consent was given to. Empty for URL-form (CIMD) clients. + final String appId; + + /// Client ID metadata document URL of the client the consent was given to. Empty for registered apps. + final String cimdUrl; + + /// OAuth2 scopes the user consented to. + final List scopes; + + /// RFC 8707 resource indicators the user consented to. + final List resources; + + /// Authorization details the user consented to, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; + + /// Consent expiration time in ISO 8601 format. Empty when the consent has no token-bound expiry yet. + final String expire; + + Oauth2Consent({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.appId, + required this.cimdUrl, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.expire, + }); + + factory Oauth2Consent.fromMap(Map map) { + return Oauth2Consent( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + cimdUrl: map['cimdUrl'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + expire: map['expire'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "appId": appId, + "cimdUrl": cimdUrl, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "expire": expire, + }; + } +} diff --git a/lib/src/models/oauth2_consent_list.dart b/lib/src/models/oauth2_consent_list.dart new file mode 100644 index 00000000..b606f8c1 --- /dev/null +++ b/lib/src/models/oauth2_consent_list.dart @@ -0,0 +1,30 @@ +part of '../../models.dart'; + +/// OAuth2 consents list +class Oauth2ConsentList implements Model { + /// Total number of consents that matched your query. + final int total; + + /// List of consents. + final List consents; + + Oauth2ConsentList({ + required this.total, + required this.consents, + }); + + factory Oauth2ConsentList.fromMap(Map map) { + return Oauth2ConsentList( + total: map['total'], + consents: List.from(map['consents'].map((p) => Oauth2Consent.fromMap(p))), + ); + } + + @override + Map toMap() { + return { + "total": total, + "consents": consents.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_consent_token.dart b/lib/src/models/oauth2_consent_token.dart new file mode 100644 index 00000000..356d7e93 --- /dev/null +++ b/lib/src/models/oauth2_consent_token.dart @@ -0,0 +1,84 @@ +part of '../../models.dart'; + +/// OAuth2 Consent Token +class Oauth2ConsentToken implements Model { + /// Token family ID. + final String $id; + + /// Token creation time in ISO 8601 format. + final String $createdAt; + + /// Token update date in ISO 8601 format. Refreshing the token family updates this. + final String $updatedAt; + + /// ID of the consent the token family was issued under. + final String consentId; + + /// ID of the user the token family belongs to. + final String userId; + + /// ID of the registered app the token family was issued to. Empty for URL-form (CIMD) clients. + final String appId; + + /// Client ID metadata document URL of the client the token family was issued to. Empty for registered apps. + final String cimdUrl; + + /// OAuth2 scopes granted on the token family. + final List scopes; + + /// RFC 8707 resource indicators granted on the token family. + final List resources; + + /// Authorization details granted on the token family, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; + + /// Expiration time of the current access token of this family in ISO 8601 format. + final String expire; + + Oauth2ConsentToken({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.consentId, + required this.userId, + required this.appId, + required this.cimdUrl, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.expire, + }); + + factory Oauth2ConsentToken.fromMap(Map map) { + return Oauth2ConsentToken( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + consentId: map['consentId'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + cimdUrl: map['cimdUrl'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + expire: map['expire'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "consentId": consentId, + "userId": userId, + "appId": appId, + "cimdUrl": cimdUrl, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "expire": expire, + }; + } +} diff --git a/lib/src/models/oauth2_consent_token_list.dart b/lib/src/models/oauth2_consent_token_list.dart new file mode 100644 index 00000000..82e9bf71 --- /dev/null +++ b/lib/src/models/oauth2_consent_token_list.dart @@ -0,0 +1,30 @@ +part of '../../models.dart'; + +/// OAuth2 consent tokens list +class Oauth2ConsentTokenList implements Model { + /// Total number of tokens that matched your query. + final int total; + + /// List of tokens. + final List tokens; + + Oauth2ConsentTokenList({ + required this.total, + required this.tokens, + }); + + factory Oauth2ConsentTokenList.fromMap(Map map) { + return Oauth2ConsentTokenList( + total: map['total'], + tokens: List.from(map['tokens'].map((p) => Oauth2ConsentToken.fromMap(p))), + ); + } + + @override + Map toMap() { + return { + "total": total, + "tokens": tokens.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 60e2abd9..7ac578e2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 1a197fc7..9791d590 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3ca04118..b107afe5 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index d31911de..133fe66d 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index 3d010b1c..aebbe880 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: - List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index a825eab0..c5f233b4 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 5023c633..90efa95f 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 92e4034e..c37de95a 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 4ea12394..d823d0e6 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 450aafd1..850ab8d2 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 c2e8c4dc..742e7590 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 91b888b9..21e65e95 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 e8f1c621..ffca5e98 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b5ea87c8..b05320da 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index b0606dd8..e3f3e43d 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 7f321175..19ea651d 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,30 +2,29 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from( - map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5a6cad30..e3b9536b 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 28e4c43d..7a5e6303 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..83f01b4c 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 72edf5ee..6cebb5b1 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,7 +58,9 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({"type": "ping"})); + _websok!.sink.add(jsonEncode({ + "type": "ping" + })); } }); } @@ -138,11 +140,9 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; + final subscriptions = (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? []; if (subscriptions.isEmpty) { break; @@ -209,15 +209,13 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = - "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -312,11 +310,9 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = - channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -333,7 +329,8 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update({List? channels, List? queries}) async { + Future update( + {List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -420,4 +417,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} +} \ No newline at end of file diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index b0356111..56e7669a 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/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..ce0b7e95 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', - ); + 'Cannot create a client without dart:html or dart:io.', +); diff --git a/pubspec.yaml b/pubspec.yaml index 7009bc3b..98866f5c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 25.3.0 +version: 25.4.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies 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/channel_test.dart b/test/channel_test.dart index 9e0e11d3..62031aec 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,22 +13,12 @@ void main() { }); test('returns database channel with action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), + expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -44,12 +34,7 @@ void main() { }); test('returns tablesdb channel with action', () { - expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), + expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -62,16 +47,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + expect(Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -98,30 +83,29 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index db7b9214..25388fad 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,3 +354,4 @@ void main() { expect(query['method'], 'between'); }); } + diff --git a/test/services/account_test.dart b/test/services/account_test.dart index d5d61fe7..456c6b48 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,1356 +41,1770 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; + group('Account test', () { + late MockClient client; + late Account account; - setUp(() { - client = MockClient(); - account = Account(client); - }); + setUp(() { + client = MockClient(); + account = Account(client); + }); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.get(); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', - test('test method updateEmail()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + }; - test('test method listIdentities()', () async { - final Map data = { - 'total': 5, - 'identities': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.listIdentities(); - expect(response, isA()); - }); - test('test method deleteIdentity()', () async { - final data = ''; + final response = await account.get( + ); + expect(response, isA()); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.deleteIdentity( - identityId: '', - ); - }); + test('test method create()', () async { - test('test method createJWT()', () async { - final Map data = { - 'jwt': - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - }; + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + }; - final response = await account.createJWT(); - expect(response, isA()); - }); - test('test method listLogs()', () async { - final Map data = { - 'total': 5, - 'logs': [], - }; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.listLogs(); - expect(response, isA()); - }); + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - test('test method updateMFA()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - }); + }); - test('test method createMfaAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); + test('test method listConsents()', () async { - test('test method createMFAAuthenticator()', () async { - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'consents': [], - test('test method updateMfaAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); + }; - test('test method updateMFAAuthenticator()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - }); - test('test method deleteMfaAuthenticator()', () async { - final data = ''; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + final response = await account.listConsents( + ); + expect(response, isA()); - test('test method deleteMFAAuthenticator()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method getConsent()', () async { - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'appId': '5e5ea5c16897e', + 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + 'scopes': [], + 'resources': [], + 'authorizationDetails': '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + 'expire': '2020-10-15T06:38:00.000+00:00', - test('test method createMfaChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); + }; - test('test method createMFAChallenge()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - }); - test('test method updateMfaChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMFAChallenge()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - }); - test('test method listMfaFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final response = await account.getConsent( + consentId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.listMfaFactors(); - expect(response, isA()); - }); + test('test method deleteConsent()', () async { - test('test method listMFAFactors()', () async { - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - }; + final data = ''; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.listMFAFactors(); - expect(response, isA()); - }); - test('test method getMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + final response = await account.deleteConsent( + consentId: '', + ); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listConsentTokens()', () async { - final response = await account.getMfaRecoveryCodes(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'tokens': [], - test('test method getMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await account.getMFARecoveryCodes(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.listConsentTokens( + consentId: '', + ); + expect(response, isA()); - final response = await account.createMfaRecoveryCodes(); - expect(response, isA()); - }); + }); - test('test method createMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + test('test method getConsentToken()', () async { - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'consentId': '5e5ea5c16897e', + 'userId': '5e5ea5c16897e', + 'appId': '5e5ea5c16897e', + 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + 'scopes': [], + 'resources': [], + 'authorizationDetails': '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + 'expire': '2020-10-15T06:38:00.000+00:00', - final response = await account.createMFARecoveryCodes(); - expect(response, isA()); - }); + }; - test('test method updateMfaRecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.updateMfaRecoveryCodes(); - expect(response, isA()); - }); - test('test method updateMFARecoveryCodes()', () async { - final Map data = { - 'recoveryCodes': [], - }; + final response = await account.getConsentToken( + consentId: '', + tokenId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await account.updateMFARecoveryCodes(); - expect(response, isA()); - }); + test('test method deleteConsentToken()', () async { - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - }); + final data = ''; - test('test method updatePassword()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updatePhone()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - }); - test('test method getPrefs()', () async { - final Map data = {}; + final response = await account.deleteConsentToken( + consentId: '', + tokenId: '', + ); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateEmail()', () async { - final response = await account.getPrefs(); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', - test('test method updatePrefs()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - }); + }; - test('test method createRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - }); - test('test method updateRecovery()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - test('test method listSessions()', () async { - final Map data = { - 'total': 5, - 'sessions': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); - final response = await account.listSessions(); - expect(response, isA()); - }); + }); - test('test method deleteSessions()', () async { - final data = ''; + test('test method listIdentities()', () async { - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'identities': [], - final response = await account.deleteSessions(); - }); + }; - test('test method createAnonymousSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createAnonymousSession(); - expect(response, isA()); - }); - test('test method createEmailPasswordSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateMagicURLSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); - test('test method createOAuth2Session()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final response = await account.listIdentities( + ); + expect(response, isA()); - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); + }); - test('test method updatePhoneSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + test('test method deleteIdentity()', () async { - test('test method createSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + final data = ''; - test('test method getSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateSession()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - }); - test('test method deleteSession()', () async { - final data = ''; + final response = await account.deleteIdentity( + identityId: '', + ); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createJWT()', () async { - final response = await account.deleteSession( - sessionId: '', - ); - }); + final Map data = { + 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - test('test method updateStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateStatus(); - expect(response, isA()); - }); + }; - test('test method createPushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); - test('test method updatePushTarget()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method deletePushTarget()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.createJWT( + ); + expect(response, isA()); - final response = await account.deletePushTarget( - targetId: '', - ); - }); + }); - test('test method createEmailToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + test('test method listLogs()', () async { - test('test method createMagicURLToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'logs': [], - test('test method createOAuth2Token()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + }; - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - }); - test('test method createPhoneToken()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); - test('test method createVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); - }); + final response = await account.listLogs( + ); + expect(response, isA()); - test('test method updateEmailVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + }); - test('test method updateVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); - }); + test('test method updateMFA()', () async { - test('test method createPhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.createPhoneVerification(); - expect(response, isA()); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); + + }); + + test('test method createMfaAuthenticator()', () async { + + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + + }); + + test('test method createMFAAuthenticator()', () async { + + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + + }); + + test('test method updateMfaAuthenticator()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + + }); + + test('test method updateMFAAuthenticator()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + + }); + + test('test method deleteMfaAuthenticator()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + + test('test method deleteMFAAuthenticator()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); + + test('test method createMfaChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method createMFAChallenge()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + + }); + + test('test method updateMfaChallenge()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + + }); + + test('test method updateMFAChallenge()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + + }); + + test('test method listMfaFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMfaFactors( + ); + expect(response, isA()); + + }); + + test('test method listMFAFactors()', () async { + + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listMFAFactors( + ); + expect(response, isA()); + + }); + + test('test method getMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method getMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method createMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMfaRecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMfaRecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateMFARecoveryCodes()', () async { + + final Map data = { + 'recoveryCodes': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMFARecoveryCodes( + ); + expect(response, isA()); + + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + + }); + + test('test method updatePassword()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updatePhone()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = { + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getPrefs( + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + + }); + + test('test method createRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateRecovery()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method listSessions()', () async { + + final Map data = { + 'total': 5, + 'sessions': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.listSessions( + ); + expect(response, isA()); + + }); + + test('test method deleteSessions()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSessions( + ); + }); + + test('test method createAnonymousSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createAnonymousSession( + ); + expect(response, isA()); + + }); + + test('test method createEmailPasswordSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + + }); + + test('test method updateMagicURLSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Session()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method updatePhoneSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateSession()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSession()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deleteSession( + sessionId: '', + ); + }); + + test('test method updateStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateStatus( + ); + expect(response, isA()); + + }); + + test('test method createPushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method updatePushTarget()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + + }); + + test('test method deletePushTarget()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.deletePushTarget( + targetId: '', + ); + }); + + test('test method createEmailToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createMagicURLToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + + }); + + test('test method createOAuth2Token()', () async { + + + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); + + + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + + }); + + test('test method createPhoneToken()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + + }); + + test('test method createEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method createVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method updateEmailVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method updateVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method createPhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.createPhoneVerification( + ); + expect(response, isA()); + + }); + + test('test method updatePhoneVerification()', () async { + + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + + }); - test('test method updatePhoneVerification()', () async { - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 8d2c48fb..4bdb434d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,123 +41,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); - test('test method getBrowser()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getBrowser()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - }); - test('test method getCreditCard()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - }); + test('test method getCreditCard()', () async { +final Uint8List data = Uint8List.fromList([]); - test('test method getFavicon()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - }); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); - test('test method getFlag()', () async { - final Uint8List data = Uint8List.fromList([]); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFavicon()', () async { +final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getImage()', () async { - final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); - }); + }); - test('test method getInitials()', () async { - final Uint8List data = Uint8List.fromList([]); + test('test method getFlag()', () async { +final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials(); - expect(response, isA()); - }); - test('test method getQR()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); + + test('test method getImage()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + + }); + + test('test method getInitials()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getInitials( + ); + expect(response, isA()); + + }); + + test('test method getQR()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + + }); + + test('test method getScreenshot()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); - }); - test('test method getScreenshot()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a3807093..d4bedd10 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,361 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; + group('Databases test', () { + late MockClient client; + late Databases databases; - setUp(() { - client = MockClient(); - databases = Databases(client); - }); + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [], - final response = await databases.listTransactions(); - expect(response, isA()); - }); + }; - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createTransaction(); - expect(response, isA()); - }); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method deleteTransaction()', () async { - final data = ''; + final response = await databases.listTransactions( + ); + expect(response, isA()); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); + test('test method createTransaction()', () async { - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', - test('test method listDocuments()', () async { - final Map data = { - 'total': 5, - 'documents': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - }); + }; - test('test method createDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method upsertDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); - test('test method updateDocument()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - }); + final response = await databases.createTransaction( + ); + expect(response, isA()); - test('test method deleteDocument()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method getTransaction()', () async { - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', - test('test method decrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); - }); + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listDocuments()', () async { + + final Map data = { + 'total': 5, + 'documents': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + + }); + + test('test method createDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method updateDocument()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteDocument()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); + + test('test method decrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); + + test('test method incrementDocumentAttribute()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + + }); - test('test method incrementDocumentAttribute()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index c6e50a50..734c15a8 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,100 +41,113 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; + group('Functions test', () { + late MockClient client; + late Functions functions; - setUp(() { - client = MockClient(); - functions = Functions(client); - }); + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - test('test method listExecutions()', () async { - final Map data = { - 'total': 5, - 'executions': [], - }; + test('test method listExecutions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'executions': [], - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - }); + }; - test('test method createExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - }); - test('test method getExecution()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method createExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + + }); + + test('test method getExecution()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); + + }); + }); - }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 84b7de1c..c548e414 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,45 +41,47 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method query()', () async { - final data = ''; + test('test method query()', () async { - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final data = ''; - final response = await graphql.query( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await graphql.query( + query: {}, + ); + }); + + test('test method mutation()', () async { + + final data = ''; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method mutation()', () async { - final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); + }); - final response = await graphql.mutation( - query: {}, - ); }); - }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index f9f6489d..842b85da 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,138 +41,184 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; + group('Locale test', () { + late MockClient client; + late Locale locale; - setUp(() { - client = MockClient(); - locale = Locale(client); - }); + setUp(() { + client = MockClient(); + locale = Locale(client); + }); - test('test method get()', () async { - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await locale.get(); - expect(response, isA()); - }); + test('test method get()', () async { - test('test method listCodes()', () async { - final Map data = { - 'total': 5, - 'localeCodes': [], - }; + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD', - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }; - final response = await locale.listCodes(); - expect(response, isA()); - }); - test('test method listContinents()', () async { - final Map data = { - 'total': 5, - 'continents': [], - }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listContinents(); - expect(response, isA()); - }); + final response = await locale.get( + ); + expect(response, isA()); - test('test method listCountries()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listCodes()', () async { - final response = await locale.listCountries(); - expect(response, isA()); - }); + final Map data = { + 'total': 5, + 'localeCodes': [], - test('test method listCountriesEU()', () async { - final Map data = { - 'total': 5, - 'countries': [], - }; + }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCountriesEU(); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method listCountriesPhones()', () async { - final Map data = { - 'total': 5, - 'phones': [], - }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCodes( + ); + expect(response, isA()); - final response = await locale.listCountriesPhones(); - expect(response, isA()); - }); + }); - test('test method listCurrencies()', () async { - final Map data = { - 'total': 5, - 'currencies': [], - }; + test('test method listContinents()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'continents': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listContinents( + ); + expect(response, isA()); + + }); + + test('test method listCountries()', () async { + + final Map data = { + 'total': 5, + 'countries': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountries( + ); + expect(response, isA()); + + }); + + test('test method listCountriesEU()', () async { + + final Map data = { + 'total': 5, + 'countries': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesEU( + ); + expect(response, isA()); + + }); + + test('test method listCountriesPhones()', () async { + + final Map data = { + 'total': 5, + 'phones': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCountriesPhones( + ); + expect(response, isA()); + + }); + + test('test method listCurrencies()', () async { + + final Map data = { + 'total': 5, + 'currencies': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await locale.listCurrencies( + ); + expect(response, isA()); + + }); + + test('test method listLanguages()', () async { + + final Map data = { + 'total': 5, + 'languages': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCurrencies(); - expect(response, isA()); - }); - test('test method listLanguages()', () async { - final Map data = { - 'total': 5, - 'languages': [], - }; + final response = await locale.listLanguages( + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await locale.listLanguages(); - expect(response, isA()); }); - }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 0c938eff..bd05daaf 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,68 +41,73 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; + group('Messaging test', () { + late MockClient client; + late Messaging messaging; - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - test('test method createSubscriber()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - }); + test('test method createSubscriber()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteSubscriber()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method deleteSubscriber()', () async { - final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); + }); - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); }); - }); } diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart new file mode 100644 index 00000000..f203e6ce --- /dev/null +++ b/test/services/organization_test.dart @@ -0,0 +1,177 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod(Invocation.method(#call, [method]), + returnValue: Response()); + } + + @override + Future webAuth( + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + }) async { + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + } +} + +void main() { + group('Organization test', () { + late MockClient client; + late Organization organization; + + setUp(() { + client = MockClient(); + organization = Organization(client); + }); + + test('test method listInstallations()', () async { + + final Map data = { + 'total': 5, + 'installations': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await organization.listInstallations( + ); + expect(response, isA()); + + }); + + test('test method createInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await organization.createInstallation( + appId: '', + ); + expect(response, isA()); + + }); + + test('test method getInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await organization.getInstallation( + installationId: '', + ); + expect(response, isA()); + + }); + + test('test method updateInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await organization.updateInstallation( + installationId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteInstallation()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await organization.deleteInstallation( + installationId: '', + ); + }); + + }); +} diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7fed0439..a15aedc8 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,108 +41,129 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; + group('Presences test', () { + late MockClient client; + late Presences presences; - setUp(() { - client = MockClient(); - presences = Presences(client); - }); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'presences': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'presences': [], - final response = await presences.list(); - expect(response, isA()); - }); + }; - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - }); - test('test method upsert()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method update()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); - }); - test('test method delete()', () async { - final data = ''; + final response = await presences.list( + ); + expect(response, isA()); + + }); + + test('test method get()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method upsert()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + + }); + + test('test method update()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); + }); - final response = await presences.delete( - presenceId: '', - ); }); - }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 55a42f94..15808cd1 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,184 +41,216 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; + group('Storage test', () { + late MockClient client; + late Storage storage; - setUp(() { - client = MockClient(); - storage = Storage(client); - }); + setUp(() { + client = MockClient(); + storage = Storage(client); + }); - test('test method listFiles()', () async { - final Map data = { - 'total': 5, - 'files': [], - }; + test('test method listFiles()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'files': [], - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - }); + }; - test('test method createFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - }); - test('test method getFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateFile()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method deleteFile()', () async { - final data = ''; + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + test('test method createFile()', () async { - test('test method getFileDownload()', () async { - final Uint8List data = Uint8List.fromList([]); + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }; - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); - test('test method getFilePreview()', () async { - final Uint8List data = Uint8List.fromList([]); + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - }); + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + + }); + + test('test method getFile()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method updateFile()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteFile()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + + test('test method getFileDownload()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFilePreview()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + + }); + + test('test method getFileView()', () async { +final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + - test('test method getFileView()', () async { - final Uint8List data = Uint8List.fromList([]); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index f318cad2..3b800ee4 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,297 +41,361 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - test('test method listTransactions()', () async { - final Map data = { - 'total': 5, - 'transactions': [], - }; + test('test method listTransactions()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'transactions': [], - final response = await tablesDB.listTransactions(); - expect(response, isA()); - }); + }; - test('test method createTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createTransaction(); - expect(response, isA()); - }); - test('test method getTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateTransaction()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - }); - test('test method deleteTransaction()', () async { - final data = ''; + final response = await tablesDB.listTransactions( + ); + expect(response, isA()); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); + test('test method createTransaction()', () async { - test('test method createOperations()', () async { - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', - test('test method listRows()', () async { - final Map data = { - 'total': 5, - 'rows': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - }); + }; - test('test method createRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - }); - test('test method getRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method upsertRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); - test('test method updateRow()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - }); + final response = await tablesDB.createTransaction( + ); + expect(response, isA()); - test('test method deleteRow()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method getTransaction()', () async { - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', - test('test method decrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); - }); + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method updateTransaction()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteTransaction()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); + + test('test method createOperations()', () async { + + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + + }); + + test('test method listRows()', () async { + + final Map data = { + 'total': 5, + 'rows': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + + }); + + test('test method createRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + + }); + + test('test method getRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method upsertRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method updateRow()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteRow()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); + + test('test method decrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); + + test('test method incrementRowColumn()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + + }); - test('test method incrementRowColumn()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); }); - }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index 83f2667b..0dfbc4de 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,11 +24,12 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, + { + String? callbackUrlScheme, + } + ) async { + return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -40,288 +41,471 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; + group('Teams test', () { + late MockClient client; + late Teams teams; - setUp(() { - client = MockClient(); - teams = Teams(client); - }); + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - test('test method list()', () async { - final Map data = { - 'total': 5, - 'teams': [], - }; + test('test method list()', () async { - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final Map data = { + 'total': 5, + 'teams': [], - final response = await teams.list(); - expect(response, isA()); - }); + }; - test('test method create()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - }); - test('test method get()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateName()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - }; - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - }); - test('test method delete()', () async { - final data = ''; + final response = await teams.list( + ); + expect(response, isA()); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await teams.delete( - teamId: '', - ); - }); + test('test method create()', () async { - test('test method listMemberships()', () async { - final Map data = { - 'total': 5, - 'memberships': [], - }; + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + }; - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - }); - test('test method createMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - test('test method getMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - }); - test('test method updateMembership()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); - }); + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); - test('test method deleteMembership()', () async { - final data = ''; + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method get()', () async { - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, - test('test method updateMembershipStatus()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - }; - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); - }); + }; - test('test method getPrefs()', () async { - final Map data = {}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method updateName()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + + }); + + test('test method delete()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.delete( + teamId: '', + ); + }); + + test('test method listInstallations()', () async { + + final Map data = { + 'total': 5, + 'installations': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.listInstallations( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method createInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.createInstallation( + teamId: '', + appId: '', + ); + expect(response, isA()); + + }); + + test('test method getInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getInstallation( + teamId: '', + installationId: '', + ); + expect(response, isA()); + + }); + + test('test method updateInstallation()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateInstallation( + teamId: '', + installationId: '', + ); + expect(response, isA()); + + }); + + test('test method deleteInstallation()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.deleteInstallation( + teamId: '', + installationId: '', + ); + }); + + test('test method listMemberships()', () async { + + final Map data = { + 'total': 5, + 'memberships': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method createMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + + }; + + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method getMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + + }); + + test('test method updateMembership()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + + }); + + test('test method deleteMembership()', () async { + + final data = ''; + + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); + + test('test method updateMembershipStatus()', () async { + + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + + }; + + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + + }); + + test('test method getPrefs()', () async { + + final Map data = { + + }; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + + }); + + test('test method updatePrefs()', () async { + + final Map data = { + + }; + + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); - }); - test('test method updatePrefs()', () async { - final Map data = {}; + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); }); - }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 261daa46..15e85f5a 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 3da36624..87a3ca3c 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index e58fa5b5..3b842e6c 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 3bcbb488..49b1e22c 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index b2084927..dd7fa8c3 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,18 +8,16 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index 8c131568..c7d9cdbf 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index d080569c..ae58b57e 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/app_installation_list_test.dart b/test/src/models/app_installation_list_test.dart new file mode 100644 index 00000000..0cc780a1 --- /dev/null +++ b/test/src/models/app_installation_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppInstallationList', () { + test('model', () { + final model = AppInstallationList( + total: 5, + installations: [], + ); + + final map = model.toMap(); + final result = AppInstallationList.fromMap(map); + + expect(result.total, 5); + expect(result.installations, []); + }); + }); +} diff --git a/test/src/models/app_installation_test.dart b/test/src/models/app_installation_test.dart new file mode 100644 index 00000000..3afac34b --- /dev/null +++ b/test/src/models/app_installation_test.dart @@ -0,0 +1,33 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppInstallation', () { + test('model', () { + final model = AppInstallation( + $id: '5e5ea5c16897e', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + appId: '5e5ea5c16897e', + teamId: '5e5ea5c16897e', + scopes: [], + authorizationDetails: {}, + createdById: '5e5ea5c16897e', + createdByName: 'Walter White', + ); + + final map = model.toMap(); + final result = AppInstallation.fromMap(map); + + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.scopes, []); + expect(result.authorizationDetails, {}); + expect(result.createdById, '5e5ea5c16897e'); + expect(result.createdByName, 'Walter White'); + }); + }); +} diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index e71dcae1..8de695b0 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index 85e559f5..d5242a4e 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 6df5c584..869f5db6 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index d5404a7f..bc66ab7b 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index d7410db8..09da675c 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 00e046c7..29890008 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index 217d37e8..f1a5b3cc 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 397b5fab..6c1fbb77 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index 8d209722..cb10c58e 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -13,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 80ef508a..6d9bf33c 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index 8e02f65e..d8e6c95c 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 7f132646..037b5e4d 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -11,6 +11,8 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', $permissions: [], name: 'Pink.png', + folder: 'photos/2026/', + key: 'photos/2026/Pink.png', signature: '5d529fd02b544198ae075bd57c1762bb', mimeType: 'image/png', sizeOriginal: 17890, @@ -24,20 +26,22 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.folder, 'photos/2026/'); + expect(result.key, 'photos/2026/Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 9252b469..489891d4 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 8c35afec..65f562a7 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 525af4ea..708c8c60 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index 93376af1..e616a956 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,15 +5,13 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index a07c0b5f..94c1e33f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index 4a6c96c1..d4087d5e 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index 65b44ad1..b6de5137 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index 88cf157b..f0fcdbce 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 49cb1fc9..72102045 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index b07ca8ee..84c560c8 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index c8211d3b..1b463633 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index 4f30c48e..bb1f0946 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index b2b8bd3d..ab136c24 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 5d3febca..9410baa3 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index 64cc55e4..ed6467d3 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index 500913c8..fa097a49 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 81657394..3f45d288 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,16 +6,14 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/oauth2_consent_list_test.dart b/test/src/models/oauth2_consent_list_test.dart new file mode 100644 index 00000000..07406f01 --- /dev/null +++ b/test/src/models/oauth2_consent_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ConsentList', () { + test('model', () { + final model = Oauth2ConsentList( + total: 5, + consents: [], + ); + + final map = model.toMap(); + final result = Oauth2ConsentList.fromMap(map); + + expect(result.total, 5); + expect(result.consents, []); + }); + }); +} diff --git a/test/src/models/oauth2_consent_test.dart b/test/src/models/oauth2_consent_test.dart new file mode 100644 index 00000000..5a89ec43 --- /dev/null +++ b/test/src/models/oauth2_consent_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Consent', () { + test('model', () { + final model = Oauth2Consent( + $id: '5e5ea5c16897e', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + userId: '5e5ea5c16897e', + appId: '5e5ea5c16897e', + cimdUrl: 'https://example.com/.well-known/client-metadata.json', + scopes: [], + resources: [], + authorizationDetails: '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + expire: '2020-10-15T06:38:00.000+00:00', + ); + + final map = model.toMap(); + final result = Oauth2Consent.fromMap(map); + + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.cimdUrl, 'https://example.com/.well-known/client-metadata.json'); + expect(result.scopes, []); + expect(result.resources, []); + expect(result.authorizationDetails, '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); + }); +} diff --git a/test/src/models/oauth2_consent_token_list_test.dart b/test/src/models/oauth2_consent_token_list_test.dart new file mode 100644 index 00000000..a2271e56 --- /dev/null +++ b/test/src/models/oauth2_consent_token_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ConsentTokenList', () { + test('model', () { + final model = Oauth2ConsentTokenList( + total: 5, + tokens: [], + ); + + final map = model.toMap(); + final result = Oauth2ConsentTokenList.fromMap(map); + + expect(result.total, 5); + expect(result.tokens, []); + }); + }); +} diff --git a/test/src/models/oauth2_consent_token_test.dart b/test/src/models/oauth2_consent_token_test.dart new file mode 100644 index 00000000..39dda758 --- /dev/null +++ b/test/src/models/oauth2_consent_token_test.dart @@ -0,0 +1,37 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ConsentToken', () { + test('model', () { + final model = Oauth2ConsentToken( + $id: '5e5ea5c16897e', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + consentId: '5e5ea5c16897e', + userId: '5e5ea5c16897e', + appId: '5e5ea5c16897e', + cimdUrl: 'https://example.com/.well-known/client-metadata.json', + scopes: [], + resources: [], + authorizationDetails: '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + expire: '2020-10-15T06:38:00.000+00:00', + ); + + final map = model.toMap(); + final result = Oauth2ConsentToken.fromMap(map); + + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.consentId, '5e5ea5c16897e'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.cimdUrl, 'https://example.com/.well-known/client-metadata.json'); + expect(result.scopes, []); + expect(result.resources, []); + expect(result.authorizationDetails, '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); + }); +} diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index bf22a5c7..6ca46a63 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index f70db0e3..d0e5333b 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index 9db30b03..acde349c 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,6 +10,7 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); + }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 46f69af6..57a86348 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index ef2ebe31..edcfe5f5 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index 12693926..d4900dd4 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 564bf303..4e72a449 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index 708e0583..eaab249e 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 689e6048..0177e477 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 7445514c..94c6a502 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index 49f1e75e..a49f3def 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index fe2f4a85..a19b667d 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index f652f2c1..43b2e45c 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 8f0957c9..7ee4b268 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index a524ef71..68023e18 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 0169427f..723ebac2 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index 77c7dd97..c058ea26 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From 30daa7b5d58a8afa8889dd4fa2a699db77f707a3 Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Wed, 5 Aug 2026 06:01:04 +0000 Subject: [PATCH 06/17] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/channel.dart | 20 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/operator.dart | 11 +- lib/query.dart | 89 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 2 +- lib/services/account.dart | 1691 +++++----- lib/services/avatars.dart | 417 +-- lib/services/databases.dart | 603 ++-- lib/services/functions.dart | 115 +- lib/services/graphql.dart | 50 +- lib/services/locale.dart | 142 +- lib/services/messaging.dart | 70 +- lib/services/organization.dart | 139 +- lib/services/presences.dart | 186 +- lib/services/storage.dart | 370 +- lib/services/tables_db.dart | 551 +-- lib/services/teams.dart | 582 ++-- lib/src/client.dart | 4 +- lib/src/client_base.dart | 1 - lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 16 +- lib/src/client_mixin.dart | 9 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/browser_permission.dart | 50 +- lib/src/enums/browser_theme.dart | 14 +- lib/src/enums/credit_card.dart | 44 +- lib/src/enums/execution_method.dart | 24 +- lib/src/enums/execution_status.dart | 20 +- lib/src/enums/execution_trigger.dart | 16 +- lib/src/enums/flag.dart | 400 ++- lib/src/enums/image_format.dart | 24 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 98 +- lib/src/enums/timezone.dart | 848 +++-- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 62 +- lib/src/models/algo_bcrypt.dart | 32 +- lib/src/models/algo_md5.dart | 32 +- lib/src/models/algo_phpass.dart | 32 +- lib/src/models/algo_scrypt.dart | 86 +- lib/src/models/algo_scrypt_modified.dart | 62 +- lib/src/models/algo_sha.dart | 32 +- lib/src/models/app_installation.dart | 122 +- lib/src/models/app_installation_list.dart | 43 +- lib/src/models/continent.dart | 42 +- lib/src/models/continent_list.dart | 43 +- lib/src/models/country.dart | 42 +- lib/src/models/country_list.dart | 43 +- lib/src/models/currency.dart | 110 +- lib/src/models/currency_list.dart | 43 +- lib/src/models/document.dart | 102 +- lib/src/models/document_list.dart | 47 +- lib/src/models/execution.dart | 246 +- lib/src/models/execution_list.dart | 43 +- lib/src/models/file.dart | 218 +- lib/src/models/file_list.dart | 42 +- lib/src/models/headers.dart | 42 +- lib/src/models/identity.dart | 122 +- lib/src/models/identity_list.dart | 43 +- lib/src/models/jwt.dart | 32 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 43 +- lib/src/models/locale.dart | 243 +- lib/src/models/locale_code.dart | 42 +- lib/src/models/locale_code_list.dart | 43 +- lib/src/models/log.dart | 290 +- lib/src/models/log_list.dart | 42 +- lib/src/models/membership.dart | 206 +- lib/src/models/membership_list.dart | 43 +- lib/src/models/mfa_challenge.dart | 62 +- lib/src/models/mfa_factors.dart | 62 +- lib/src/models/mfa_recovery_codes.dart | 32 +- lib/src/models/mfa_type.dart | 42 +- lib/src/models/model.dart | 2 +- lib/src/models/oauth2_consent.dart | 122 +- lib/src/models/oauth2_consent_list.dart | 43 +- lib/src/models/oauth2_consent_token.dart | 132 +- lib/src/models/oauth2_consent_token_list.dart | 43 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 42 +- lib/src/models/preferences.dart | 32 +- lib/src/models/presence.dart | 112 +- lib/src/models/presence_list.dart | 43 +- lib/src/models/row.dart | 102 +- lib/src/models/row_list.dart | 46 +- lib/src/models/session.dart | 360 +- lib/src/models/session_list.dart | 43 +- lib/src/models/subscriber.dart | 112 +- lib/src/models/target.dart | 112 +- lib/src/models/team.dart | 98 +- lib/src/models/team_list.dart | 42 +- lib/src/models/token.dart | 98 +- lib/src/models/transaction.dart | 98 +- lib/src/models/transaction_list.dart | 43 +- lib/src/models/user.dart | 332 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 31 +- lib/src/realtime_response.dart | 10 +- lib/src/realtime_stub.dart | 4 +- test/channel_test.dart | 42 +- test/query_test.dart | 1 - test/services/account_test.dart | 3000 ++++++++--------- test/services/avatars_test.dart | 204 +- test/services/databases_test.dart | 609 ++-- test/services/functions_test.dart | 194 +- test/services/graphql_test.dart | 71 +- test/services/locale_test.dart | 269 +- test/services/messaging_test.dart | 124 +- test/services/organization_test.dart | 226 +- test/services/presences_test.dart | 210 +- test/services/storage_test.dart | 361 +- test/services/tables_db_test.dart | 609 ++-- test/services/teams_test.dart | 783 ++--- test/src/models/algo_argon2_test.dart | 10 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 14 +- test/src/models/algo_scrypt_test.dart | 12 +- test/src/models/algo_sha_test.dart | 4 +- .../models/app_installation_list_test.dart | 6 +- test/src/models/app_installation_test.dart | 20 +- test/src/models/continent_list_test.dart | 6 +- test/src/models/continent_test.dart | 6 +- test/src/models/country_list_test.dart | 6 +- test/src/models/country_test.dart | 6 +- test/src/models/currency_list_test.dart | 6 +- test/src/models/currency_test.dart | 16 +- test/src/models/document_list_test.dart | 6 +- test/src/models/document_test.dart | 16 +- test/src/models/execution_list_test.dart | 6 +- test/src/models/execution_test.dart | 36 +- test/src/models/file_list_test.dart | 6 +- test/src/models/file_test.dart | 34 +- test/src/models/headers_test.dart | 6 +- test/src/models/identity_list_test.dart | 6 +- test/src/models/identity_test.dart | 22 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_list_test.dart | 6 +- test/src/models/language_test.dart | 8 +- test/src/models/locale_code_list_test.dart | 6 +- test/src/models/locale_code_test.dart | 6 +- test/src/models/locale_test.dart | 16 +- test/src/models/log_list_test.dart | 6 +- test/src/models/log_test.dart | 46 +- test/src/models/membership_list_test.dart | 6 +- test/src/models/membership_test.dart | 32 +- test/src/models/mfa_challenge_test.dart | 10 +- test/src/models/mfa_factors_test.dart | 10 +- test/src/models/mfa_recovery_codes_test.dart | 4 +- test/src/models/mfa_type_test.dart | 10 +- test/src/models/oauth2_consent_list_test.dart | 6 +- test/src/models/oauth2_consent_test.dart | 27 +- .../oauth2_consent_token_list_test.dart | 6 +- .../src/models/oauth2_consent_token_test.dart | 29 +- test/src/models/phone_list_test.dart | 6 +- test/src/models/phone_test.dart | 8 +- test/src/models/preferences_test.dart | 1 - test/src/models/presence_list_test.dart | 6 +- test/src/models/presence_test.dart | 14 +- test/src/models/row_list_test.dart | 6 +- test/src/models/row_test.dart | 16 +- test/src/models/session_list_test.dart | 6 +- test/src/models/session_test.dart | 60 +- test/src/models/subscriber_test.dart | 36 +- test/src/models/target_test.dart | 18 +- test/src/models/team_list_test.dart | 6 +- test/src/models/team_test.dart | 12 +- test/src/models/token_test.dart | 14 +- test/src/models/transaction_list_test.dart | 6 +- test/src/models/transaction_test.dart | 14 +- test/src/models/user_test.dart | 32 +- 180 files changed, 9490 insertions(+), 9839 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index bc955b6c..f55bd86a 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.9.x. +/// This SDK is compatible with Appwrite server version 1.9.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/channel.dart b/lib/channel.dart index d511f5a4..afc68efa 100644 --- a/lib/channel.dart +++ b/lib/channel.dart @@ -2,19 +2,33 @@ part of appwrite; // Marker classes for type safety class _Root {} + class _Database {} + class _Collection {} + class _Document {} + class _TablesDB {} + class _Table {} + class _Row {} + class _Bucket {} + class _File {} + class _Func {} + class _Execution {} + class _Team {} + class _Membership {} + class _Presence {} + class _Resolved {} // Helper function for normalizing ID @@ -99,15 +113,15 @@ extension DatabaseChannel on Channel<_Database> { /// Only available on Channel<_Collection> extension CollectionChannel on Channel<_Collection> { - Channel<_Document> document([String? id]) => _next<_Document>('documents', id); + Channel<_Document> document([String? id]) => + _next<_Document>('documents', id); } // --- TABLESDB ROUTE --- /// Only available on Channel<_TablesDB> extension TablesDBChannel on Channel<_TablesDB> { - Channel<_Table> table(String id) => - _next<_Table>('tables', id); + Channel<_Table> table(String id) => _next<_Table>('tables', id); } /// Only available on Channel<_Table> 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/operator.dart b/lib/operator.dart index 9dd7f4c7..337dda30 100644 --- a/lib/operator.dart +++ b/lib/operator.dart @@ -31,7 +31,7 @@ class Operator { result['method'] = method; - if(values != null) { + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -147,8 +147,7 @@ class Operator { Operator._('arrayRemove', [value]).toString(); /// Remove duplicate values from an array attribute. - static String arrayUnique() => - Operator._('arrayUnique', []).toString(); + static String arrayUnique() => Operator._('arrayUnique', []).toString(); /// Keep only values that exist in both the current array and the provided array. static String arrayIntersect(List values) => @@ -173,8 +172,7 @@ class Operator { Operator._('stringReplace', [search, replace]).toString(); /// Toggle a boolean attribute. - static String toggle() => - Operator._('toggle', []).toString(); + static String toggle() => Operator._('toggle', []).toString(); /// Add days to a date attribute. static String dateAddDays(int days) => @@ -185,6 +183,5 @@ class Operator { Operator._('dateSubDays', [days]).toString(); /// Set a date attribute to the current date and time. - static String dateSetNow() => - Operator._('dateSetNow', []).toString(); + static String dateSetNow() => Operator._('dateSetNow', []).toString(); } diff --git a/lib/query.dart b/lib/query.dart index 2221a6e6..2772116a 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -10,14 +10,14 @@ class Query { Map toJson() { final result = {}; - + result['method'] = method; - - if(attribute != null) { + + if (attribute != null) { result['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { result['values'] = values is List ? values : [values]; } @@ -28,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. @@ -140,50 +140,46 @@ class Query { Query._('notEndsWith', attribute, value).toString(); /// Filter resources where document was created before [value]. - static String createdBefore(String value) => - lessThan('\$createdAt', value); + static String createdBefore(String value) => lessThan('\$createdAt', value); /// Filter resources where document was created after [value]. - static String createdAfter(String value) => - greaterThan('\$createdAt', value); + static String createdAfter(String value) => greaterThan('\$createdAt', value); /// Filter resources where document was created between [start] and [end] (inclusive). static String createdBetween(String start, String end) => between('\$createdAt', start, end); /// Filter resources where document was updated before [value]. - static String updatedBefore(String value) => - lessThan('\$updatedAt', value); + static String updatedBefore(String value) => lessThan('\$updatedAt', value); /// Filter resources where document was updated after [value]. - static String updatedAfter(String value) => - greaterThan('\$updatedAt', value); + static String updatedAfter(String value) => greaterThan('\$updatedAt', value); /// Filter resources where document was updated between [start] and [end] (inclusive). static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => @@ -198,18 +194,17 @@ class Query { Query._('orderDesc', attribute).toString(); /// Sort results randomly. - static String orderRandom() => - Query._('orderRandom').toString(); + static String orderRandom() => Query._('orderRandom').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(); /// 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) => @@ -219,27 +214,43 @@ class Query { 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(); /// Filter resources where [attribute] is at a specific distance from the given coordinates. - static String distanceEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. - static String distanceNotEqual(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceNotEqual', attribute, [[values, distance, meters]]).toString(); + static String distanceNotEqual( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceNotEqual', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. - static String distanceGreaterThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceGreaterThan', attribute, [[values, distance, meters]]).toString(); + static String distanceGreaterThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceGreaterThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. - static String distanceLessThan(String attribute, List values, num distance, [bool meters = true]) => - Query._('distanceLessThan', attribute, [[values, distance, meters]]).toString(); + static String distanceLessThan( + String attribute, List values, num distance, + [bool meters = true]) => + Query._('distanceLessThan', attribute, [ + [values, distance, meters] + ]).toString(); /// Filter resources using vector dot product similarity. static String vectorDot(String attribute, List vector) => 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 3f91a53a..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -63,4 +63,4 @@ class Role { 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 8f8238ae..3b8fbded 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1,6 +1,6 @@ part of '../appwrite.dart'; - /// The Account service allows you to authenticate and manage a user account. +/// The Account service allows you to authenticate and manage a user account. class Account extends Service { /// Initializes a [Account] service Account(super.client); @@ -9,18 +9,17 @@ class Account extends Service { Future get() async { final String apiPath = '/account'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to allow a new user to register a new account in your @@ -30,154 +29,160 @@ class Account extends Service { /// 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 { + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { final String apiPath = '/account'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - 'password': password, - - if (name != null) 'name': name, - - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + if (name != null) 'name': name, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get a list of the OAuth2 consents the current user has given to third-party /// apps. - Future listConsents({List? queries, bool? total}) async { + Future listConsents( + {List? queries, bool? total}) async { final String apiPath = '/account/consents'; - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Oauth2ConsentList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Oauth2ConsentList.fromMap(res.data); } /// Get an OAuth2 consent the current user has given to a third-party app by /// its unique ID. Future getConsent({required String consentId}) async { - final String apiPath = '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); + final String apiPath = + '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Oauth2Consent.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Oauth2Consent.fromMap(res.data); } /// Delete an OAuth2 consent by its unique ID. All token families issued under /// the consent are revoked, and the app must ask for consent again to regain /// access. Future deleteConsent({required String consentId}) async { - final String apiPath = '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); - - final Map apiParams = { - }; + final String apiPath = + '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Get a list of the token families issued under an OAuth2 consent. Each entry /// represents one authorized device or session; the token secrets themselves /// are never returned. - Future listConsentTokens({required String consentId, List? queries, bool? total}) async { - final String apiPath = '/account/consents/{consentId}/tokens'.replaceAll('{consentId}', consentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; + Future listConsentTokens( + {required String consentId, List? queries, bool? total}) async { + final String apiPath = '/account/consents/{consentId}/tokens' + .replaceAll('{consentId}', consentId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Oauth2ConsentTokenList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Oauth2ConsentTokenList.fromMap(res.data); } /// Get a token family issued under an OAuth2 consent by its unique ID. The /// token secrets themselves are never returned. - Future getConsentToken({required String consentId, required String tokenId}) async { - final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}'.replaceAll('{consentId}', consentId).replaceAll('{tokenId}', tokenId); + Future getConsentToken( + {required String consentId, required String tokenId}) async { + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' + .replaceAll('{consentId}', consentId) + .replaceAll('{tokenId}', tokenId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Oauth2ConsentToken.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Oauth2ConsentToken.fromMap(res.data); } /// Delete a token family issued under an OAuth2 consent by its unique ID. The /// access and refresh tokens of the family stop working immediately; other /// token families and the consent itself are unaffected. - Future deleteConsentToken({required String consentId, required String tokenId}) async { - final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}'.replaceAll('{consentId}', consentId).replaceAll('{tokenId}', tokenId); - - final Map apiParams = { - }; + Future deleteConsentToken( + {required String consentId, required String tokenId}) async { + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' + .replaceAll('{consentId}', consentId) + .replaceAll('{tokenId}', tokenId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Update currently logged in user account email address. After changing user @@ -187,66 +192,65 @@ class Account extends Service { /// 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 { + /// + Future updateEmail( + {required String email, required String password}) async { final String apiPath = '/account/email'; - final Map apiParams = { - 'email': email, - - 'password': password, - - }; + final Map apiParams = { + 'email': email, + 'password': password, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries, bool? total}) async { + Future listIdentities( + {List? queries, bool? total}) async { final String apiPath = '/account/identities'; - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.IdentityList.fromMap(res.data); } /// 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 String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT @@ -257,20 +261,20 @@ class Account extends Service { Future createJWT({int? duration}) async { final String apiPath = '/account/jwts'; - final Map apiParams = { - if (duration != null) 'duration': duration, + final Map apiParams = { + if (duration != null) 'duration': duration, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Jwt.fromMap(res.data); } /// Get the list of latest security activity logs for the currently logged in @@ -278,212 +282,224 @@ class Account extends Service { Future listLogs({List? queries, bool? total}) async { final String apiPath = '/account/logs'; - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (total != null) 'total': total, - - }; + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. Future updateMFA({required bool mfa}) async { final String apiPath = '/account/mfa'; - final Map apiParams = { - 'mfa': mfa, - - }; + final Map apiParams = { + 'mfa': mfa, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// 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); + Future createMFAAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaType.fromMap(res.data); } /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - 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, + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') + 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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, + 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'factor': factor.value, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// 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 { + Future createMFAChallenge( + {required enums.AuthenticationFactor factor}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'factor': factor.value, + final Map apiParams = { + 'factor': factor.value, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaChallenge.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -491,26 +507,27 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge({required String challengeId, required String otp}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - - 'otp': otp, - - }; + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Complete the MFA challenge by providing the one-time password. Finish the @@ -518,84 +535,83 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge({required String challengeId, required String otp}) async { + Future updateMFAChallenge( + {required String challengeId, required String otp}) async { final String apiPath = '/account/mfa/challenges'; - final Map apiParams = { - 'challengeId': challengeId, - - 'otp': otp, - - }; + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. Future listMFAFactors() async { final String apiPath = '/account/mfa/factors'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaFactors.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Get recovery codes that can be used as backup for MFA flow. Before getting @@ -605,18 +621,17 @@ class Account extends Service { Future getMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -624,22 +639,23 @@ class Account extends Service { /// authehticator. Recovery codes can be used as a MFA verification type in /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Generate recovery codes as backup for MFA flow. It's recommended to @@ -650,40 +666,41 @@ class Account extends Service { Future createMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Regenerate recovery codes that can be used as backup for MFA flow. Before @@ -693,62 +710,62 @@ class Account extends Service { Future updateMFARecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.MfaRecoveryCodes.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. Future updateName({required String name}) async { final String apiPath = '/account/name'; - final Map apiParams = { - 'name': name, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'name': name, + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// 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 { + Future updatePassword( + {required String password, String? oldPassword}) async { final String apiPath = '/account/password'; - final Map apiParams = { - 'password': password, + final Map apiParams = { + 'password': password, + if (oldPassword != null) 'oldPassword': oldPassword, + }; - if (oldPassword != null) 'oldPassword': oldPassword, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Update the currently logged in user's phone number. After updating the @@ -756,43 +773,42 @@ class Account extends Service { /// 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 { + Future updatePhone( + {required String phone, required String password}) async { final String apiPath = '/account/phone'; - final Map apiParams = { - 'phone': phone, - - 'password': password, + final Map apiParams = { + 'phone': phone, + 'password': password, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Get the preferences as a key-value object for the currently logged in user. Future getPrefs() async { final String apiPath = '/account/prefs'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// Update currently logged in user account preferences. The object you pass is @@ -801,20 +817,20 @@ class Account extends Service { Future updatePrefs({required Map prefs}) async { final String apiPath = '/account/prefs'; - final Map apiParams = { - 'prefs': prefs, - - }; + final Map apiParams = { + 'prefs': prefs, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Sends the user an email with a temporary secret key for password reset. @@ -825,25 +841,25 @@ class Account extends Service { /// /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 { + Future createRecovery( + {required String email, required String url}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'email': email, - - 'url': url, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'email': email, + 'url': url, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to complete the user account password reset. Both the @@ -851,32 +867,33 @@ class Account extends Service { /// 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 { + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { final String apiPath = '/account/recovery'; - final Map apiParams = { - 'userId': userId, + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; - 'secret': secret, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - 'password': password, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Get the list of active sessions across different devices for the currently @@ -884,18 +901,17 @@ class Account extends Service { Future listSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.SessionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.SessionList.fromMap(res.data); } /// Delete all sessions from the user account and remove any sessions cookies @@ -903,18 +919,17 @@ class Account extends Service { Future deleteSessions() async { final String apiPath = '/account/sessions'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to allow a new user to register an anonymous account in @@ -927,213 +942,216 @@ class Account extends Service { Future createAnonymousSession() async { final String apiPath = '/account/sessions/anonymous'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createEmailPasswordSession( + {required String email, required String password}) async { final String apiPath = '/account/sessions/email'; - final Map apiParams = { - 'email': email, - - 'password': password, - - }; + final Map apiParams = { + 'email': email, + 'password': password, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updateMagicURLSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + /// + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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)}'); - } - }); + } + } 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('&') - ); + 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); + return client.webAuth(url, callbackUrlScheme: success); } /// 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. - @Deprecated('This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') + Future updatePhoneSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 { + Future createSession( + {required String userId, required String secret}) async { final String apiPath = '/account/sessions/token'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Session.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Session.fromMap(res.data); } /// Logout the user. Use 'current' as the session ID to logout on this device, @@ -1142,20 +1160,20 @@ class Account extends Service { /// 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 String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Block the currently logged in user account. Behind the scene, the user @@ -1164,18 +1182,18 @@ class Account extends Service { Future updateStatus() async { final String apiPath = '/account/status'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.User.fromMap(res.data); + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.User.fromMap(res.data); } /// Use this endpoint to register a device for push notifications. Provide a @@ -1183,27 +1201,28 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { final String apiPath = '/account/targets/push'; - final Map apiParams = { - 'targetId': targetId, - - 'identifier': identifier, - - if (providerId != null) 'providerId': providerId, + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + if (providerId != null) 'providerId': providerId, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Update the currently logged in user's push notification target. You can @@ -1211,43 +1230,45 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - - }; + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'identifier': identifier, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Target.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Target.fromMap(res.data); } /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Sends the user an email with a secret key for creating a session. If the @@ -1259,32 +1280,31 @@ class Account extends Service { /// /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 { + /// + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { final String apiPath = '/account/tokens/email'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - if (phrase != null) 'phrase': phrase, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + if (phrase != null) 'phrase': phrase, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Sends the user an email with a secret key for creating a session. If the @@ -1296,87 +1316,88 @@ class Account extends Service { /// /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. - /// + /// /// A user 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 { + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { final String apiPath = '/account/tokens/magic-url'; - final Map apiParams = { - 'userId': userId, - - 'email': email, - - if (url != null) 'url': url, - - if (phrase != null) 'phrase': phrase, - - }; + final Map apiParams = { + 'userId': userId, + 'email': email, + if (url != null) 'url': url, + if (phrase != null) 'phrase': phrase, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - /// + /// 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 = { - - if (success != null) 'success': success, - - if (failure != null) 'failure': failure, - - if (scopes != null) 'scopes': scopes, - - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add( + 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 = { + if (success != null) 'success': success, + if (failure != null) 'failure': failure, + if (scopes != null) '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)}'); - } - }); + } + } 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('&') - ); + 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); + return client.webAuth(url, callbackUrlScheme: success); } /// Sends the user an SMS with a secret key for creating a session. If the @@ -1385,29 +1406,29 @@ class Account extends Service { /// /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 { + Future createPhoneToken( + {required String userId, required String phone}) async { final String apiPath = '/account/tokens/phone'; - final Map apiParams = { - 'userId': userId, + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; - 'phone': phone, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1419,29 +1440,29 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'url': url, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification message to your user email address @@ -1453,81 +1474,83 @@ class Account extends Service { /// 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. - /// - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') + /// + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') Future createVerification({required String url}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'url': url, + final Map apiParams = { + 'url': url, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 updateEmailVerification({required String userId, required String secret}) async { + Future updateEmailVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification({required String userId, required String secret}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') + Future updateVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/email'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// Use this endpoint to send a verification SMS to the currently logged in @@ -1541,42 +1564,42 @@ class Account extends Service { Future createPhoneVerification() async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Token.fromMap(res.data); } /// 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 { + Future updatePhoneVerification( + {required String userId, required String secret}) async { final String apiPath = '/account/verifications/phone'; - final Map apiParams = { - 'userId': userId, - - 'secret': secret, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Token.fromMap(res.data); + 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 e422f227..2fe54e87 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Avatars service aims to help you complete everyday tasks related to - /// your app image, icons, and avatars. +/// 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); @@ -11,149 +11,164 @@ class Avatars extends Service { /// /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 apiParams = { - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + 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 apiParams = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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 apiParams = { - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + /// + 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 apiParams = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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 { final String apiPath = '/avatars/favicon'; - final Map apiParams = { - 'url': url, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/*', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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 apiParams = { - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + /// + 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 apiParams = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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 { + Future getImage( + {required String url, int? width, int? height}) async { final String apiPath = '/avatars/image'; - final Map apiParams = { - 'url': url, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/*', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + final Map apiParams = { + 'url': url, + if (width != null) 'width': width, + if (height != null) 'height': height, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to show your user initials avatar icon on your website or @@ -161,131 +176,135 @@ class Avatars extends Service { /// 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 { + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { final String apiPath = '/avatars/initials'; - final Map apiParams = { - if (name != null) 'name': name, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (background != null) 'background': background, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + final Map apiParams = { + if (name != null) 'name': name, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (background != null) 'background': background, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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 { + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { final String apiPath = '/avatars/qr'; - final Map apiParams = { - 'text': text, - - if (size != null) 'size': size, - - if (margin != null) 'margin': margin, - - if (download != null) 'download': download, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + final Map apiParams = { + 'text': text, + if (size != null) 'size': size, + if (margin != null) 'margin': margin, + if (download != null) 'download': download, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot({required String url, Map? headers, int? viewportWidth, int? viewportHeight, double? scale, enums.BrowserTheme? theme, String? userAgent, bool? fullpage, String? locale, enums.Timezone? timezone, double? latitude, double? longitude, double? accuracy, bool? touch, List? permissions, int? sleep, int? width, int? height, int? quality, enums.ImageFormat? output}) async { + Future getScreenshot( + {required String url, + Map? headers, + int? viewportWidth, + int? viewportHeight, + double? scale, + enums.BrowserTheme? theme, + String? userAgent, + bool? fullpage, + String? locale, + enums.Timezone? timezone, + double? latitude, + double? longitude, + double? accuracy, + bool? touch, + List? permissions, + int? sleep, + int? width, + int? height, + int? quality, + enums.ImageFormat? output}) async { final String apiPath = '/avatars/screenshots'; - final Map apiParams = { - 'url': url, - - if (headers != null) 'headers': headers, - - if (viewportWidth != null) 'viewportWidth': viewportWidth, - - if (viewportHeight != null) 'viewportHeight': viewportHeight, - - if (scale != null) 'scale': scale, - - if (theme != null) 'theme': theme.value, - - if (userAgent != null) 'userAgent': userAgent, - - if (fullpage != null) 'fullpage': fullpage, - - if (locale != null) 'locale': locale, - - if (timezone != null) 'timezone': timezone.value, - - if (latitude != null) 'latitude': latitude, - - if (longitude != null) 'longitude': longitude, - - if (accuracy != null) 'accuracy': accuracy, - - if (touch != null) 'touch': touch, - - if (permissions != null) 'permissions': permissions.map((e) => e.value).toList(), - - if (sleep != null) 'sleep': sleep, - - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (quality != null) 'quality': quality, - - if (output != null) 'output': output.value, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/png', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + final Map apiParams = { + 'url': url, + if (headers != null) 'headers': headers, + if (viewportWidth != null) 'viewportWidth': viewportWidth, + if (viewportHeight != null) 'viewportHeight': viewportHeight, + if (scale != null) 'scale': scale, + if (theme != null) 'theme': theme.value, + if (userAgent != null) 'userAgent': userAgent, + if (fullpage != null) 'fullpage': fullpage, + if (locale != null) 'locale': locale, + if (timezone != null) 'timezone': timezone.value, + if (latitude != null) 'latitude': latitude, + if (longitude != null) 'longitude': longitude, + if (accuracy != null) 'accuracy': accuracy, + if (touch != null) 'touch': touch, + if (permissions != null) + 'permissions': permissions.map((e) => e.value).toList(), + if (sleep != null) 'sleep': sleep, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + if (output != null) 'output': output.value, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/png', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/databases.dart b/lib/services/databases.dart index c791ea0e..d298cec0 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -1,339 +1,418 @@ part of '../appwrite.dart'; - /// The Databases service allows you to create structured collections of - /// documents, query and filter lists of documents +/// 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 transactions across all databases. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions({List? queries}) async { + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') + Future listTransactions( + {List? queries}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') Future createTransaction({int? ttl}) async { final String apiPath = '/databases/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/databases/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (operations != null) 'operations': operations, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments({required String databaseId, required String collectionId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); } /// 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - - 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Create or update a 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. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') + Future upsertDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (data != null) 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Delete a document by its unique ID. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument({required String databaseId, required String collectionId, required String documentId, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? min, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - if (min != null) 'min': min, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') + Future decrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + if (min != null) 'min': min, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } /// Increment a specific attribute of a document by a given value. - @Deprecated('This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute({required String databaseId, required String collectionId, required String documentId, required String attribute, double? value, double? max, String? transactionId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId).replaceAll('{attribute}', attribute); - - final Map apiParams = { - if (value != null) 'value': value, - - if (max != null) 'max': max, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - + @Deprecated( + 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') + Future incrementDocumentAttribute( + {required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId) + .replaceAll('{attribute}', attribute); + + final Map apiParams = { + if (value != null) 'value': value, + if (max != null) 'max': max, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); } } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 49236018..6cde02ed 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -1,82 +1,87 @@ part of '../appwrite.dart'; - /// The Functions Service allows you view, create and manage your Cloud - /// Functions. +/// The Functions Service allows you view, create and manage your Cloud +/// Functions. class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + Future listExecutions( + {required String functionId, List? queries, bool? total}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ExecutionList.fromMap(res.data); } /// 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 = { - if (body != null) 'body': body, - - if (xasync != null) 'async': xasync, - - if (path != null) 'path': path, - - if (method != null) 'method': method.value, - - if (headers != null) 'headers': headers, - - if (scheduledAt != null) 'scheduledAt': scheduledAt, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - + 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 = { + if (body != null) 'body': body, + if (xasync != null) 'async': xasync, + if (path != null) 'path': path, + if (method != null) 'method': method.value, + if (headers != null) 'headers': headers, + if (scheduledAt != null) 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); } /// 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 = { - }; + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Execution.fromMap(res.data); + 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 978331fa..c86f3719 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The GraphQL API allows you to query and mutate your Appwrite server using - /// GraphQL. +/// 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); @@ -10,39 +10,41 @@ class Graphql extends Service { Future query({required Map query}) async { final String apiPath = '/graphql'; - final Map apiParams = { - 'query': query, + final Map apiParams = { + 'query': query, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Execute a GraphQL mutation. Future mutation({required Map query}) async { final String apiPath = '/graphql/mutation'; - final Map apiParams = { - 'query': query, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'x-sdk-graphql': 'true', 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'query': query, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + 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 c45a1269..87ea162e 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -1,7 +1,7 @@ part of '../appwrite.dart'; - /// The Locale service allows you to customize your app based on your users' - /// location. +/// 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); @@ -10,23 +10,22 @@ class Locale extends Service { /// 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 { final String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Locale.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Locale.fromMap(res.data); } /// List of all locale codes in [ISO @@ -34,18 +33,17 @@ class Locale extends Service { Future listCodes() async { final String apiPath = '/locale/codes'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); } /// List of all continents. You can use the locale header to get the data in a @@ -53,18 +51,17 @@ class Locale extends Service { Future listContinents() async { final String apiPath = '/locale/continents'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ContinentList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.ContinentList.fromMap(res.data); } /// List of all countries. You can use the locale header to get the data in a @@ -72,18 +69,17 @@ class Locale extends Service { Future listCountries() async { final String apiPath = '/locale/countries'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '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 of all countries that are currently members of the EU. You can use the @@ -91,18 +87,17 @@ class Locale extends Service { Future listCountriesEU() async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - 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 of all countries phone codes. You can use the locale header to get the @@ -110,18 +105,17 @@ class Locale extends Service { Future listCountriesPhones() async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.PhoneList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PhoneList.fromMap(res.data); } /// List of all currencies, including currency symbol, name, plural, and @@ -130,18 +124,17 @@ class Locale extends Service { Future listCurrencies() async { final String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.CurrencyList.fromMap(res.data); } /// List of all languages classified by ISO 639-1 including 2-letter code, name @@ -149,17 +142,16 @@ class Locale extends Service { Future listLanguages() async { final String apiPath = '/locale/languages'; - final Map apiParams = { - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.LanguageList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.LanguageList.fromMap(res.data); } } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 3dffe41b..61ecefee 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -1,48 +1,54 @@ part of '../appwrite.dart'; - /// The Messaging service allows you to send messages to any provider type - /// (SMTP, push notification, SMS, etc.). +/// 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 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); } /// 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 = { - }; + 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 apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } } diff --git a/lib/services/organization.dart b/lib/services/organization.dart index f0ad5cfd..68275296 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -1,116 +1,121 @@ part of '../appwrite.dart'; - /// The Organization service allows you to manage organization-level projects. +/// The Organization service allows you to manage organization-level projects. class Organization extends Service { /// Initializes a [Organization] service Organization(super.client); /// List app installations on the organization. Any organization member can /// read installations. - Future listInstallations({List? queries, bool? total}) async { + Future listInstallations( + {List? queries, bool? total}) async { final String apiPath = '/organization/installations'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallationList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallationList.fromMap(res.data); } /// Install an app on the organization. Only organization members with the /// owner role can install apps. The installation is granted the scopes the app /// currently requests. - Future createInstallation({required String appId, String? authorizationDetails}) async { + Future createInstallation( + {required String appId, String? authorizationDetails}) async { final String apiPath = '/organization/installations'; - final Map apiParams = { - 'appId': appId, - - if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, + final Map apiParams = { + 'appId': appId, + if (authorizationDetails != null) + 'authorizationDetails': authorizationDetails, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallation.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallation.fromMap(res.data); } /// Get an app installation on the organization by its unique ID. Any /// organization member can read installations. - Future getInstallation({required String installationId}) async { - final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); - - final Map apiParams = { - }; + Future getInstallation( + {required String installationId}) async { + final String apiPath = '/organization/installations/{installationId}' + .replaceAll('{installationId}', installationId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.AppInstallation.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallation.fromMap(res.data); } /// Update an app installation on the organization. Only organization members /// with the owner role can update installations. The installation's granted /// scopes are refreshed to the scopes the app currently requests; previously /// issued installation access tokens are revoked. - Future updateInstallation({required String installationId, String? authorizationDetails}) async { - final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); - - final Map apiParams = { - if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallation.fromMap(res.data); - + Future updateInstallation( + {required String installationId, String? authorizationDetails}) async { + final String apiPath = '/organization/installations/{installationId}' + .replaceAll('{installationId}', installationId); + + final Map apiParams = { + if (authorizationDetails != null) + 'authorizationDetails': authorizationDetails, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); } /// Uninstall an app from the organization by its installation ID. Only /// organization members with the owner role can remove installations. /// Previously issued installation access tokens are revoked. Future deleteInstallation({required String installationId}) async { - final String apiPath = '/organization/installations/{installationId}'.replaceAll('{installationId}', installationId); - - final Map apiParams = { - }; + final String apiPath = '/organization/installations/{installationId}' + .replaceAll('{installationId}', installationId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index 4e0803d8..fd5d6be2 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -1,129 +1,133 @@ part of '../appwrite.dart'; - /// The Presences service allows you to track and manage real-time user - /// presence in your project. +/// The Presences service allows you to track and manage real-time user +/// presence in your project. class Presences extends Service { /// Initializes a [Presences] service Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list({List? queries, bool? total, int? ttl}) async { + /// + Future list( + {List? queries, bool? total, int? ttl}) async { final String apiPath = '/presences'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; - if (total != null) 'total': total, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.PresenceList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// + /// Future get({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert({required String presenceId, required String status, List? permissions, String? expiresAt, Map? metadata}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - 'status': status, - - if (permissions != null) 'permissions': permissions, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future upsert( + {required String presenceId, + required String status, + List? permissions, + String? expiresAt, + Map? metadata}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + 'status': status, + if (permissions != null) 'permissions': permissions, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update({required String presenceId, String? status, String? expiresAt, Map? metadata, List? permissions, bool? purge}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - if (status != null) 'status': status, - - if (expiresAt != null) 'expiresAt': expiresAt, - - if (metadata != null) 'metadata': metadata, - - if (permissions != null) 'permissions': permissions, - - if (purge != null) 'purge': purge, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Presence.fromMap(res.data); - + /// + Future update( + {required String presenceId, + String? status, + String? expiresAt, + Map? metadata, + List? permissions, + bool? purge}) async { + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + + final Map apiParams = { + if (status != null) 'status': status, + if (expiresAt != null) 'expiresAt': expiresAt, + if (metadata != null) 'metadata': metadata, + if (permissions != null) 'permissions': permissions, + if (purge != null) 'purge': purge, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Presence.fromMap(res.data); } /// Delete a presence log by its unique ID. - /// + /// Future delete({required String presenceId}) async { - final String apiPath = '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - - final Map apiParams = { - }; + final String apiPath = + '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + 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 fc609bb6..d261ef17 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -1,170 +1,186 @@ part of '../appwrite.dart'; - /// The Storage service allows you to manage your project files. +/// The Storage service allows you to manage your project files. class Storage extends Service { /// Initializes a [Storage] service Storage(super.client); /// 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, bool? total}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - + Future listFiles( + {required String bucketId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); } /// 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, String? folder, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - - 'file': file, - - if (permissions != null) 'permissions': permissions, - - if (folder != null) 'folder': folder, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'multipart/form-data', 'accept': 'application/json', - }; - - 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); - + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + String? folder, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + if (permissions != null) 'permissions': permissions, + if (folder != null) 'folder': folder, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + 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 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 = { - }; + 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 apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.File.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.File.fromMap(res.data); } /// 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 = { - if (name != null) 'name': name, - - if (permissions != null) 'permissions': permissions, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - + 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 = { + if (name != null) 'name': name, + if (permissions != null) 'permissions': permissions, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); } /// 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 String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - if (token != null) 'token': token, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '*/*', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + Future getFileDownload( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (token != null) 'token': token, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '*/*', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// Get a file preview image. Currently, this method supports preview for image @@ -172,64 +188,76 @@ class Storage extends Service { /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - if (width != null) 'width': width, - - if (height != null) 'height': height, - - if (gravity != null) 'gravity': gravity.value, - - if (quality != null) 'quality': quality, - - if (borderWidth != null) 'borderWidth': borderWidth, - - if (borderColor != null) 'borderColor': borderColor, - - if (borderRadius != null) 'borderRadius': borderRadius, - - if (opacity != null) 'opacity': opacity, - - if (rotation != null) 'rotation': rotation, - - if (background != null) 'background': background, - - if (output != null) 'output': output.value, - - if (token != null) 'token': token, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'image/*', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + 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, + String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (gravity != null) 'gravity': gravity.value, + if (quality != null) 'quality': quality, + if (borderWidth != null) 'borderWidth': borderWidth, + if (borderColor != null) 'borderColor': borderColor, + if (borderRadius != null) 'borderRadius': borderRadius, + if (opacity != null) 'opacity': opacity, + if (rotation != null) 'rotation': rotation, + if (background != null) 'background': background, + if (output != null) 'output': output.value, + if (token != null) 'token': token, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } /// 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, String? token}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - if (token != null) 'token': token, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': '*/*', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders, responseType: ResponseType.bytes); - return res.data; - + Future getFileView( + {required String bucketId, required String fileId, String? token}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + if (token != null) 'token': token, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': '*/*', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes); + return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 93a5c190..45c239e6 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -1,325 +1,388 @@ part of '../appwrite.dart'; - /// The TablesDB service allows you to create structured tables of columns, - /// query and filter lists of rows +/// The TablesDB service allows you to create structured tables of columns, +/// query and filter lists of rows class TablesDB extends Service { /// Initializes a [TablesDB] service TablesDB(super.client); /// List transactions across all databases. - Future listTransactions({List? queries}) async { + Future listTransactions( + {List? queries}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TransactionList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TransactionList.fromMap(res.data); } /// Create a new transaction. Future createTransaction({int? ttl}) async { final String apiPath = '/tablesdb/transactions'; - final Map apiParams = { - if (ttl != null) 'ttl': ttl, - - }; + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + Future getTransaction( + {required String transactionId}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction({required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (commit != null) 'commit': commit, - - if (rollback != null) 'rollback': rollback, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Transaction.fromMap(res.data); - + Future updateTransaction( + {required String transactionId, bool? commit, bool? rollback}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - }; + final String apiPath = '/tablesdb/transactions/{transactionId}' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Create multiple operations in a single transaction. - Future createOperations({required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll('{transactionId}', transactionId); - - final Map apiParams = { - if (operations != null) 'operations': operations, - - }; + Future createOperations( + {required String transactionId, List? operations}) async { + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll('{transactionId}', transactionId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + if (operations != null) 'operations': operations, + }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Transaction.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows({required String databaseId, required String tableId, List? queries, String? transactionId, bool? total, int? ttl}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - if (total != null) 'total': total, - - if (ttl != null) 'ttl': ttl, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.RowList.fromMap(res.data); - + Future listRows( + {required String databaseId, + required String tableId, + List? queries, + String? transactionId, + bool? total, + int? ttl}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.RowList.fromMap(res.data); } /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow({required String databaseId, required String tableId, required String rowId, required Map data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId); - - final Map apiParams = { - 'rowId': rowId, - - 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future createRow( + {required String databaseId, + required String tableId, + required String rowId, + required Map data, + List? permissions, + String? transactionId}) async { + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId); + + final Map apiParams = { + 'rowId': rowId, + 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow({required String databaseId, required String tableId, required String rowId, List? queries, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future getRow( + {required String databaseId, + required String tableId, + required String rowId, + List? queries, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future upsertRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow({required String databaseId, required String tableId, required String rowId, Map? data, List? permissions, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (data != null) 'data': data, - - if (permissions != null) 'permissions': permissions, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future updateRow( + {required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Delete a row by its unique ID. - Future deleteRow({required String databaseId, required String tableId, required String rowId, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId); - - final Map apiParams = { - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - + Future deleteRow( + {required String databaseId, + required String tableId, + required String rowId, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? min, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - if (min != null) 'min': min, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future decrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? min, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + if (min != null) 'min': min, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } /// Increment a specific column of a row by a given value. - Future incrementRowColumn({required String databaseId, required String tableId, required String rowId, required String column, double? value, double? max, String? transactionId}) async { - final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replaceAll('{databaseId}', databaseId).replaceAll('{tableId}', tableId).replaceAll('{rowId}', rowId).replaceAll('{column}', column); - - final Map apiParams = { - if (value != null) 'value': value, - - if (max != null) 'max': max, - - if (transactionId != null) 'transactionId': transactionId, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Row.fromMap(res.data); - + Future incrementRowColumn( + {required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? max, + String? transactionId}) async { + final String apiPath = + '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{tableId}', tableId) + .replaceAll('{rowId}', rowId) + .replaceAll('{column}', column); + + final Map apiParams = { + if (value != null) 'value': value, + if (max != null) 'max': max, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Row.fromMap(res.data); } } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a3a0cea4..c9b7b646 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -1,98 +1,97 @@ 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 +/// 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); /// 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, bool? total}) async { + Future list( + {List? queries, String? search, bool? total}) async { final String apiPath = '/teams'; - final Map apiParams = { - if (queries != null) 'queries': queries, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; - if (search != null) 'search': search, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.TeamList.fromMap(res.data); } /// 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 { + Future create( + {required String teamId, + required String name, + List? roles}) async { final String apiPath = '/teams'; - final Map apiParams = { - 'teamId': teamId, - - 'name': name, + final Map apiParams = { + 'teamId': teamId, + 'name': name, + if (roles != null) 'roles': roles, + }; - if (roles != null) 'roles': roles, + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { + Future updateName( + {required String teamId, required String name}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - 'name': name, + final Map apiParams = { + 'name': name, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Team.fromMap(res.data); } /// Delete a team using its ID. Only team members with the owner role can @@ -100,153 +99,169 @@ class Teams extends Service { Future delete({required String teamId}) async { final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// List app installations on a team. Any team member can read installations. - Future listInstallations({required String teamId, List? queries, bool? total}) async { - final String apiPath = '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, + Future listInstallations( + {required String teamId, List? queries, bool? total}) async { + final String apiPath = + '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); - if (total != null) 'total': total, + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallationList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallationList.fromMap(res.data); } /// Install an app on a team. When authenticated as a user, only team members /// with the owner role can install apps. Requests using an API key or in admin /// mode can install apps on any team. The installation is granted the scopes /// the app currently requests. - Future createInstallation({required String teamId, required String appId, String? authorizationDetails}) async { - final String apiPath = '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'appId': appId, - - if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallation.fromMap(res.data); - + Future createInstallation( + {required String teamId, + required String appId, + String? authorizationDetails}) async { + final String apiPath = + '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'appId': appId, + if (authorizationDetails != null) + 'authorizationDetails': authorizationDetails, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); } /// Get an app installation on a team by its unique ID. Any team member can /// read installations. - Future getInstallation({required String teamId, required String installationId}) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); + Future getInstallation( + {required String teamId, required String installationId}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{installationId}', installationId); - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallation.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.AppInstallation.fromMap(res.data); } /// Update an app installation on a team. Only team members with the owner role /// can update installations. The installation's granted scopes are refreshed /// to the scopes the app currently requests; previously issued installation /// access tokens are revoked. - Future updateInstallation({required String teamId, required String installationId, String? authorizationDetails}) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); - - final Map apiParams = { - if (authorizationDetails != null) 'authorizationDetails': authorizationDetails, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.AppInstallation.fromMap(res.data); - + Future updateInstallation( + {required String teamId, + required String installationId, + String? authorizationDetails}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{installationId}', installationId); + + final Map apiParams = { + if (authorizationDetails != null) + 'authorizationDetails': authorizationDetails, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.AppInstallation.fromMap(res.data); } /// Uninstall an app from a team by its installation ID. Only team members with /// the owner role can remove installations. Previously issued installation /// access tokens are revoked. - Future deleteInstallation({required String teamId, required String installationId}) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}'.replaceAll('{teamId}', teamId).replaceAll('{installationId}', installationId); - - final Map apiParams = { - }; + Future deleteInstallation( + {required String teamId, required String installationId}) async { + final String apiPath = '/teams/{teamId}/installations/{installationId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{installationId}', installationId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships({required String teamId, List? queries, String? search, bool? total}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - if (queries != null) 'queries': queries, - - if (search != null) 'search': search, - - if (total != null) 'total': total, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - + Future listMemberships( + {required String teamId, + List? queries, + String? search, + bool? total}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (search != null) 'search': search, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); } /// Invite a new member to join your team. Provide an ID for existing users, or @@ -255,180 +270,199 @@ class Teams extends Service { /// 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. - /// + /// 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 = { - if (email != null) 'email': email, - - if (userId != null) 'userId': userId, - - if (phone != null) 'phone': phone, - - 'roles': roles, - - if (url != null) 'url': url, - - if (name != null) 'name': name, - - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + if (email != null) 'email': email, + if (userId != null) 'userId': userId, + if (phone != null) 'phone': phone, + 'roles': roles, + if (url != null) 'url': url, + if (name != null) 'name': name, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + 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 apiParams = {}; - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Membership.fromMap(res.data); } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 = { - }; + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; - return res.data; + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + return res.data; } /// 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 = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - + /// + 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 = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); } /// 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 String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + return models.Preferences.fromMap(res.data); } /// 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, - - }; + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', 'accept': 'application/json', - }; + final Map apiParams = { + 'prefs': prefs, + }; - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; - return models.Preferences.fromMap(res.data); + 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 c75dc37b..dbfe4bdf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,7 +27,8 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => + createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -112,7 +113,6 @@ abstract class Client { /// Send a ping to project as part of onboarding. Future ping(); - /// Send the API request. Future call( HttpMethod method, { diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 6794a5a2..9e6cf566 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -42,7 +42,6 @@ abstract class ClientBase implements Client { @override ClientBase setImpersonateUserPhone(value); - @override ClientBase setSelfSigned({bool status = true}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 56c7a549..47d38062 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -62,6 +62,7 @@ class ClientBrowser extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -69,6 +70,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientBrowser setBearer(value) { @@ -76,12 +78,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -89,6 +93,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientBrowser setDevKey(value) { @@ -96,6 +101,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -103,6 +109,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientBrowser setImpersonateUserId(value) { @@ -110,6 +117,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientBrowser setImpersonateUserEmail(value) { @@ -117,6 +125,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientBrowser setImpersonateUserPhone(value) { @@ -226,7 +235,8 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id) async { + Future uploadChunk( + int index, int start, int end, String? id) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); @@ -264,7 +274,9 @@ class ClientBrowser extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index d4bcece8..c675f9e1 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -88,6 +88,7 @@ class ClientIO extends ClientBase with ClientMixin { config['project'] = value; return this; } + /// Your secret JSON Web Token @override ClientIO setJWT(value) { @@ -95,6 +96,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + /// The OAuth access token to authenticate with @override ClientIO setBearer(value) { @@ -102,12 +104,14 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Authorization', 'Bearer $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) { @@ -115,6 +119,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Session', value); return this; } + /// Your secret dev API key @override ClientIO setDevKey(value) { @@ -122,6 +127,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Dev-Key', value); return this; } + /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { @@ -129,6 +135,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('Cookie', value); return this; } + /// Impersonate a user by ID @override ClientIO setImpersonateUserId(value) { @@ -136,6 +143,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Id', value); return this; } + /// Impersonate a user by email @override ClientIO setImpersonateUserEmail(value) { @@ -143,6 +151,7 @@ class ClientIO extends ClientBase with ClientMixin { addHeader('X-Appwrite-Impersonate-User-Email', value); return this; } + /// Impersonate a user by phone @override ClientIO setImpersonateUserPhone(value) { @@ -401,7 +410,9 @@ class ClientIO extends ClientBase with ClientMixin { bool isUploadComplete(Response response) { final chunksUploaded = response.data['chunksUploaded']; final chunksTotal = response.data['chunksTotal'] ?? totalChunks; - return chunksUploaded is num && chunksTotal is num && chunksUploaded >= chunksTotal; + return chunksUploaded is num && + chunksTotal is num && + chunksUploaded >= chunksTotal; } final progress = UploadProgress( @@ -425,7 +436,8 @@ class ClientIO extends ClientBase with ClientMixin { var nextChunk = 0; Future uploadNext() async { - final raf = file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; + final raf = + file.bytes == null ? await iofile!.open(mode: FileMode.read) : null; try { while (nextChunk < chunks.length) { final chunk = chunks[nextChunk++]; diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 40484946..89aad359 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -12,7 +12,6 @@ mixin ClientMixin { required Map headers, required Map params, }) { - http.BaseRequest request = http.Request(method.name(), uri); if (headers['content-type'] == 'multipart/form-data') { request = http.MultipartRequest(method.name(), uri); @@ -128,9 +127,13 @@ mixin ClientMixin { http.StreamedResponse streamedResponse, ) async { if (streamedResponse.statusCode == 204) { - return http.Response('', + return http.Response( + '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + 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, 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/browser_permission.dart b/lib/src/enums/browser_permission.dart index 765b3e0c..fb4983db 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,32 +1,30 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: 'geolocation'), + camera(value: 'camera'), + microphone(value: 'microphone'), + notifications(value: 'notifications'), + midi(value: 'midi'), + push(value: 'push'), + clipboardRead(value: 'clipboard-read'), + clipboardWrite(value: 'clipboard-write'), + paymentHandler(value: 'payment-handler'), + usb(value: 'usb'), + bluetooth(value: 'bluetooth'), + accelerometer(value: 'accelerometer'), + gyroscope(value: 'gyroscope'), + magnetometer(value: 'magnetometer'), + ambientLightSensor(value: 'ambient-light-sensor'), + backgroundSync(value: 'background-sync'), + persistentStorage(value: 'persistent-storage'), + screenWakeLock(value: 'screen-wake-lock'), + webShare(value: 'web-share'), + xrSpatialTracking(value: 'xr-spatial-tracking'); - const BrowserPermission({ - required this.value - }); + const BrowserPermission({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_theme.dart b/lib/src/enums/browser_theme.dart index e81a0f68..1e059c2c 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,14 +1,12 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: 'light'), + dark(value: 'dark'); - const BrowserTheme({ - required this.value - }); + const BrowserTheme({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 4d6bce3a..28c2a1b3 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,29 +1,27 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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'), + unionPay(value: 'unionpay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'), + rupay(value: 'rupay'); - 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 6ad112fe..44de4907 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'), + hEAD(value: 'HEAD'); - 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/execution_status.dart b/lib/src/enums/execution_status.dart index f54859c9..7ea9865e 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: 'waiting'), + processing(value: 'processing'), + completed(value: 'completed'), + failed(value: 'failed'), + scheduled(value: 'scheduled'); - const ExecutionStatus({ - required this.value - }); + const ExecutionStatus({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_trigger.dart b/lib/src/enums/execution_trigger.dart index 8a14ae60..fb05eb7d 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,15 +1,13 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: 'http'), + schedule(value: 'schedule'), + event(value: 'event'); - const ExecutionTrigger({ - required this.value - }); + const ExecutionTrigger({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 0f996ed9..55f4c5db 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,19 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + png(value: 'png'), + webp(value: 'webp'), + heic(value: 'heic'), + avif(value: 'avif'), + gif(value: 'gif'); - 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 77cad38c..6c8dbc70 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,56 +1,54 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: 'amazon'), + apple(value: 'apple'), + appwrite(value: 'appwrite'), + 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'), + figma(value: 'figma'), + fusionauth(value: 'fusionauth'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + keycloak(value: 'keycloak'), + kick(value: 'kick'), + 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'), + x(value: 'x'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'); - 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/enums/timezone.dart b/lib/src/enums/timezone.dart index 4a8de1ce..d5d8d94a 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,431 +1,429 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: 'africa/abidjan'), + africaAccra(value: 'africa/accra'), + africaAddisAbaba(value: 'africa/addis_ababa'), + africaAlgiers(value: 'africa/algiers'), + africaAsmara(value: 'africa/asmara'), + africaBamako(value: 'africa/bamako'), + africaBangui(value: 'africa/bangui'), + africaBanjul(value: 'africa/banjul'), + africaBissau(value: 'africa/bissau'), + africaBlantyre(value: 'africa/blantyre'), + africaBrazzaville(value: 'africa/brazzaville'), + africaBujumbura(value: 'africa/bujumbura'), + africaCairo(value: 'africa/cairo'), + africaCasablanca(value: 'africa/casablanca'), + africaCeuta(value: 'africa/ceuta'), + africaConakry(value: 'africa/conakry'), + africaDakar(value: 'africa/dakar'), + africaDarEsSalaam(value: 'africa/dar_es_salaam'), + africaDjibouti(value: 'africa/djibouti'), + africaDouala(value: 'africa/douala'), + africaElAaiun(value: 'africa/el_aaiun'), + africaFreetown(value: 'africa/freetown'), + africaGaborone(value: 'africa/gaborone'), + africaHarare(value: 'africa/harare'), + africaJohannesburg(value: 'africa/johannesburg'), + africaJuba(value: 'africa/juba'), + africaKampala(value: 'africa/kampala'), + africaKhartoum(value: 'africa/khartoum'), + africaKigali(value: 'africa/kigali'), + africaKinshasa(value: 'africa/kinshasa'), + africaLagos(value: 'africa/lagos'), + africaLibreville(value: 'africa/libreville'), + africaLome(value: 'africa/lome'), + africaLuanda(value: 'africa/luanda'), + africaLubumbashi(value: 'africa/lubumbashi'), + africaLusaka(value: 'africa/lusaka'), + africaMalabo(value: 'africa/malabo'), + africaMaputo(value: 'africa/maputo'), + africaMaseru(value: 'africa/maseru'), + africaMbabane(value: 'africa/mbabane'), + africaMogadishu(value: 'africa/mogadishu'), + africaMonrovia(value: 'africa/monrovia'), + africaNairobi(value: 'africa/nairobi'), + africaNdjamena(value: 'africa/ndjamena'), + africaNiamey(value: 'africa/niamey'), + africaNouakchott(value: 'africa/nouakchott'), + africaOuagadougou(value: 'africa/ouagadougou'), + africaPortoNovo(value: 'africa/porto-novo'), + africaSaoTome(value: 'africa/sao_tome'), + africaTripoli(value: 'africa/tripoli'), + africaTunis(value: 'africa/tunis'), + africaWindhoek(value: 'africa/windhoek'), + americaAdak(value: 'america/adak'), + americaAnchorage(value: 'america/anchorage'), + americaAnguilla(value: 'america/anguilla'), + americaAntigua(value: 'america/antigua'), + americaAraguaina(value: 'america/araguaina'), + americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), + americaArgentinaCatamarca(value: 'america/argentina/catamarca'), + americaArgentinaCordoba(value: 'america/argentina/cordoba'), + americaArgentinaJujuy(value: 'america/argentina/jujuy'), + americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), + americaArgentinaMendoza(value: 'america/argentina/mendoza'), + americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), + americaArgentinaSalta(value: 'america/argentina/salta'), + americaArgentinaSanJuan(value: 'america/argentina/san_juan'), + americaArgentinaSanLuis(value: 'america/argentina/san_luis'), + americaArgentinaTucuman(value: 'america/argentina/tucuman'), + americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), + americaAruba(value: 'america/aruba'), + americaAsuncion(value: 'america/asuncion'), + americaAtikokan(value: 'america/atikokan'), + americaBahia(value: 'america/bahia'), + americaBahiaBanderas(value: 'america/bahia_banderas'), + americaBarbados(value: 'america/barbados'), + americaBelem(value: 'america/belem'), + americaBelize(value: 'america/belize'), + americaBlancSablon(value: 'america/blanc-sablon'), + americaBoaVista(value: 'america/boa_vista'), + americaBogota(value: 'america/bogota'), + americaBoise(value: 'america/boise'), + americaCambridgeBay(value: 'america/cambridge_bay'), + americaCampoGrande(value: 'america/campo_grande'), + americaCancun(value: 'america/cancun'), + americaCaracas(value: 'america/caracas'), + americaCayenne(value: 'america/cayenne'), + americaCayman(value: 'america/cayman'), + americaChicago(value: 'america/chicago'), + americaChihuahua(value: 'america/chihuahua'), + americaCiudadJuarez(value: 'america/ciudad_juarez'), + americaCostaRica(value: 'america/costa_rica'), + americaCoyhaique(value: 'america/coyhaique'), + americaCreston(value: 'america/creston'), + americaCuiaba(value: 'america/cuiaba'), + americaCuracao(value: 'america/curacao'), + americaDanmarkshavn(value: 'america/danmarkshavn'), + americaDawson(value: 'america/dawson'), + americaDawsonCreek(value: 'america/dawson_creek'), + americaDenver(value: 'america/denver'), + americaDetroit(value: 'america/detroit'), + americaDominica(value: 'america/dominica'), + americaEdmonton(value: 'america/edmonton'), + americaEirunepe(value: 'america/eirunepe'), + americaElSalvador(value: 'america/el_salvador'), + americaFortNelson(value: 'america/fort_nelson'), + americaFortaleza(value: 'america/fortaleza'), + americaGlaceBay(value: 'america/glace_bay'), + americaGooseBay(value: 'america/goose_bay'), + americaGrandTurk(value: 'america/grand_turk'), + americaGrenada(value: 'america/grenada'), + americaGuadeloupe(value: 'america/guadeloupe'), + americaGuatemala(value: 'america/guatemala'), + americaGuayaquil(value: 'america/guayaquil'), + americaGuyana(value: 'america/guyana'), + americaHalifax(value: 'america/halifax'), + americaHavana(value: 'america/havana'), + americaHermosillo(value: 'america/hermosillo'), + americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), + americaIndianaKnox(value: 'america/indiana/knox'), + americaIndianaMarengo(value: 'america/indiana/marengo'), + americaIndianaPetersburg(value: 'america/indiana/petersburg'), + americaIndianaTellCity(value: 'america/indiana/tell_city'), + americaIndianaVevay(value: 'america/indiana/vevay'), + americaIndianaVincennes(value: 'america/indiana/vincennes'), + americaIndianaWinamac(value: 'america/indiana/winamac'), + americaInuvik(value: 'america/inuvik'), + americaIqaluit(value: 'america/iqaluit'), + americaJamaica(value: 'america/jamaica'), + americaJuneau(value: 'america/juneau'), + americaKentuckyLouisville(value: 'america/kentucky/louisville'), + americaKentuckyMonticello(value: 'america/kentucky/monticello'), + americaKralendijk(value: 'america/kralendijk'), + americaLaPaz(value: 'america/la_paz'), + americaLima(value: 'america/lima'), + americaLosAngeles(value: 'america/los_angeles'), + americaLowerPrinces(value: 'america/lower_princes'), + americaMaceio(value: 'america/maceio'), + americaManagua(value: 'america/managua'), + americaManaus(value: 'america/manaus'), + americaMarigot(value: 'america/marigot'), + americaMartinique(value: 'america/martinique'), + americaMatamoros(value: 'america/matamoros'), + americaMazatlan(value: 'america/mazatlan'), + americaMenominee(value: 'america/menominee'), + americaMerida(value: 'america/merida'), + americaMetlakatla(value: 'america/metlakatla'), + americaMexicoCity(value: 'america/mexico_city'), + americaMiquelon(value: 'america/miquelon'), + americaMoncton(value: 'america/moncton'), + americaMonterrey(value: 'america/monterrey'), + americaMontevideo(value: 'america/montevideo'), + americaMontserrat(value: 'america/montserrat'), + americaNassau(value: 'america/nassau'), + americaNewYork(value: 'america/new_york'), + americaNome(value: 'america/nome'), + americaNoronha(value: 'america/noronha'), + americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), + americaNorthDakotaCenter(value: 'america/north_dakota/center'), + americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), + americaNuuk(value: 'america/nuuk'), + americaOjinaga(value: 'america/ojinaga'), + americaPanama(value: 'america/panama'), + americaParamaribo(value: 'america/paramaribo'), + americaPhoenix(value: 'america/phoenix'), + americaPortAuPrince(value: 'america/port-au-prince'), + americaPortOfSpain(value: 'america/port_of_spain'), + americaPortoVelho(value: 'america/porto_velho'), + americaPuertoRico(value: 'america/puerto_rico'), + americaPuntaArenas(value: 'america/punta_arenas'), + americaRankinInlet(value: 'america/rankin_inlet'), + americaRecife(value: 'america/recife'), + americaRegina(value: 'america/regina'), + americaResolute(value: 'america/resolute'), + americaRioBranco(value: 'america/rio_branco'), + americaSantarem(value: 'america/santarem'), + americaSantiago(value: 'america/santiago'), + americaSantoDomingo(value: 'america/santo_domingo'), + americaSaoPaulo(value: 'america/sao_paulo'), + americaScoresbysund(value: 'america/scoresbysund'), + americaSitka(value: 'america/sitka'), + americaStBarthelemy(value: 'america/st_barthelemy'), + americaStJohns(value: 'america/st_johns'), + americaStKitts(value: 'america/st_kitts'), + americaStLucia(value: 'america/st_lucia'), + americaStThomas(value: 'america/st_thomas'), + americaStVincent(value: 'america/st_vincent'), + americaSwiftCurrent(value: 'america/swift_current'), + americaTegucigalpa(value: 'america/tegucigalpa'), + americaThule(value: 'america/thule'), + americaTijuana(value: 'america/tijuana'), + americaToronto(value: 'america/toronto'), + americaTortola(value: 'america/tortola'), + americaVancouver(value: 'america/vancouver'), + americaWhitehorse(value: 'america/whitehorse'), + americaWinnipeg(value: 'america/winnipeg'), + americaYakutat(value: 'america/yakutat'), + antarcticaCasey(value: 'antarctica/casey'), + antarcticaDavis(value: 'antarctica/davis'), + antarcticaDumontdurville(value: 'antarctica/dumontdurville'), + antarcticaMacquarie(value: 'antarctica/macquarie'), + antarcticaMawson(value: 'antarctica/mawson'), + antarcticaMcmurdo(value: 'antarctica/mcmurdo'), + antarcticaPalmer(value: 'antarctica/palmer'), + antarcticaRothera(value: 'antarctica/rothera'), + antarcticaSyowa(value: 'antarctica/syowa'), + antarcticaTroll(value: 'antarctica/troll'), + antarcticaVostok(value: 'antarctica/vostok'), + arcticLongyearbyen(value: 'arctic/longyearbyen'), + asiaAden(value: 'asia/aden'), + asiaAlmaty(value: 'asia/almaty'), + asiaAmman(value: 'asia/amman'), + asiaAnadyr(value: 'asia/anadyr'), + asiaAqtau(value: 'asia/aqtau'), + asiaAqtobe(value: 'asia/aqtobe'), + asiaAshgabat(value: 'asia/ashgabat'), + asiaAtyrau(value: 'asia/atyrau'), + asiaBaghdad(value: 'asia/baghdad'), + asiaBahrain(value: 'asia/bahrain'), + asiaBaku(value: 'asia/baku'), + asiaBangkok(value: 'asia/bangkok'), + asiaBarnaul(value: 'asia/barnaul'), + asiaBeirut(value: 'asia/beirut'), + asiaBishkek(value: 'asia/bishkek'), + asiaBrunei(value: 'asia/brunei'), + asiaChita(value: 'asia/chita'), + asiaColombo(value: 'asia/colombo'), + asiaDamascus(value: 'asia/damascus'), + asiaDhaka(value: 'asia/dhaka'), + asiaDili(value: 'asia/dili'), + asiaDubai(value: 'asia/dubai'), + asiaDushanbe(value: 'asia/dushanbe'), + asiaFamagusta(value: 'asia/famagusta'), + asiaGaza(value: 'asia/gaza'), + asiaHebron(value: 'asia/hebron'), + asiaHoChiMinh(value: 'asia/ho_chi_minh'), + asiaHongKong(value: 'asia/hong_kong'), + asiaHovd(value: 'asia/hovd'), + asiaIrkutsk(value: 'asia/irkutsk'), + asiaJakarta(value: 'asia/jakarta'), + asiaJayapura(value: 'asia/jayapura'), + asiaJerusalem(value: 'asia/jerusalem'), + asiaKabul(value: 'asia/kabul'), + asiaKamchatka(value: 'asia/kamchatka'), + asiaKarachi(value: 'asia/karachi'), + asiaKathmandu(value: 'asia/kathmandu'), + asiaKhandyga(value: 'asia/khandyga'), + asiaKolkata(value: 'asia/kolkata'), + asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), + asiaKualaLumpur(value: 'asia/kuala_lumpur'), + asiaKuching(value: 'asia/kuching'), + asiaKuwait(value: 'asia/kuwait'), + asiaMacau(value: 'asia/macau'), + asiaMagadan(value: 'asia/magadan'), + asiaMakassar(value: 'asia/makassar'), + asiaManila(value: 'asia/manila'), + asiaMuscat(value: 'asia/muscat'), + asiaNicosia(value: 'asia/nicosia'), + asiaNovokuznetsk(value: 'asia/novokuznetsk'), + asiaNovosibirsk(value: 'asia/novosibirsk'), + asiaOmsk(value: 'asia/omsk'), + asiaOral(value: 'asia/oral'), + asiaPhnomPenh(value: 'asia/phnom_penh'), + asiaPontianak(value: 'asia/pontianak'), + asiaPyongyang(value: 'asia/pyongyang'), + asiaQatar(value: 'asia/qatar'), + asiaQostanay(value: 'asia/qostanay'), + asiaQyzylorda(value: 'asia/qyzylorda'), + asiaRiyadh(value: 'asia/riyadh'), + asiaSakhalin(value: 'asia/sakhalin'), + asiaSamarkand(value: 'asia/samarkand'), + asiaSeoul(value: 'asia/seoul'), + asiaShanghai(value: 'asia/shanghai'), + asiaSingapore(value: 'asia/singapore'), + asiaSrednekolymsk(value: 'asia/srednekolymsk'), + asiaTaipei(value: 'asia/taipei'), + asiaTashkent(value: 'asia/tashkent'), + asiaTbilisi(value: 'asia/tbilisi'), + asiaTehran(value: 'asia/tehran'), + asiaThimphu(value: 'asia/thimphu'), + asiaTokyo(value: 'asia/tokyo'), + asiaTomsk(value: 'asia/tomsk'), + asiaUlaanbaatar(value: 'asia/ulaanbaatar'), + asiaUrumqi(value: 'asia/urumqi'), + asiaUstNera(value: 'asia/ust-nera'), + asiaVientiane(value: 'asia/vientiane'), + asiaVladivostok(value: 'asia/vladivostok'), + asiaYakutsk(value: 'asia/yakutsk'), + asiaYangon(value: 'asia/yangon'), + asiaYekaterinburg(value: 'asia/yekaterinburg'), + asiaYerevan(value: 'asia/yerevan'), + atlanticAzores(value: 'atlantic/azores'), + atlanticBermuda(value: 'atlantic/bermuda'), + atlanticCanary(value: 'atlantic/canary'), + atlanticCapeVerde(value: 'atlantic/cape_verde'), + atlanticFaroe(value: 'atlantic/faroe'), + atlanticMadeira(value: 'atlantic/madeira'), + atlanticReykjavik(value: 'atlantic/reykjavik'), + atlanticSouthGeorgia(value: 'atlantic/south_georgia'), + atlanticStHelena(value: 'atlantic/st_helena'), + atlanticStanley(value: 'atlantic/stanley'), + australiaAdelaide(value: 'australia/adelaide'), + australiaBrisbane(value: 'australia/brisbane'), + australiaBrokenHill(value: 'australia/broken_hill'), + australiaDarwin(value: 'australia/darwin'), + australiaEucla(value: 'australia/eucla'), + australiaHobart(value: 'australia/hobart'), + australiaLindeman(value: 'australia/lindeman'), + australiaLordHowe(value: 'australia/lord_howe'), + australiaMelbourne(value: 'australia/melbourne'), + australiaPerth(value: 'australia/perth'), + australiaSydney(value: 'australia/sydney'), + europeAmsterdam(value: 'europe/amsterdam'), + europeAndorra(value: 'europe/andorra'), + europeAstrakhan(value: 'europe/astrakhan'), + europeAthens(value: 'europe/athens'), + europeBelgrade(value: 'europe/belgrade'), + europeBerlin(value: 'europe/berlin'), + europeBratislava(value: 'europe/bratislava'), + europeBrussels(value: 'europe/brussels'), + europeBucharest(value: 'europe/bucharest'), + europeBudapest(value: 'europe/budapest'), + europeBusingen(value: 'europe/busingen'), + europeChisinau(value: 'europe/chisinau'), + europeCopenhagen(value: 'europe/copenhagen'), + europeDublin(value: 'europe/dublin'), + europeGibraltar(value: 'europe/gibraltar'), + europeGuernsey(value: 'europe/guernsey'), + europeHelsinki(value: 'europe/helsinki'), + europeIsleOfMan(value: 'europe/isle_of_man'), + europeIstanbul(value: 'europe/istanbul'), + europeJersey(value: 'europe/jersey'), + europeKaliningrad(value: 'europe/kaliningrad'), + europeKirov(value: 'europe/kirov'), + europeKyiv(value: 'europe/kyiv'), + europeLisbon(value: 'europe/lisbon'), + europeLjubljana(value: 'europe/ljubljana'), + europeLondon(value: 'europe/london'), + europeLuxembourg(value: 'europe/luxembourg'), + europeMadrid(value: 'europe/madrid'), + europeMalta(value: 'europe/malta'), + europeMariehamn(value: 'europe/mariehamn'), + europeMinsk(value: 'europe/minsk'), + europeMonaco(value: 'europe/monaco'), + europeMoscow(value: 'europe/moscow'), + europeOslo(value: 'europe/oslo'), + europeParis(value: 'europe/paris'), + europePodgorica(value: 'europe/podgorica'), + europePrague(value: 'europe/prague'), + europeRiga(value: 'europe/riga'), + europeRome(value: 'europe/rome'), + europeSamara(value: 'europe/samara'), + europeSanMarino(value: 'europe/san_marino'), + europeSarajevo(value: 'europe/sarajevo'), + europeSaratov(value: 'europe/saratov'), + europeSimferopol(value: 'europe/simferopol'), + europeSkopje(value: 'europe/skopje'), + europeSofia(value: 'europe/sofia'), + europeStockholm(value: 'europe/stockholm'), + europeTallinn(value: 'europe/tallinn'), + europeTirane(value: 'europe/tirane'), + europeUlyanovsk(value: 'europe/ulyanovsk'), + europeVaduz(value: 'europe/vaduz'), + europeVatican(value: 'europe/vatican'), + europeVienna(value: 'europe/vienna'), + europeVilnius(value: 'europe/vilnius'), + europeVolgograd(value: 'europe/volgograd'), + europeWarsaw(value: 'europe/warsaw'), + europeZagreb(value: 'europe/zagreb'), + europeZurich(value: 'europe/zurich'), + indianAntananarivo(value: 'indian/antananarivo'), + indianChagos(value: 'indian/chagos'), + indianChristmas(value: 'indian/christmas'), + indianCocos(value: 'indian/cocos'), + indianComoro(value: 'indian/comoro'), + indianKerguelen(value: 'indian/kerguelen'), + indianMahe(value: 'indian/mahe'), + indianMaldives(value: 'indian/maldives'), + indianMauritius(value: 'indian/mauritius'), + indianMayotte(value: 'indian/mayotte'), + indianReunion(value: 'indian/reunion'), + pacificApia(value: 'pacific/apia'), + pacificAuckland(value: 'pacific/auckland'), + pacificBougainville(value: 'pacific/bougainville'), + pacificChatham(value: 'pacific/chatham'), + pacificChuuk(value: 'pacific/chuuk'), + pacificEaster(value: 'pacific/easter'), + pacificEfate(value: 'pacific/efate'), + pacificFakaofo(value: 'pacific/fakaofo'), + pacificFiji(value: 'pacific/fiji'), + pacificFunafuti(value: 'pacific/funafuti'), + pacificGalapagos(value: 'pacific/galapagos'), + pacificGambier(value: 'pacific/gambier'), + pacificGuadalcanal(value: 'pacific/guadalcanal'), + pacificGuam(value: 'pacific/guam'), + pacificHonolulu(value: 'pacific/honolulu'), + pacificKanton(value: 'pacific/kanton'), + pacificKiritimati(value: 'pacific/kiritimati'), + pacificKosrae(value: 'pacific/kosrae'), + pacificKwajalein(value: 'pacific/kwajalein'), + pacificMajuro(value: 'pacific/majuro'), + pacificMarquesas(value: 'pacific/marquesas'), + pacificMidway(value: 'pacific/midway'), + pacificNauru(value: 'pacific/nauru'), + pacificNiue(value: 'pacific/niue'), + pacificNorfolk(value: 'pacific/norfolk'), + pacificNoumea(value: 'pacific/noumea'), + pacificPagoPago(value: 'pacific/pago_pago'), + pacificPalau(value: 'pacific/palau'), + pacificPitcairn(value: 'pacific/pitcairn'), + pacificPohnpei(value: 'pacific/pohnpei'), + pacificPortMoresby(value: 'pacific/port_moresby'), + pacificRarotonga(value: 'pacific/rarotonga'), + pacificSaipan(value: 'pacific/saipan'), + pacificTahiti(value: 'pacific/tahiti'), + pacificTarawa(value: 'pacific/tarawa'), + pacificTongatapu(value: 'pacific/tongatapu'), + pacificWake(value: 'pacific/wake'), + pacificWallis(value: 'pacific/wallis'), + utc(value: 'utc'); - const Timezone({ - required this.value - }); + const Timezone({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 683e6387..c6974573 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 f80fa854..344a8770 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,41 +2,41 @@ 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; + /// Memory used to compute hash. + final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; + /// Amount of time consumed to compute hash + final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Number of threads used to compute hash. + final int threads; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.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'], - ); - } + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - @override - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + @override + 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 c51da4bb..9909265e 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 43523ab1..746fbd52 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 8562c4e3..cab45e49 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 8e844839..a1648843 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,47 +2,47 @@ 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'], - ); - } - - @override - 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'], + ); + } + + @override + 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 5202db05..33ef4a6f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,41 +2,41 @@ 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; + /// Salt used to compute hash. + final String salt; - /// Separator used to compute hash. - final String saltSeparator; + /// Separator used to compute hash. + final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Key used to compute hash. + final String signerKey; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.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(), - ); - } + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - @override - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + @override + 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 3d08af9f..4984df75 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "type": type, - }; - } + @override + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/app_installation.dart b/lib/src/models/app_installation.dart index ec5d9b2f..3ed121ec 100644 --- a/lib/src/models/app_installation.dart +++ b/lib/src/models/app_installation.dart @@ -2,77 +2,77 @@ part of '../../models.dart'; /// AppInstallation class AppInstallation implements Model { - /// Installation ID. - final String $id; + /// Installation ID. + final String $id; - /// Installation creation time in ISO 8601 format. - final String $createdAt; + /// Installation creation time in ISO 8601 format. + final String $createdAt; - /// Installation update time in ISO 8601 format. - final String $updatedAt; + /// Installation update time in ISO 8601 format. + final String $updatedAt; - /// ID of the installed application. - final String appId; + /// ID of the installed application. + final String appId; - /// ID of the team the application is installed on. - final String teamId; + /// ID of the team the application is installed on. + final String teamId; - /// Scopes granted to the application. Snapshot of the application's installation scopes taken when the installation was created or last updated. - final List scopes; + /// Scopes granted to the application. Snapshot of the application's installation scopes taken when the installation was created or last updated. + final List scopes; - /// Authorization details granted to the application. Rich authorization request (RFC 9396) style entries; the Appwrite Console stores authorized project IDs here. - final Map authorizationDetails; + /// Authorization details granted to the application. Rich authorization request (RFC 9396) style entries; the Appwrite Console stores authorized project IDs here. + final Map authorizationDetails; - /// ID of the user who created the installation. - final String createdById; + /// ID of the user who created the installation. + final String createdById; - /// Name of the user who created the installation. - final String createdByName; + /// Name of the user who created the installation. + final String createdByName; - /// Time an access token was last issued for the installation in ISO 8601 format. Null if never used. - final String? lastAccessedAt; + /// Time an access token was last issued for the installation in ISO 8601 format. Null if never used. + final String? lastAccessedAt; - AppInstallation({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.appId, - required this.teamId, - required this.scopes, - required this.authorizationDetails, - required this.createdById, - required this.createdByName, - this.lastAccessedAt, - }); + AppInstallation({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.teamId, + required this.scopes, + required this.authorizationDetails, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); - factory AppInstallation.fromMap(Map map) { - return AppInstallation( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - appId: map['appId'].toString(), - teamId: map['teamId'].toString(), - scopes: List.from(map['scopes'] ?? []), - authorizationDetails: map['authorizationDetails'], - createdById: map['createdById'].toString(), - createdByName: map['createdByName'].toString(), - lastAccessedAt: map['lastAccessedAt']?.toString(), - ); - } + factory AppInstallation.fromMap(Map map) { + return AppInstallation( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + teamId: map['teamId'].toString(), + scopes: List.from(map['scopes'] ?? []), + authorizationDetails: map['authorizationDetails'], + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "appId": appId, - "teamId": teamId, - "scopes": scopes, - "authorizationDetails": authorizationDetails, - "createdById": createdById, - "createdByName": createdByName, - "lastAccessedAt": lastAccessedAt, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "teamId": teamId, + "scopes": scopes, + "authorizationDetails": authorizationDetails, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } } diff --git a/lib/src/models/app_installation_list.dart b/lib/src/models/app_installation_list.dart index f9484c53..c55f831f 100644 --- a/lib/src/models/app_installation_list.dart +++ b/lib/src/models/app_installation_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// App installations list class AppInstallationList implements Model { - /// Total number of installations that matched your query. - final int total; + /// Total number of installations that matched your query. + final int total; - /// List of installations. - final List installations; + /// List of installations. + final List installations; - AppInstallationList({ - required this.total, - required this.installations, - }); + AppInstallationList({ + required this.total, + required this.installations, + }); - factory AppInstallationList.fromMap(Map map) { - return AppInstallationList( - total: map['total'], - installations: List.from(map['installations'].map((p) => AppInstallation.fromMap(p))), - ); - } + factory AppInstallationList.fromMap(Map map) { + return AppInstallationList( + total: map['total'], + installations: List.from( + map['installations'].map((p) => AppInstallation.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "installations": installations.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "installations": installations.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 930900bf..ec3c41be 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index 753bcacc..df28f04b 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents that matched your query. - final int total; + /// Total number of continents 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 c4838ba3..3bcbb76d 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - }; - } + @override + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index f363a54b..79cb1256 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries that matched your query. - final int total; + /// Total number of countries 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b6bb455f..f2b18093 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,59 +2,59 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + 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 eb2bad19..6c39ae2e 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies that matched your query. - final int total; + /// Total number of currencies 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + @override + 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 0d1fdeb0..be08d599 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; + /// Document ID. + final String $id; - /// Document sequence ID. - final String $sequence; + /// Document sequence ID. + final String $sequence; - /// Collection ID. - final String $collectionId; + /// Collection ID. + final String $collectionId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; + /// Document creation date in ISO 8601 format. + final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Document({ - required this.$id, - required this.$sequence, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Document({ + required this.$id, + required this.$sequence, + 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(), - $sequence: map['\$sequence'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(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 0e30844a..76a07309 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,33 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents that matched your query. - final int total; + /// Total number of 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3e767ca3..3629e1d6 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,125 +2,129 @@ 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 update date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// Function's deployment ID used to create the execution. - final String deploymentId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final enums.ExecutionTrigger trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. - final enums.ExecutionStatus status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP request 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; - - /// Resource(function/site) 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.deploymentId, - 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: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), - deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values.firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values.firstWhere((e) => e.value == map['status']), - 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(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "deploymentId": deploymentId, - "trigger": trigger.value, - "status": status.value, - "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 update date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// Function's deployment ID used to create the execution. + final String deploymentId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final enums.ExecutionTrigger trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + final enums.ExecutionStatus status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP request 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; + + /// Resource(function/site) 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.deploymentId, + 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: List.from(map['\$permissions'] ?? []), + functionId: map['functionId'].toString(), + deploymentId: map['deploymentId'].toString(), + trigger: enums.ExecutionTrigger.values + .firstWhere((e) => e.value == map['trigger']), + status: enums.ExecutionStatus.values + .firstWhere((e) => e.value == map['status']), + 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "deploymentId": deploymentId, + "trigger": trigger.value, + "status": status.value, + "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 45b60682..63c2ad7e 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions that matched your query. - final int total; + /// Total number of executions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 f70fdcd4..91c5e945 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,113 +2,113 @@ 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; - - /// Virtual folder containing the file, with a trailing slash. Empty for the bucket root. - final String folder; - - /// Full virtual path of the file: the folder followed by the file name. - final String key; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// File actual stored size in bytes after compression and/or encryption. - final int sizeActual; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - /// Whether file contents are encrypted at rest. - final bool encryption; - - /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). - final String compression; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.folder, - required this.key, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.sizeActual, - required this.chunksTotal, - required this.chunksUploaded, - required this.encryption, - required this.compression, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - name: map['name'].toString(), - folder: map['folder'].toString(), - key: map['key'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - sizeActual: map['sizeActual'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - encryption: map['encryption'], - compression: map['compression'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "folder": folder, - "key": key, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "sizeActual": sizeActual, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - "encryption": encryption, - "compression": compression, - }; - } + /// 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; + + /// Virtual folder containing the file, with a trailing slash. Empty for the bucket root. + final String folder; + + /// Full virtual path of the file: the folder followed by the file name. + final String key; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// File actual stored size in bytes after compression and/or encryption. + final int sizeActual; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + /// Whether file contents are encrypted at rest. + final bool encryption; + + /// Compression algorithm used for the file. Will be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd). + final String compression; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.folder, + required this.key, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.sizeActual, + required this.chunksTotal, + required this.chunksUploaded, + required this.encryption, + required this.compression, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + name: map['name'].toString(), + folder: map['folder'].toString(), + key: map['key'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + sizeActual: map['sizeActual'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + encryption: map['encryption'], + compression: map['compression'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "folder": folder, + "key": key, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "sizeActual": sizeActual, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + "encryption": encryption, + "compression": compression, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 84c54b2e..1157554a 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files that matched your query. - final int total; + /// Total number of files 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + @override + 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 bbccf88a..fa054420 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "name": name, - "value": value, - }; - } + @override + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 7e90020c..cc659043 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,77 +2,77 @@ 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 creation date in ISO 8601 format. + final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Identity Provider. - final String provider; + /// Identity Provider. + final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; + /// ID of the User in the Identity Provider. + final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; + /// Email of the User in the Identity Provider. + final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; + /// Identity Provider Access Token. + final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + @override + 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 d9cc09a2..a5d39ea0 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities that matched your query. - final int total; + /// Total number of identities 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + @override + 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 2000acb6..cda66c70 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,23 +2,23 @@ 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(), + ); + } - @override - Map toMap() { - return { - "jwt": jwt, - }; - } + @override + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 1422d065..87dc3606 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,35 +2,35 @@ 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 two-character ISO 639-1 codes. + final String code; - /// Language native name. - final String nativeName; + /// Language native name. + final String nativeName; - Language({ - required this.name, - required this.code, - required this.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(), - ); - } + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - @override - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + @override + 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 5d78a367..6198d61e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages that matched your query. - final int total; + /// Total number of languages 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + @override + 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 926e352d..c29b9e25 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,125 +2,126 @@ 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; - - /// City - final String? city; - - /// Name of timezone - final String? timeZone; - - /// Postal code - final String? postalCode; - - /// Latitude - final double? latitude; - - /// Longitude - final double? longitude; - - /// Autonomous System Number (ASN) of the IP - final String? autonomousSystemNumber; - - /// Organization that owns the ASN - final String? autonomousSystemOrganization; - - /// Internet service provider of the IP - final String? isp; - - /// Connection type of the IP (e.g. cable, cellular, corporate) - final String? connectionType; - - /// User type classification of the IP (e.g. residential, business, hosting) - final String? connectionUsageType; - - /// Registered organization of the IP - final String? connectionOrganization; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - this.city, - this.timeZone, - this.postalCode, - this.latitude, - this.longitude, - this.autonomousSystemNumber, - this.autonomousSystemOrganization, - this.isp, - this.connectionType, - this.connectionUsageType, - this.connectionOrganization, - }); - - 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(), - city: map['city']?.toString(), - timeZone: map['timeZone']?.toString(), - postalCode: map['postalCode']?.toString(), - latitude: map['latitude']?.toDouble(), - longitude: map['longitude']?.toDouble(), - autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), - autonomousSystemOrganization: map['autonomousSystemOrganization']?.toString(), - isp: map['isp']?.toString(), - connectionType: map['connectionType']?.toString(), - connectionUsageType: map['connectionUsageType']?.toString(), - connectionOrganization: map['connectionOrganization']?.toString(), - ); - } - - @override - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - "city": city, - "timeZone": timeZone, - "postalCode": postalCode, - "latitude": latitude, - "longitude": longitude, - "autonomousSystemNumber": autonomousSystemNumber, - "autonomousSystemOrganization": autonomousSystemOrganization, - "isp": isp, - "connectionType": connectionType, - "connectionUsageType": connectionUsageType, - "connectionOrganization": connectionOrganization, - }; - } + /// 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; + + /// City + final String? city; + + /// Name of timezone + final String? timeZone; + + /// Postal code + final String? postalCode; + + /// Latitude + final double? latitude; + + /// Longitude + final double? longitude; + + /// Autonomous System Number (ASN) of the IP + final String? autonomousSystemNumber; + + /// Organization that owns the ASN + final String? autonomousSystemOrganization; + + /// Internet service provider of the IP + final String? isp; + + /// Connection type of the IP (e.g. cable, cellular, corporate) + final String? connectionType; + + /// User type classification of the IP (e.g. residential, business, hosting) + final String? connectionUsageType; + + /// Registered organization of the IP + final String? connectionOrganization; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + this.city, + this.timeZone, + this.postalCode, + this.latitude, + this.longitude, + this.autonomousSystemNumber, + this.autonomousSystemOrganization, + this.isp, + this.connectionType, + this.connectionUsageType, + this.connectionOrganization, + }); + + 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(), + city: map['city']?.toString(), + timeZone: map['timeZone']?.toString(), + postalCode: map['postalCode']?.toString(), + latitude: map['latitude']?.toDouble(), + longitude: map['longitude']?.toDouble(), + autonomousSystemNumber: map['autonomousSystemNumber']?.toString(), + autonomousSystemOrganization: + map['autonomousSystemOrganization']?.toString(), + isp: map['isp']?.toString(), + connectionType: map['connectionType']?.toString(), + connectionUsageType: map['connectionUsageType']?.toString(), + connectionOrganization: map['connectionOrganization']?.toString(), + ); + } + + @override + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + "city": city, + "timeZone": timeZone, + "postalCode": postalCode, + "latitude": latitude, + "longitude": longitude, + "autonomousSystemNumber": autonomousSystemNumber, + "autonomousSystemOrganization": autonomousSystemOrganization, + "isp": isp, + "connectionType": connectionType, + "connectionUsageType": connectionUsageType, + "connectionOrganization": connectionOrganization, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 49ef3b0b..21405aff 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "code": code, - "name": name, - }; - } + @override + 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 a3a26b61..202355a4 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes that matched your query. - final int total; + /// Total number of localeCodes 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + @override + 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 ac4eacf3..d754130d 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,149 +2,149 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. + final String userId; + + /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userEmail; + + /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. + final String userType; + + /// 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.userType, + 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(), + userType: map['userType'].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(), + ); + } + + @override + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "userType": userType, + "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 ebf593c2..3494b111 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs that matched your query. - final int total; + /// Total number of logs 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + @override + 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 4baffb71..4d8a2f9b 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,107 +2,107 @@ 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. Hide this attribute by toggling membership privacy in the Console. - final String userName; - - /// User email address. Hide this attribute by toggling membership privacy in the Console. - final String userEmail; - - /// User phone number. Hide this attribute by toggling membership privacy in the Console. - final String userPhone; - - /// 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. Hide this attribute by toggling membership privacy in the Console. - final bool mfa; - - /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. - final String userAccessedAt; - - /// 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.userPhone, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.userAccessedAt, - 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(), - userPhone: map['userPhone'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - userAccessedAt: map['userAccessedAt'].toString(), - roles: List.from(map['roles'] ?? []), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "userPhone": userPhone, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "userAccessedAt": userAccessedAt, - "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. Hide this attribute by toggling membership privacy in the Console. + final String userName; + + /// User email address. Hide this attribute by toggling membership privacy in the Console. + final String userEmail; + + /// User phone number. Hide this attribute by toggling membership privacy in the Console. + final String userPhone; + + /// 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. Hide this attribute by toggling membership privacy in the Console. + final bool mfa; + + /// Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console. + final String userAccessedAt; + + /// 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.userPhone, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.userAccessedAt, + 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(), + userPhone: map['userPhone'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + userAccessedAt: map['userAccessedAt'].toString(), + roles: List.from(map['roles'] ?? []), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "userPhone": userPhone, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "userAccessedAt": userAccessedAt, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index a0641a28..cc664c9f 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships that matched your query. - final int total; + /// Total number of memberships 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + @override + 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 3d2e2335..fa385541 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,41 +2,41 @@ 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; + /// Token creation date in ISO 8601 format. + final String $createdAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token expiration date in ISO 8601 format. + final String expire; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.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(), - ); - } + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + @override + 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 a7e5fefc..2777de7f 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,41 +2,41 @@ 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 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 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 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, - }); + 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'], - ); - } + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - @override - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + @override + 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 33036476..864a5db8 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,23 +2,23 @@ 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: List.from(map['recoveryCodes'] ?? []), - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: List.from(map['recoveryCodes'] ?? []), + ); + } - @override - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + @override + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 05cab363..fe5327fc 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,29 +2,29 @@ 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(), + ); + } - @override - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + @override + 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/oauth2_consent.dart b/lib/src/models/oauth2_consent.dart index d927fe3b..0f71fac2 100644 --- a/lib/src/models/oauth2_consent.dart +++ b/lib/src/models/oauth2_consent.dart @@ -2,77 +2,77 @@ part of '../../models.dart'; /// OAuth2 Consent class Oauth2Consent implements Model { - /// Consent ID. - final String $id; + /// Consent ID. + final String $id; - /// Consent creation time in ISO 8601 format. - final String $createdAt; + /// Consent creation time in ISO 8601 format. + final String $createdAt; - /// Consent update date in ISO 8601 format. - final String $updatedAt; + /// Consent update date in ISO 8601 format. + final String $updatedAt; - /// ID of the user the consent belongs to. - final String userId; + /// ID of the user the consent belongs to. + final String userId; - /// ID of the registered app the consent was given to. Empty for URL-form (CIMD) clients. - final String appId; + /// ID of the registered app the consent was given to. Empty for URL-form (CIMD) clients. + final String appId; - /// Client ID metadata document URL of the client the consent was given to. Empty for registered apps. - final String cimdUrl; + /// Client ID metadata document URL of the client the consent was given to. Empty for registered apps. + final String cimdUrl; - /// OAuth2 scopes the user consented to. - final List scopes; + /// OAuth2 scopes the user consented to. + final List scopes; - /// RFC 8707 resource indicators the user consented to. - final List resources; + /// RFC 8707 resource indicators the user consented to. + final List resources; - /// Authorization details the user consented to, as a JSON string. Each entry has a `type` plus project-defined fields. - final String authorizationDetails; + /// Authorization details the user consented to, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; - /// Consent expiration time in ISO 8601 format. Empty when the consent has no token-bound expiry yet. - final String expire; + /// Consent expiration time in ISO 8601 format. Empty when the consent has no token-bound expiry yet. + final String expire; - Oauth2Consent({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.appId, - required this.cimdUrl, - required this.scopes, - required this.resources, - required this.authorizationDetails, - required this.expire, - }); + Oauth2Consent({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.appId, + required this.cimdUrl, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.expire, + }); - factory Oauth2Consent.fromMap(Map map) { - return Oauth2Consent( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - appId: map['appId'].toString(), - cimdUrl: map['cimdUrl'].toString(), - scopes: List.from(map['scopes'] ?? []), - resources: List.from(map['resources'] ?? []), - authorizationDetails: map['authorizationDetails'].toString(), - expire: map['expire'].toString(), - ); - } + factory Oauth2Consent.fromMap(Map map) { + return Oauth2Consent( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + cimdUrl: map['cimdUrl'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "appId": appId, - "cimdUrl": cimdUrl, - "scopes": scopes, - "resources": resources, - "authorizationDetails": authorizationDetails, - "expire": expire, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "appId": appId, + "cimdUrl": cimdUrl, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "expire": expire, + }; + } } diff --git a/lib/src/models/oauth2_consent_list.dart b/lib/src/models/oauth2_consent_list.dart index b606f8c1..a5f355e1 100644 --- a/lib/src/models/oauth2_consent_list.dart +++ b/lib/src/models/oauth2_consent_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// OAuth2 consents list class Oauth2ConsentList implements Model { - /// Total number of consents that matched your query. - final int total; + /// Total number of consents that matched your query. + final int total; - /// List of consents. - final List consents; + /// List of consents. + final List consents; - Oauth2ConsentList({ - required this.total, - required this.consents, - }); + Oauth2ConsentList({ + required this.total, + required this.consents, + }); - factory Oauth2ConsentList.fromMap(Map map) { - return Oauth2ConsentList( - total: map['total'], - consents: List.from(map['consents'].map((p) => Oauth2Consent.fromMap(p))), - ); - } + factory Oauth2ConsentList.fromMap(Map map) { + return Oauth2ConsentList( + total: map['total'], + consents: List.from( + map['consents'].map((p) => Oauth2Consent.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "consents": consents.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "consents": consents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/oauth2_consent_token.dart b/lib/src/models/oauth2_consent_token.dart index 356d7e93..adbee89f 100644 --- a/lib/src/models/oauth2_consent_token.dart +++ b/lib/src/models/oauth2_consent_token.dart @@ -2,83 +2,83 @@ part of '../../models.dart'; /// OAuth2 Consent Token class Oauth2ConsentToken implements Model { - /// Token family ID. - final String $id; + /// Token family ID. + final String $id; - /// Token creation time in ISO 8601 format. - final String $createdAt; + /// Token creation time in ISO 8601 format. + final String $createdAt; - /// Token update date in ISO 8601 format. Refreshing the token family updates this. - final String $updatedAt; + /// Token update date in ISO 8601 format. Refreshing the token family updates this. + final String $updatedAt; - /// ID of the consent the token family was issued under. - final String consentId; + /// ID of the consent the token family was issued under. + final String consentId; - /// ID of the user the token family belongs to. - final String userId; + /// ID of the user the token family belongs to. + final String userId; - /// ID of the registered app the token family was issued to. Empty for URL-form (CIMD) clients. - final String appId; + /// ID of the registered app the token family was issued to. Empty for URL-form (CIMD) clients. + final String appId; - /// Client ID metadata document URL of the client the token family was issued to. Empty for registered apps. - final String cimdUrl; + /// Client ID metadata document URL of the client the token family was issued to. Empty for registered apps. + final String cimdUrl; - /// OAuth2 scopes granted on the token family. - final List scopes; + /// OAuth2 scopes granted on the token family. + final List scopes; - /// RFC 8707 resource indicators granted on the token family. - final List resources; + /// RFC 8707 resource indicators granted on the token family. + final List resources; - /// Authorization details granted on the token family, as a JSON string. Each entry has a `type` plus project-defined fields. - final String authorizationDetails; + /// Authorization details granted on the token family, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; - /// Expiration time of the current access token of this family in ISO 8601 format. - final String expire; + /// Expiration time of the current access token of this family in ISO 8601 format. + final String expire; - Oauth2ConsentToken({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.consentId, - required this.userId, - required this.appId, - required this.cimdUrl, - required this.scopes, - required this.resources, - required this.authorizationDetails, - required this.expire, - }); + Oauth2ConsentToken({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.consentId, + required this.userId, + required this.appId, + required this.cimdUrl, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.expire, + }); - factory Oauth2ConsentToken.fromMap(Map map) { - return Oauth2ConsentToken( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - consentId: map['consentId'].toString(), - userId: map['userId'].toString(), - appId: map['appId'].toString(), - cimdUrl: map['cimdUrl'].toString(), - scopes: List.from(map['scopes'] ?? []), - resources: List.from(map['resources'] ?? []), - authorizationDetails: map['authorizationDetails'].toString(), - expire: map['expire'].toString(), - ); - } + factory Oauth2ConsentToken.fromMap(Map map) { + return Oauth2ConsentToken( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + consentId: map['consentId'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + cimdUrl: map['cimdUrl'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + expire: map['expire'].toString(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "consentId": consentId, - "userId": userId, - "appId": appId, - "cimdUrl": cimdUrl, - "scopes": scopes, - "resources": resources, - "authorizationDetails": authorizationDetails, - "expire": expire, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "consentId": consentId, + "userId": userId, + "appId": appId, + "cimdUrl": cimdUrl, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "expire": expire, + }; + } } diff --git a/lib/src/models/oauth2_consent_token_list.dart b/lib/src/models/oauth2_consent_token_list.dart index 82e9bf71..cc5cdc16 100644 --- a/lib/src/models/oauth2_consent_token_list.dart +++ b/lib/src/models/oauth2_consent_token_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// OAuth2 consent tokens list class Oauth2ConsentTokenList implements Model { - /// Total number of tokens that matched your query. - final int total; + /// Total number of tokens that matched your query. + final int total; - /// List of tokens. - final List tokens; + /// List of tokens. + final List tokens; - Oauth2ConsentTokenList({ - required this.total, - required this.tokens, - }); + Oauth2ConsentTokenList({ + required this.total, + required this.tokens, + }); - factory Oauth2ConsentTokenList.fromMap(Map map) { - return Oauth2ConsentTokenList( - total: map['total'], - tokens: List.from(map['tokens'].map((p) => Oauth2ConsentToken.fromMap(p))), - ); - } + factory Oauth2ConsentTokenList.fromMap(Map map) { + return Oauth2ConsentTokenList( + total: map['total'], + tokens: List.from( + map['tokens'].map((p) => Oauth2ConsentToken.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "tokens": tokens.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "tokens": tokens.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 7ac578e2..60e2abd9 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,35 +2,35 @@ 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 two-character ISO 3166-1 alpha code. + final String countryCode; - /// Country name. - final String countryName; + /// Country name. + final String countryName; - Phone({ - required this.code, - required this.countryCode, - required this.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(), - ); - } + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - @override - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + @override + 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 9791d590..1a197fc7 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones that matched your query. - final int total; + /// Total number of phones 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b107afe5..3ca04118 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,24 +2,24 @@ 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["data"] ?? map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "data": data, - }; - } + @override + 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/presence.dart b/lib/src/models/presence.dart index 133fe66d..d31911de 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Presence class Presence implements Model { - /// Presence ID. - final String $id; + /// Presence ID. + final String $id; - /// Presence creation date in ISO 8601 format. - final String $createdAt; + /// Presence creation date in ISO 8601 format. + final String $createdAt; - /// Presence update date in ISO 8601 format. - final String $updatedAt; + /// Presence update date in ISO 8601 format. + final String $updatedAt; - /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Presence permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Presence status. - final String? status; + /// Presence status. + final String? status; - /// Presence source. - final String source; + /// Presence source. + final String source; - /// Presence expiry date in ISO 8601 format. - final String? expiresAt; + /// Presence expiry date in ISO 8601 format. + final String? expiresAt; - /// Presence metadata. - final Map? metadata; + /// Presence metadata. + final Map? metadata; - Presence({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.userId, - this.status, - required this.source, - this.expiresAt, - this.metadata, - }); + Presence({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.userId, + this.status, + required this.source, + this.expiresAt, + this.metadata, + }); - factory Presence.fromMap(Map map) { - return Presence( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - userId: map['userId'].toString(), - status: map['status']?.toString(), - source: map['source'].toString(), - expiresAt: map['expiresAt']?.toString(), - metadata: map['metadata'], - ); - } + factory Presence.fromMap(Map map) { + return Presence( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + userId: map['userId'].toString(), + status: map['status']?.toString(), + source: map['source'].toString(), + expiresAt: map['expiresAt']?.toString(), + metadata: map['metadata'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "userId": userId, - "status": status, - "source": source, - "expiresAt": expiresAt, - "metadata": metadata, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "userId": userId, + "status": status, + "source": source, + "expiresAt": expiresAt, + "metadata": metadata, + }; + } } diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index aebbe880..3d010b1c 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Presences List class PresenceList implements Model { - /// Total number of presences that matched your query. - final int total; + /// Total number of presences that matched your query. + final int total; - /// List of presences. - final List presences; + /// List of presences. + final List presences; - PresenceList({ - required this.total, - required this.presences, - }); + PresenceList({ + required this.total, + required this.presences, + }); - factory PresenceList.fromMap(Map map) { - return PresenceList( - total: map['total'], - presences: List.from(map['presences'].map((p) => Presence.fromMap(p))), - ); - } + factory PresenceList.fromMap(Map map) { + return PresenceList( + total: map['total'], + presences: + List.from(map['presences'].map((p) => Presence.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "presences": presences.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "presences": presences.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index c5f233b4..a825eab0 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -2,66 +2,66 @@ part of '../../models.dart'; /// Row class Row implements Model { - /// Row ID. - final String $id; + /// Row ID. + final String $id; - /// Row sequence ID. - final String $sequence; + /// Row sequence ID. + final String $sequence; - /// Table ID. - final String $tableId; + /// Table ID. + final String $tableId; - /// Database ID. - final String $databaseId; + /// Database ID. + final String $databaseId; - /// Row creation date in ISO 8601 format. - final String $createdAt; + /// Row creation date in ISO 8601 format. + final String $createdAt; - /// Row update date in ISO 8601 format. - final String $updatedAt; + /// Row update date in ISO 8601 format. + final String $updatedAt; - /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; + /// Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; - final Map data; + final Map data; - Row({ - required this.$id, - required this.$sequence, - required this.$tableId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); + Row({ + required this.$id, + required this.$sequence, + required this.$tableId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); - factory Row.fromMap(Map map) { - return Row( - $id: map['\$id'].toString(), - $sequence: map['\$sequence'].toString(), - $tableId: map['\$tableId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: List.from(map['\$permissions'] ?? []), - data: map["data"] ?? map, - ); - } + factory Row.fromMap(Map map) { + return Row( + $id: map['\$id'].toString(), + $sequence: map['\$sequence'].toString(), + $tableId: map['\$tableId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: List.from(map['\$permissions'] ?? []), + data: map["data"] ?? map, + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$sequence": $sequence, - "\$tableId": $tableId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$sequence": $sequence, + "\$tableId": $tableId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 90efa95f..5023c633 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -2,32 +2,32 @@ part of '../../models.dart'; /// Rows List class RowList implements Model { - /// Total number of rows that matched your query. - final int total; + /// Total number of rows that matched your query. + final int total; - /// List of rows. - final List rows; + /// List of rows. + final List rows; - RowList({ - required this.total, - required this.rows, - }); + RowList({ + required this.total, + required this.rows, + }); - factory RowList.fromMap(Map map) { - return RowList( - total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), - ); - } + factory RowList.fromMap(Map map) { + return RowList( + total: map['total'], + rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "rows": rows.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "rows": rows.map((p) => p.toMap()).toList(), + }; + } - List convertTo(T Function(Map) fromJson) => - rows.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + rows.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index c37de95a..92e4034e 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,191 +2,191 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; + /// Session ID. + final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; + /// Session creation date in ISO 8601 format. + final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; + /// Session expiration date in ISO 8601 format. + final String expire; - /// Session Provider. - final String provider; + /// Session Provider. + final String provider; - /// Session Provider User ID. - final String providerUid; + /// 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: List.from(map['factors'] ?? []), - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - @override - 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 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: List.from(map['factors'] ?? []), + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + @override + 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 d823d0e6..4ea12394 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions that matched your query. - final int total; + /// Total number of sessions 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + @override + 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 850ab8d2..450aafd1 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; + /// Subscriber ID. + final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; - /// Target ID. - final String targetId; + /// Target ID. + final String targetId; - /// Target. - final Target target; + /// Target. + final Target target; - /// Topic ID. - final String userId; + /// Topic ID. + final String userId; - /// User Name. - final String userName; + /// User Name. + final String userName; - /// Topic ID. - final String topicId; + /// Topic ID. + final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// 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, - }); + 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(), - ); - } + 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(), + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + @override + 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 742e7590..c2e8c4dc 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,71 +2,71 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; + /// Target ID. + final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; + /// Target creation time in ISO 8601 format. + final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; - /// Target Name. - final String name; + /// Target Name. + final String name; - /// User ID. - final String userId; + /// User ID. + final String userId; - /// Provider ID. - final String? providerId; + /// Provider ID. + final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; - /// The target identifier. - final String identifier; + /// The target identifier. + final String identifier; - /// Is the target expired. - final bool expired; + /// Is the target expired. + final bool expired; - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - required this.expired, - }); + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + required this.expired, + }); - 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(), - expired: map['expired'], - ); - } + 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(), + expired: map['expired'], + ); + } - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - "expired": expired, - }; - } + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + "expired": expired, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 21e65e95..91b888b9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,53 +2,53 @@ 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']), - ); - } - - @override - 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']), + ); + } + + @override + 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 ffca5e98..e8f1c621 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,29 +2,29 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams that matched your query. - final int total; + /// Total number of teams 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))), + ); + } - @override - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + @override + 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 b05320da..b5ea87c8 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,53 +2,53 @@ 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(), - ); - } - - @override - 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(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index e3f3e43d..b0606dd8 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -2,53 +2,53 @@ part of '../../models.dart'; /// Transaction class Transaction implements Model { - /// Transaction ID. - final String $id; - - /// Transaction creation time in ISO 8601 format. - final String $createdAt; - - /// Transaction update date in ISO 8601 format. - final String $updatedAt; - - /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. - final String status; - - /// Number of operations in the transaction. - final int operations; - - /// Expiration time in ISO 8601 format. - final String expiresAt; - - Transaction({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.status, - required this.operations, - required this.expiresAt, - }); - - factory Transaction.fromMap(Map map) { - return Transaction( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - status: map['status'].toString(), - operations: map['operations'], - expiresAt: map['expiresAt'].toString(), - ); - } - - @override - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "status": status, - "operations": operations, - "expiresAt": expiresAt, - }; - } + /// Transaction ID. + final String $id; + + /// Transaction creation time in ISO 8601 format. + final String $createdAt; + + /// Transaction update date in ISO 8601 format. + final String $updatedAt; + + /// Current status of the transaction. One of: pending, committing, committed, rolled_back, failed. + final String status; + + /// Number of operations in the transaction. + final int operations; + + /// Expiration time in ISO 8601 format. + final String expiresAt; + + Transaction({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.status, + required this.operations, + required this.expiresAt, + }); + + factory Transaction.fromMap(Map map) { + return Transaction( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + status: map['status'].toString(), + operations: map['operations'], + expiresAt: map['expiresAt'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "status": status, + "operations": operations, + "expiresAt": expiresAt, + }; + } } diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 19ea651d..7f321175 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -2,29 +2,30 @@ part of '../../models.dart'; /// Transaction List class TransactionList implements Model { - /// Total number of transactions that matched your query. - final int total; + /// Total number of transactions that matched your query. + final int total; - /// List of transactions. - final List transactions; + /// List of transactions. + final List transactions; - TransactionList({ - required this.total, - required this.transactions, - }); + TransactionList({ + required this.total, + required this.transactions, + }); - factory TransactionList.fromMap(Map map) { - return TransactionList( - total: map['total'], - transactions: List.from(map['transactions'].map((p) => Transaction.fromMap(p))), - ); - } + factory TransactionList.fromMap(Map map) { + return TransactionList( + total: map['total'], + transactions: List.from( + map['transactions'].map((p) => Transaction.fromMap(p))), + ); + } - @override - Map toMap() { - return { - "total": total, - "transactions": transactions.map((p) => p.toMap()).toList(), - }; - } + @override + Map toMap() { + return { + "total": total, + "transactions": transactions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index e3b9536b..5a6cad30 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,173 +2,173 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; + /// User ID. + final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; + /// User creation date in ISO 8601 format. + final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; + /// 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; - - /// Canonical form of the user email address. - final String? emailCanonical; - - /// Whether the user email is from a free email provider. - final bool? emailIsFree; - - /// Whether the user email is from a disposable email provider. - final bool? emailIsDisposable; - - /// Whether the user email is from a corporate domain. - final bool? emailIsCorporate; - - /// Whether the user email is in its canonical form. - final bool? emailIsCanonical; - - /// 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; - - /// Whether the user can impersonate other users. - final bool? impersonator; - - /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. - final String? impersonatorUserId; - - 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, - this.emailCanonical, - this.emailIsFree, - this.emailIsDisposable, - this.emailIsCorporate, - this.emailIsCanonical, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - this.impersonator, - this.impersonatorUserId, - }); - - 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: List.from(map['labels'] ?? []), - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - emailCanonical: map['emailCanonical']?.toString(), - emailIsFree: map['emailIsFree'], - emailIsDisposable: map['emailIsDisposable'], - emailIsCorporate: map['emailIsCorporate'], - emailIsCanonical: map['emailIsCanonical'], - 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(), - impersonator: map['impersonator'], - impersonatorUserId: map['impersonatorUserId']?.toString(), - ); - } - - @override - 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, - "emailCanonical": emailCanonical, - "emailIsFree": emailIsFree, - "emailIsDisposable": emailIsDisposable, - "emailIsCorporate": emailIsCorporate, - "emailIsCanonical": emailIsCanonical, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - "impersonator": impersonator, - "impersonatorUserId": impersonatorUserId, - }; - } + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + 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, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + + 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: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + 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, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 7a5e6303..28e4c43d 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(); /// ``` - /// + /// /// You can also use Channel builders: /// ```dart /// final subscription = realtime.subscribe([ diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 83f01b4c..0ed367a6 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 6cebb5b1..72edf5ee 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -58,9 +58,7 @@ mixin RealtimeMixin { _stopHeartbeat(); _heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) { if (_websok != null) { - _websok!.sink.add(jsonEncode({ - "type": "ping" - })); + _websok!.sink.add(jsonEncode({"type": "ping"})); } }); } @@ -140,9 +138,11 @@ mixin RealtimeMixin { case 'event': final messageData = data.data as Map; final message = RealtimeMessage.fromMap(messageData); - final subscriptions = (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? []; + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; if (subscriptions.isEmpty) { break; @@ -209,13 +209,15 @@ mixin RealtimeMixin { "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); - - var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; + + var queryParams = + "project=${Uri.encodeComponent(client.config['project']!)}"; final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) ? ':${uri.port}' : ''; - return Uri.parse("${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + return Uri.parse( + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -310,9 +312,11 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, [List queries = const []]) { + RealtimeSubscription subscribeTo(List channels, + [List queries = const []]) { StreamController controller = StreamController.broadcast(); - final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); + final channelStrings = + channels.map((ch) => _channelToString(ch)).toList().cast(); final queryStrings = List.from(queries); final subscriptionId = _generateUniqueSubscriptionId(); @@ -329,8 +333,7 @@ mixin RealtimeMixin { _sendUnsubscribeMessage([subscriptionId]); } - Future update( - {List? channels, List? queries}) async { + Future update({List? channels, List? queries}) async { final current = _subscriptions[subscriptionId]; if (current == null) { return; @@ -417,4 +420,4 @@ mixin RealtimeMixin { // until the application-level handshake completes. _flushPendingPresence(); } -} \ No newline at end of file +} diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index 56e7669a..b0356111 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 diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index ce0b7e95..3aab4e03 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -3,5 +3,5 @@ import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. RealtimeBase createRealtime(Client client) => throw UnsupportedError( - 'Cannot create a client without dart:html or dart:io.', -); + 'Cannot create a client without dart:html or dart:io.', + ); diff --git a/test/channel_test.dart b/test/channel_test.dart index 62031aec..9e0e11d3 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -13,12 +13,22 @@ void main() { }); test('returns database channel with action', () { - expect(Channel.database('db1').collection('col1').document('doc1').create().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .create() + .toString(), 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { - expect(Channel.database('db1').collection('col1').document('doc1').upsert().toString(), + expect( + Channel.database('db1') + .collection('col1') + .document('doc1') + .upsert() + .toString(), 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -34,7 +44,12 @@ void main() { }); test('returns tablesdb channel with action', () { - expect(Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + expect( + Channel.tablesdb('db1') + .table('table1') + .row('row1') + .update() + .toString(), 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -47,16 +62,16 @@ void main() { group('bucket()', () { test('throws when bucket id is missing', () { - expect(() => Channel.bucket(''), throwsArgumentError); + expect(() => Channel.bucket(''), throwsArgumentError); }); test('returns buckets channel with specific IDs', () { - expect(Channel.bucket('bucket1').file().toString(), - 'buckets.bucket1.files'); + expect( + Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), + expect(Channel.bucket('bucket1').file('file1').delete().toString(), 'buckets.bucket1.files.file1.delete'); }); }); @@ -83,29 +98,30 @@ void main() { group('teams()', () { test('throws when team id is missing', () { - expect(() => Channel.team(''), throwsArgumentError); + expect(() => Channel.team(''), throwsArgumentError); }); test('returns teams channel with specific team ID', () { - expect(Channel.team('team1').toString(), 'teams.team1'); + expect(Channel.team('team1').toString(), 'teams.team1'); }); test('returns teams channel with action', () { - expect(Channel.team('team1').create().toString(), 'teams.team1.create'); + expect(Channel.team('team1').create().toString(), 'teams.team1.create'); }); }); group('memberships()', () { test('throws when membership id is missing', () { - expect(() => Channel.membership(''), throwsArgumentError); + expect(() => Channel.membership(''), throwsArgumentError); }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), 'memberships.membership1'); + expect(Channel.membership('membership1').toString(), + 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), + expect(Channel.membership('membership1').update().toString(), 'memberships.membership1.update'); }); }); diff --git a/test/query_test.dart b/test/query_test.dart index 25388fad..db7b9214 100644 --- a/test/query_test.dart +++ b/test/query_test.dart @@ -354,4 +354,3 @@ void main() { expect(query['method'], 'between'); }); } - diff --git a/test/services/account_test.dart b/test/services/account_test.dart index 456c6b48..2752044f 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,1770 +40,1463 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Account test', () { - late MockClient client; - late Account account; - - setUp(() { - client = MockClient(); - account = Account(client); - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.get( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method listConsents()', () async { - - final Map data = { - 'total': 5, - 'consents': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listConsents( - ); - expect(response, isA()); - - }); - - test('test method getConsent()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'appId': '5e5ea5c16897e', - 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', - 'scopes': [], - 'resources': [], - 'authorizationDetails': '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - 'expire': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getConsent( - consentId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteConsent()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteConsent( - consentId: '', - ); - }); - - test('test method listConsentTokens()', () async { - - final Map data = { - 'total': 5, - 'tokens': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listConsentTokens( - consentId: '', - ); - expect(response, isA()); - - }); - - test('test method getConsentToken()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'consentId': '5e5ea5c16897e', - 'userId': '5e5ea5c16897e', - 'appId': '5e5ea5c16897e', - 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', - 'scopes': [], - 'resources': [], - 'authorizationDetails': '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - 'expire': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getConsentToken( - consentId: '', - tokenId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteConsentToken()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteConsentToken( - consentId: '', - tokenId: '', - ); - }); - - test('test method updateEmail()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method listIdentities()', () async { - - final Map data = { - 'total': 5, - 'identities': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listIdentities( - ); - expect(response, isA()); - - }); - - test('test method deleteIdentity()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteIdentity( - identityId: '', - ); - }); - - test('test method createJWT()', () async { - - final Map data = { - 'jwt': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createJWT( - ); - expect(response, isA()); - - }); - - test('test method listLogs()', () async { - - final Map data = { - 'total': 5, - 'logs': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listLogs( - ); - expect(response, isA()); - - }); - - test('test method updateMFA()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFA( - mfa: true, - ); - expect(response, isA()); - - }); - - test('test method createMfaAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method createMFAAuthenticator()', () async { - - final Map data = { - 'secret': '[SHARED_SECRET]', - 'uri': 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - expect(response, isA()); - - }); - - test('test method updateMfaAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAAuthenticator()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAAuthenticator( - type: enums.AuthenticatorType.totp, - otp: '', - ); - expect(response, isA()); - - }); - - test('test method deleteMfaAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMfaAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method deleteMFAAuthenticator()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteMFAAuthenticator( - type: enums.AuthenticatorType.totp, - ); - }); - - test('test method createMfaChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method createMFAChallenge()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFAChallenge( - factor: enums.AuthenticationFactor.email, - ); - expect(response, isA()); - - }); - - test('test method updateMfaChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method updateMFAChallenge()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', - ); - expect(response, isA()); - - }); - - test('test method listMfaFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMfaFactors( - ); - expect(response, isA()); - - }); + group('Account test', () { + late MockClient client; + late Account account; - test('test method listMFAFactors()', () async { - - final Map data = { - 'totp': true, - 'phone': true, - 'email': true, - 'recoveryCode': true, - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listMFAFactors( - ); - expect(response, isA()); - - }); - - test('test method getMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method getMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method createMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMfaRecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMfaRecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateMFARecoveryCodes()', () async { - - final Map data = { - 'recoveryCodes': [], - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMFARecoveryCodes( - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateName( - name: '', - ); - expect(response, isA()); - - }); - - test('test method updatePassword()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePassword( - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updatePhone()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method getPrefs()', () async { - - final Map data = { - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getPrefs( - ); - expect(response, isA()); - - }); - - test('test method updatePrefs()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePrefs( - prefs: {}, - ); - expect(response, isA()); - - }); - - test('test method createRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method updateRecovery()', () async { - - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method listSessions()', () async { - - final Map data = { - 'total': 5, - 'sessions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.listSessions( - ); - expect(response, isA()); - - }); - - test('test method deleteSessions()', () async { + setUp(() { + client = MockClient(); + account = Account(client); + }); - final data = ''; + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.get(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.create( + userId: '', + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); + test('test method listConsents()', () async { + final Map data = { + 'total': 5, + 'consents': [], + }; - final response = await account.deleteSessions( - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createAnonymousSession()', () async { + final response = await account.listConsents(); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createAnonymousSession( - ); - expect(response, isA()); - - }); - - test('test method createEmailPasswordSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', - ); - expect(response, isA()); - - }); - - test('test method updateMagicURLSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateMagicURLSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createOAuth2Session()', () async { - - - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); - - - final response = await account.createOAuth2Session( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); - - }); - - test('test method updatePhoneSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updatePhoneSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method createSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.createSession( - userId: '', - secret: '', - ); - expect(response, isA()); - - }); - - test('test method getSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.getSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateSession()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', - 'current': true, - 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.updateSession( - sessionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSession()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await account.deleteSession( - sessionId: '', - ); - }); - - test('test method updateStatus()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', - 'status': true, - 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', - 'emailVerification': true, - 'phoneVerification': true, - 'mfa': true, - 'prefs': {}, - 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + test('test method getConsent()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'appId': '5e5ea5c16897e', + 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + 'scopes': [], + 'resources': [], + 'authorizationDetails': + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.getConsent( + consentId: '', + ); + expect(response, isA()); + }); - }; + test('test method deleteConsent()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteConsent( + consentId: '', + ); + }); + test('test method listConsentTokens()', () async { + final Map data = { + 'total': 5, + 'tokens': [], + }; - final response = await account.updateStatus( - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.listConsentTokens( + consentId: '', + ); + expect(response, isA()); + }); - test('test method createPushTarget()', () async { + test('test method getConsentToken()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'consentId': '5e5ea5c16897e', + 'userId': '5e5ea5c16897e', + 'appId': '5e5ea5c16897e', + 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + 'scopes': [], + 'resources': [], + 'authorizationDetails': + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.getConsentToken( + consentId: '', + tokenId: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, + test('test method deleteConsentToken()', () async { + final data = ''; - }; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteConsentToken( + consentId: '', + tokenId: '', + ); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateEmail()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmail( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); + test('test method listIdentities()', () async { + final Map data = { + 'total': 5, + 'identities': [], + }; - final response = await account.createPushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.listIdentities(); + expect(response, isA()); + }); - test('test method updatePushTarget()', () async { + test('test method deleteIdentity()', () async { + final data = ''; - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }; + final response = await account.deleteIdentity( + identityId: '', + ); + }); + test('test method createJWT()', () async { + final Map data = { + 'jwt': + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.createJWT(); + expect(response, isA()); + }); - final response = await account.updatePushTarget( - targetId: '', - identifier: '', - ); - expect(response, isA()); + test('test method listLogs()', () async { + final Map data = { + 'total': 5, + 'logs': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method deletePushTarget()', () async { + final response = await account.listLogs(); + expect(response, isA()); + }); - final data = ''; + test('test method updateMFA()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFA( + mfa: true, + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createMfaAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); + test('test method createMFAAuthenticator()', () async { + final Map data = { + 'secret': '[SHARED_SECRET]', + 'uri': + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + expect(response, isA()); + }); - final response = await account.deletePushTarget( - targetId: '', - ); - }); + test('test method updateMfaAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); - test('test method createEmailToken()', () async { + test('test method updateMFAAuthenticator()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAAuthenticator( + type: enums.AuthenticatorType.totp, + otp: '', + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method deleteMfaAuthenticator()', () async { + final data = ''; - }; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteMfaAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteMFAAuthenticator()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + final response = await account.deleteMFAAuthenticator( + type: enums.AuthenticatorType.totp, + ); + }); - }); + test('test method createMfaChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMfaChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - test('test method createMagicURLToken()', () async { + test('test method createMFAChallenge()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'expire': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMFAChallenge( + factor: enums.AuthenticationFactor.email, + ); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method updateMfaChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMfaChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); - }; + test('test method updateMFAChallenge()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMFAChallenge( + challengeId: '', + otp: '', + ); + expect(response, isA()); + }); + test('test method listMfaFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.listMfaFactors(); + expect(response, isA()); + }); - final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', - ); - expect(response, isA()); + test('test method listMFAFactors()', () async { + final Map data = { + 'totp': true, + 'phone': true, + 'email': true, + 'recoveryCode': true, + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createOAuth2Token()', () async { + final response = await account.listMFAFactors(); + expect(response, isA()); + }); + test('test method getMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.getMfaRecoveryCodes(); + expect(response, isA()); + }); - final response = await account.createOAuth2Token( - provider: enums.OAuthProvider.amazon, - ); - expect(response, equals('done')); + test('test method getMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method createPhoneToken()', () async { + final response = await account.getMFARecoveryCodes(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method createMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - }; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.createMfaRecoveryCodes(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method createMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', - ); - expect(response, isA()); + final response = await account.createMFARecoveryCodes(); + expect(response, isA()); + }); - }); + test('test method updateMfaRecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; - test('test method createEmailVerification()', () async { + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + final response = await account.updateMfaRecoveryCodes(); + expect(response, isA()); + }); - }; + test('test method updateMFARecoveryCodes()', () async { + final Map data = { + 'recoveryCodes': [], + }; + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await account.updateMFARecoveryCodes(); + expect(response, isA()); + }); + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateName( + name: '', + ); + expect(response, isA()); + }); - final response = await account.createEmailVerification( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method updatePassword()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePassword( + password: 'password', + ); + expect(response, isA()); + }); - }); + test('test method updatePhone()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhone( + phone: '+12065550100', + password: 'password', + ); + expect(response, isA()); + }); - test('test method createVerification()', () async { + test('test method getPrefs()', () async { + final Map data = {}; - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }; + final response = await account.getPrefs(); + expect(response, isA()); + }); + test('test method updatePrefs()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePrefs( + prefs: {}, + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + test('test method createRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createRecovery( + email: 'email@example.com', + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method updateRecovery()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateRecovery( + userId: '', + secret: '', + password: 'password', + ); + expect(response, isA()); + }); - final response = await account.createVerification( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method listSessions()', () async { + final Map data = { + 'total': 5, + 'sessions': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method updateEmailVerification()', () async { + final response = await account.listSessions(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method deleteSessions()', () async { + final data = ''; - }; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deleteSessions(); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createAnonymousSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createAnonymousSession(); + expect(response, isA()); + }); + test('test method createEmailPasswordSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailPasswordSession( + email: 'email@example.com', + password: 'password', + ); + expect(response, isA()); + }); - final response = await account.updateEmailVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateMagicURLSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateMagicURLSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createOAuth2Session()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); - test('test method updateVerification()', () async { + final response = await account.createOAuth2Session( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method updatePhoneSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }; + test('test method createSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createSession( + userId: '', + secret: '', + ); + expect(response, isA()); + }); + test('test method getSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.getSession( + sessionId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateSession()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5bb8c16897e', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'provider': 'email', + 'providerUid': 'user@example.com', + 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', + 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + 'ip': '127.0.0.1', + 'osCode': 'Mac', + 'osName': 'Mac', + 'osVersion': 'Mac', + 'clientType': 'browser', + 'clientCode': 'CM', + 'clientName': 'Chrome Mobile iOS', + 'clientVersion': '84.0', + 'clientEngine': 'WebKit', + 'clientEngineVersion': '605.1.15', + 'deviceName': 'smartphone', + 'deviceBrand': 'Google', + 'deviceModel': 'Nexus 5', + 'countryCode': 'US', + 'countryName': 'United States', + 'current': true, + 'factors': [], + 'secret': '5e5bb8c16897e', + 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateSession( + sessionId: '', + ); + expect(response, isA()); + }); + test('test method deleteSession()', () async { + final data = ''; - final response = await account.updateVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await account.deleteSession( + sessionId: '', + ); + }); - test('test method createPhoneVerification()', () async { + test('test method updateStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'John Doe', + 'registration': '2020-10-15T06:38:00.000+00:00', + 'status': true, + 'labels': [], + 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', + 'email': 'john@appwrite.io', + 'phone': '+4930901820', + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateStatus(); + expect(response, isA()); + }); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + test('test method createPushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); - }; + test('test method updatePushTarget()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePushTarget( + targetId: '', + identifier: '', + ); + expect(response, isA()); + }); + test('test method deletePushTarget()', () async { + final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await account.deletePushTarget( + targetId: '', + ); + }); - final response = await account.createPhoneVerification( - ); - expect(response, isA()); + test('test method createEmailToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - }); + test('test method createMagicURLToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createMagicURLToken( + userId: '', + email: 'email@example.com', + ); + expect(response, isA()); + }); - test('test method updatePhoneVerification()', () async { + test('test method createOAuth2Token()', () async { + when(client.webAuth( + argThat(isNotNull), + )).thenAnswer((_) async => 'done'); - final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + final response = await account.createOAuth2Token( + provider: enums.OAuthProvider.amazon, + ); + expect(response, equals('done')); + }); - }; + test('test method createPhoneToken()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneToken( + userId: '', + phone: '+12065550100', + ); + expect(response, isA()); + }); + test('test method createEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + test('test method createVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createVerification( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method updateEmailVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmailVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - final response = await account.updatePhoneVerification( - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method updateVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateVerification( + userId: '', + secret: '', + ); + expect(response, isA()); + }); - }); + test('test method createPhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.createPhoneVerification(); + expect(response, isA()); + }); + test('test method updatePhoneVerification()', () async { + final Map data = { + '\$id': 'bb8ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c168bb8', + 'secret': '', + 'expire': '2020-10-15T06:38:00.000+00:00', + 'phrase': 'Golden Fox', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await account.updatePhoneVerification( + userId: '', + secret: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 4bdb434d..8d2c48fb 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,138 +40,123 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Avatars test', () { - late MockClient client; - late Avatars avatars; - - setUp(() { - client = MockClient(); - avatars = Avatars(client); - }); - - test('test method getBrowser()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getBrowser( - code: enums.Browser.avantBrowser, - ); - expect(response, isA()); - - }); - - test('test method getCreditCard()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - ); - expect(response, isA()); - - }); - - test('test method getFavicon()', () async { -final Uint8List data = Uint8List.fromList([]); + group('Avatars test', () { + late MockClient client; + late Avatars avatars; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await avatars.getFavicon( - url: 'https://example.com', - ); - expect(response, isA()); - - }); - - test('test method getFlag()', () async { -final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + avatars = Avatars(client); + }); + test('test method getBrowser()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getFlag( - code: enums.Flag.afghanistan, - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getBrowser( + code: enums.Browser.avantBrowser, + ); + expect(response, isA()); + }); - test('test method getImage()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getCreditCard()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getCreditCard( + code: enums.CreditCard.americanExpress, + ); + expect(response, isA()); + }); - final response = await avatars.getImage( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getFavicon()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getInitials()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await avatars.getFavicon( + url: 'https://example.com', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method getFlag()', () async { + final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await avatars.getInitials( - ); - expect(response, isA()); + final response = await avatars.getFlag( + code: enums.Flag.afghanistan, + ); + expect(response, isA()); + }); - }); + test('test method getImage()', () async { + final Uint8List data = Uint8List.fromList([]); - test('test method getQR()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getImage( + url: 'https://example.com', + ); + expect(response, isA()); + }); + test('test method getInitials()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await avatars.getQR( - text: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await avatars.getInitials(); + expect(response, isA()); + }); - test('test method getScreenshot()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getQR()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getQR( + text: '', + ); + expect(response, isA()); + }); - final response = await avatars.getScreenshot( - url: 'https://example.com', - ); - expect(response, isA()); + test('test method getScreenshot()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await avatars.getScreenshot( + url: 'https://example.com', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index d4bedd10..a3807093 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,361 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Databases test', () { - late MockClient client; - late Databases databases; - - setUp(() { - client = MockClient(); - databases = Databases(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listDocuments()', () async { - - final Map data = { - 'total': 5, - 'documents': [], - - }; - + group('Databases test', () { + late MockClient client; + late Databases databases; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.listDocuments( - databaseId: '', - collectionId: '', - ); - expect(response, isA()); - - }); - - test('test method createDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method updateDocument()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteDocument()', () async { - - final data = ''; + setUp(() { + client = MockClient(); + databases = Databases(client); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', - ); - }); + final response = await databases.listTransactions(); + expect(response, isA()); + }); - test('test method decrementDocumentAttribute()', () async { + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createTransaction(); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - }; + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); + test('test method deleteTransaction()', () async { + final data = ''; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await databases.deleteTransaction( + transactionId: '', + ); + }); - final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - }); + test('test method listDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.listDocuments( + databaseId: '', + collectionId: '', + ); + expect(response, isA()); + }); - test('test method incrementDocumentAttribute()', () async { + test('test method createDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], + test('test method getDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - }; + test('test method upsertDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); + test('test method updateDocument()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteDocument()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', - attribute: '', - ); - expect(response, isA()); + final response = await databases.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + ); + }); - }); + test('test method decrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); + }); + test('test method incrementDocumentAttribute()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$collectionId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await databases.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 734c15a8..c6e50a50 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,113 +40,100 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Functions test', () { - late MockClient client; - late Functions functions; - - setUp(() { - client = MockClient(); - functions = Functions(client); - }); - - test('test method listExecutions()', () async { - - final Map data = { - 'total': 5, - 'executions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.listExecutions( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method createExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.createExecution( - functionId: '', - ); - expect(response, isA()); - - }); - - test('test method getExecution()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', - 'requestHeaders': [], - 'responseStatusCode': 200, - 'responseBody': '', - 'responseHeaders': [], - 'logs': '', - 'errors': '', - 'duration': 0.4, - - }; + group('Functions test', () { + late MockClient client; + late Functions functions; + setUp(() { + client = MockClient(); + functions = Functions(client); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listExecutions()', () async { + final Map data = { + 'total': 5, + 'executions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await functions.getExecution( - functionId: '', - executionId: '', - ); - expect(response, isA()); + final response = await functions.listExecutions( + functionId: '', + ); + expect(response, isA()); + }); - }); + test('test method createExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.createExecution( + functionId: '', + ); + expect(response, isA()); + }); + test('test method getExecution()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'functionId': '5e5ea6g16897e', + 'deploymentId': '5e5ea5c16897e', + 'trigger': 'http', + 'status': 'processing', + 'requestMethod': 'GET', + 'requestPath': '/articles?id=5', + 'requestHeaders': [], + 'responseStatusCode': 200, + 'responseBody': '', + 'responseHeaders': [], + 'logs': '', + 'errors': '', + 'duration': 0.4, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await functions.getExecution( + functionId: '', + executionId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index c548e414..84b7de1c 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,47 +40,45 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Graphql test', () { - late MockClient client; - late Graphql graphql; - - setUp(() { - client = MockClient(); - graphql = Graphql(client); - }); - - test('test method query()', () async { - - final data = ''; + group('Graphql test', () { + late MockClient client; + late Graphql graphql; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await graphql.query( - query: {}, - ); - }); + setUp(() { + client = MockClient(); + graphql = Graphql(client); + }); - test('test method mutation()', () async { + test('test method query()', () async { + final data = ''; - final data = ''; + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.query( + query: {}, + ); + }); + test('test method mutation()', () async { + final data = ''; - final response = await graphql.mutation( - query: {}, - ); - }); + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + final response = await graphql.mutation( + query: {}, + ); }); + }); } diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index 842b85da..f9f6489d 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,184 +40,138 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Locale test', () { - late MockClient client; - late Locale locale; - - setUp(() { - client = MockClient(); - locale = Locale(client); - }); - - test('test method get()', () async { - - final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', - 'eu': true, - 'currency': 'USD', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.get( - ); - expect(response, isA()); - - }); - - test('test method listCodes()', () async { - - final Map data = { - 'total': 5, - 'localeCodes': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCodes( - ); - expect(response, isA()); - - }); - - test('test method listContinents()', () async { - - final Map data = { - 'total': 5, - 'continents': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listContinents( - ); - expect(response, isA()); - - }); + group('Locale test', () { + late MockClient client; + late Locale locale; - test('test method listCountries()', () async { - - final Map data = { - 'total': 5, - 'countries': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountries( - ); - expect(response, isA()); - - }); - - test('test method listCountriesEU()', () async { - - final Map data = { - 'total': 5, - 'countries': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await locale.listCountriesEU( - ); - expect(response, isA()); - - }); - - test('test method listCountriesPhones()', () async { - - final Map data = { - 'total': 5, - 'phones': [], - - }; + setUp(() { + client = MockClient(); + locale = Locale(client); + }); + test('test method get()', () async { + final Map data = { + 'ip': '127.0.0.1', + 'countryCode': 'US', + 'country': 'United States', + 'continentCode': 'NA', + 'continent': 'North America', + 'eu': true, + 'currency': 'USD', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await locale.get(); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method listCodes()', () async { + final Map data = { + 'total': 5, + 'localeCodes': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await locale.listCountriesPhones( - ); - expect(response, isA()); + final response = await locale.listCodes(); + expect(response, isA()); + }); - }); + test('test method listContinents()', () async { + final Map data = { + 'total': 5, + 'continents': [], + }; - test('test method listCurrencies()', () async { + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final Map data = { - 'total': 5, - 'currencies': [], + final response = await locale.listContinents(); + expect(response, isA()); + }); - }; + test('test method listCountries()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCountries(); + expect(response, isA()); + }); + test('test method listCountriesEU()', () async { + final Map data = { + 'total': 5, + 'countries': [], + }; - final response = await locale.listCurrencies( - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await locale.listCountriesEU(); + expect(response, isA()); + }); - test('test method listLanguages()', () async { + test('test method listCountriesPhones()', () async { + final Map data = { + 'total': 5, + 'phones': [], + }; - final Map data = { - 'total': 5, - 'languages': [], + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }; + final response = await locale.listCountriesPhones(); + expect(response, isA()); + }); + test('test method listCurrencies()', () async { + final Map data = { + 'total': 5, + 'currencies': [], + }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listCurrencies(); + expect(response, isA()); + }); - final response = await locale.listLanguages( - ); - expect(response, isA()); + test('test method listLanguages()', () async { + final Map data = { + 'total': 5, + 'languages': [], + }; - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await locale.listLanguages(); + expect(response, isA()); }); + }); } diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index bd05daaf..0c938eff 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,73 +40,68 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Messaging test', () { - late MockClient client; - late Messaging messaging; - - setUp(() { - client = MockClient(); - messaging = Messaging(client); - }); - - test('test method createSubscriber()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', - 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', - 'expired': true, - }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + group('Messaging test', () { + late MockClient client; + late Messaging messaging; + setUp(() { + client = MockClient(); + messaging = Messaging(client); + }); - final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteSubscriber()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method createSubscriber()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'targetId': '259125845563242502', + 'target': { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'Apple iPhone 12', + 'userId': '259125845563242502', + 'providerType': 'email', + 'identifier': 'token', + 'expired': true, + }, + 'userId': '5e5ea5c16897e', + 'userName': 'Aegon Targaryen', + 'topicId': '259125845563242502', + 'providerType': 'email', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await messaging.createSubscriber( + topicId: '', + subscriberId: '', + targetId: '', + ); + expect(response, isA()); + }); + test('test method deleteSubscriber()', () async { + final data = ''; - final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await messaging.deleteSubscriber( + topicId: '', + subscriberId: '', + ); }); + }); } diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart index f203e6ce..00455d84 100644 --- a/test/services/organization_test.dart +++ b/test/services/organization_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,137 +40,116 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Organization test', () { - late MockClient client; - late Organization organization; - - setUp(() { - client = MockClient(); - organization = Organization(client); - }); - - test('test method listInstallations()', () async { - - final Map data = { - 'total': 5, - 'installations': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await organization.listInstallations( - ); - expect(response, isA()); - - }); - - test('test method createInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await organization.createInstallation( - appId: '', - ); - expect(response, isA()); - - }); + group('Organization test', () { + late MockClient client; + late Organization organization; - test('test method getInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await organization.getInstallation( - installationId: '', - ); - expect(response, isA()); - - }); - - test('test method updateInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + organization = Organization(client); + }); + test('test method listInstallations()', () async { + final Map data = { + 'total': 5, + 'installations': [], + }; - final response = await organization.updateInstallation( - installationId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await organization.listInstallations(); + expect(response, isA()); + }); - test('test method deleteInstallation()', () async { + test('test method createInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await organization.createInstallation( + appId: '', + ); + expect(response, isA()); + }); - final data = ''; + test('test method getInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await organization.getInstallation( + installationId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method updateInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await organization.updateInstallation( + installationId: '', + ); + expect(response, isA()); + }); + test('test method deleteInstallation()', () async { + final data = ''; - final response = await organization.deleteInstallation( - installationId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await organization.deleteInstallation( + installationId: '', + ); }); + }); } diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index a15aedc8..7fed0439 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,129 +40,108 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Presences test', () { - late MockClient client; - late Presences presences; - - setUp(() { - client = MockClient(); - presences = Presences(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'presences': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.list( - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.get( - presenceId: '', - ); - expect(response, isA()); - - }); + group('Presences test', () { + late MockClient client; + late Presences presences; - test('test method upsert()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await presences.upsert( - presenceId: '', - status: '', - ); - expect(response, isA()); - - }); - - test('test method update()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + presences = Presences(client); + }); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'presences': [], + }; - final response = await presences.update( - presenceId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await presences.list(); + expect(response, isA()); + }); - test('test method delete()', () async { + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.get( + presenceId: '', + ); + expect(response, isA()); + }); - final data = ''; + test('test method upsert()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.upsert( + presenceId: '', + status: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method update()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'userId': '674af8f3e12a5f9ac0be', + 'source': 'HTTP', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await presences.update( + presenceId: '', + ); + expect(response, isA()); + }); + test('test method delete()', () async { + final data = ''; - final response = await presences.delete( - presenceId: '', - ); - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await presences.delete( + presenceId: '', + ); }); + }); } diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 15808cd1..9ee2b2c2 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,216 +40,190 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Storage test', () { - late MockClient client; - late Storage storage; - - setUp(() { - client = MockClient(); - storage = Storage(client); - }); - - test('test method listFiles()', () async { - - final Map data = { - 'total': 5, - 'files': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.listFiles( - bucketId: '', - ); - expect(response, isA()); - - }); - - test('test method createFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - - }; - - - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.createFile( - bucketId: '', - fileId: '', - file: InputFile.fromPath(path: './image.png'), - ); - expect(response, isA()); - - }); - - test('test method getFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - - }; - + group('Storage test', () { + late MockClient client; + late Storage storage; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.getFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method updateFile()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', - 'sizeOriginal': 17890, - 'sizeActual': 12345, - 'chunksTotal': 17890, - 'chunksUploaded': 17890, - 'encryption': true, - 'compression': 'gzip', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await storage.updateFile( - bucketId: '', - fileId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteFile()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + setUp(() { + client = MockClient(); + storage = Storage(client); + }); + test('test method listFiles()', () async { + final Map data = { + 'total': 5, + 'files': [], + }; - final response = await storage.deleteFile( - bucketId: '', - fileId: '', - ); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - test('test method getFileDownload()', () async { -final Uint8List data = Uint8List.fromList([]); + final response = await storage.listFiles( + bucketId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method createFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.createFile( + bucketId: '', + fileId: '', + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + test('test method getFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.getFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileDownload( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method updateFile()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + 'bucketId': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + 'name': 'Pink.png', + 'folder': 'photos/2026/', + 'key': 'photos/2026/Pink.png', + 'signature': '5d529fd02b544198ae075bd57c1762bb', + 'mimeType': 'image/png', + 'sizeOriginal': 17890, + 'sizeActual': 12345, + 'chunksTotal': 17890, + 'chunksUploaded': 17890, + 'encryption': true, + 'compression': 'gzip', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await storage.updateFile( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - }); + test('test method deleteFile()', () async { + final data = ''; - test('test method getFilePreview()', () async { -final Uint8List data = Uint8List.fromList([]); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + final response = await storage.deleteFile( + bucketId: '', + fileId: '', + ); + }); + test('test method getFileDownload()', () async { + final Uint8List data = Uint8List.fromList([]); - final response = await storage.getFilePreview( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }); + final response = await storage.getFileDownload( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - test('test method getFileView()', () async { -final Uint8List data = Uint8List.fromList([]); + test('test method getFilePreview()', () async { + final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFilePreview( + bucketId: '', + fileId: '', + ); + expect(response, isA()); + }); - final response = await storage.getFileView( - bucketId: '', - fileId: '', - ); - expect(response, isA()); + test('test method getFileView()', () async { + final Uint8List data = Uint8List.fromList([]); - }); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await storage.getFileView( + bucketId: '', + fileId: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 3b800ee4..f318cad2 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,361 +40,297 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('TablesDB test', () { - late MockClient client; - late TablesDB tablesDB; - - setUp(() { - client = MockClient(); - tablesDB = TablesDB(client); - }); - - test('test method listTransactions()', () async { - - final Map data = { - 'total': 5, - 'transactions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listTransactions( - ); - expect(response, isA()); - - }); - - test('test method createTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createTransaction( - ); - expect(response, isA()); - - }); - - test('test method getTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method updateTransaction()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateTransaction( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteTransaction()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.deleteTransaction( - transactionId: '', - ); - }); - - test('test method createOperations()', () async { - - final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', - 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createOperations( - transactionId: '', - ); - expect(response, isA()); - - }); - - test('test method listRows()', () async { - - final Map data = { - 'total': 5, - 'rows': [], - - }; - + group('TablesDB test', () { + late MockClient client; + late TablesDB tablesDB; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.listRows( - databaseId: '', - tableId: '', - ); - expect(response, isA()); - - }); - - test('test method createRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', - data: {}, - ); - expect(response, isA()); - - }); - - test('test method getRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method upsertRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method updateRow()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], - - }; - - - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteRow()', () async { - - final data = ''; + setUp(() { + client = MockClient(); + tablesDB = TablesDB(client); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', - ); - }); + final response = await tablesDB.listTransactions(); + expect(response, isA()); + }); - test('test method decrementRowColumn()', () async { + test('test method createTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createTransaction(); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], + test('test method getTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getTransaction( + transactionId: '', + ); + expect(response, isA()); + }); - }; + test('test method updateTransaction()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateTransaction( + transactionId: '', + ); + expect(response, isA()); + }); + test('test method deleteTransaction()', () async { + final data = ''; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); + final response = await tablesDB.deleteTransaction( + transactionId: '', + ); + }); - final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + test('test method createOperations()', () async { + final Map data = { + '\$id': '259125845563242502', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'status': 'pending', + 'operations': 5, + 'expiresAt': '2020-10-15T06:38:00.000+00:00', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createOperations( + transactionId: '', + ); + expect(response, isA()); + }); - }); + test('test method listRows()', () async { + final Map data = { + 'total': 5, + 'rows': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.listRows( + databaseId: '', + tableId: '', + ); + expect(response, isA()); + }); - test('test method incrementRowColumn()', () async { + test('test method createRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.createRow( + databaseId: '', + tableId: '', + rowId: '', + data: {}, + ); + expect(response, isA()); + }); - final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - '\$permissions': [], + test('test method getRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.getRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - }; + test('test method upsertRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.upsertRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); + test('test method updateRow()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.updateRow( + databaseId: '', + tableId: '', + rowId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method deleteRow()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', - column: '', - ); - expect(response, isA()); + final response = await tablesDB.deleteRow( + databaseId: '', + tableId: '', + rowId: '', + ); + }); - }); + test('test method decrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.decrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); + }); + test('test method incrementRowColumn()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$sequence': '1', + '\$tableId': '5e5ea5c15117e', + '\$databaseId': '5e5ea5c15117e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$permissions': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await tablesDB.incrementRowColumn( + databaseId: '', + tableId: '', + rowId: '', + column: '', + ); + expect(response, isA()); }); + }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index 0dfbc4de..d308ebe3 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -24,12 +24,11 @@ class MockClient extends Mock implements Client { @override Future webAuth( - Uri? url, - { - String? callbackUrlScheme, - } - ) async { - return super.noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Uri? url, { + String? callbackUrlScheme, + }) async { + return super + .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); } @override @@ -41,471 +40,389 @@ class MockClient extends Mock implements Client { Map? headers, Function(UploadProgress)? onProgress, }) async { - return super.noSuchMethod(Invocation.method(#chunkedUpload, [path, params, paramName, idParamName, headers]), returnValue: Response(data: {})); + return super.noSuchMethod( + Invocation.method( + #chunkedUpload, [path, params, paramName, idParamName, headers]), + returnValue: Response(data: {})); } } void main() { - group('Teams test', () { - late MockClient client; - late Teams teams; - - setUp(() { - client = MockClient(); - teams = Teams(client); - }); - - test('test method list()', () async { - - final Map data = { - 'total': 5, - 'teams': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.list( - ); - expect(response, isA()); - - }); - - test('test method create()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.create( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method get()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.get( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method updateName()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', - 'total': 7, - 'prefs': {}, - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateName( - teamId: '', - name: '', - ); - expect(response, isA()); - - }); - - test('test method delete()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.delete( - teamId: '', - ); - }); - - test('test method listInstallations()', () async { - - final Map data = { - 'total': 5, - 'installations': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.listInstallations( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method createInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.createInstallation( - teamId: '', - appId: '', - ); - expect(response, isA()); - - }); - - test('test method getInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.getInstallation( - teamId: '', - installationId: '', - ); - expect(response, isA()); - - }); - - test('test method updateInstallation()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - - }; - - - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.updateInstallation( - teamId: '', - installationId: '', - ); - expect(response, isA()); - - }); - - test('test method deleteInstallation()', () async { - - final data = ''; - - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.deleteInstallation( - teamId: '', - installationId: '', - ); - }); - - test('test method listMemberships()', () async { - - final Map data = { - 'total': 5, - 'memberships': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.listMemberships( - teamId: '', - ); - expect(response, isA()); - - }); - - test('test method createMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - - }; - - - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.createMembership( - teamId: '', - roles: [], - ); - expect(response, isA()); - - }); - - test('test method getMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - - }; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await teams.getMembership( - teamId: '', - membershipId: '', - ); - expect(response, isA()); - - }); - - test('test method updateMembership()', () async { - - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], - - }; + group('Teams test', () { + late MockClient client; + late Teams teams; + setUp(() { + client = MockClient(); + teams = Teams(client); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method list()', () async { + final Map data = { + 'total': 5, + 'teams': [], + }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.updateMembership( - teamId: '', - membershipId: '', - roles: [], - ); - expect(response, isA()); + final response = await teams.list(); + expect(response, isA()); + }); - }); + test('test method create()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.create( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - test('test method deleteMembership()', () async { + test('test method get()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.get( + teamId: '', + ); + expect(response, isA()); + }); - final data = ''; + test('test method updateName()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'name': 'VIP', + 'total': 7, + 'prefs': {}, + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateName( + teamId: '', + name: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + test('test method delete()', () async { + final data = ''; + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final response = await teams.deleteMembership( - teamId: '', - membershipId: '', - ); - }); + final response = await teams.delete( + teamId: '', + ); + }); - test('test method updateMembershipStatus()', () async { + test('test method listInstallations()', () async { + final Map data = { + 'total': 5, + 'installations': [], + }; - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', - 'confirm': true, - 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', - 'roles': [], + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); - }; + final response = await teams.listInstallations( + teamId: '', + ); + expect(response, isA()); + }); + test('test method createInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.createInstallation( + teamId: '', + appId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + test('test method getInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.getInstallation( + teamId: '', + installationId: '', + ); + expect(response, isA()); + }); + test('test method updateInstallation()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'appId': '5e5ea5c16897e', + 'teamId': '5e5ea5c16897e', + 'scopes': [], + 'authorizationDetails': {}, + 'createdById': '5e5ea5c16897e', + 'createdByName': 'Walter White', + }; + + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateInstallation( + teamId: '', + installationId: '', + ); + expect(response, isA()); + }); - final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', - ); - expect(response, isA()); + test('test method deleteInstallation()', () async { + final data = ''; - }); + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - test('test method getPrefs()', () async { + final response = await teams.deleteInstallation( + teamId: '', + installationId: '', + ); + }); - final Map data = { + test('test method listMemberships()', () async { + final Map data = { + 'total': 5, + 'memberships': [], + }; - }; + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.listMemberships( + teamId: '', + ); + expect(response, isA()); + }); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + test('test method createMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.post, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.createMembership( + teamId: '', + roles: [], + ); + expect(response, isA()); + }); + test('test method getMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.getMembership( + teamId: '', + membershipId: '', + ); + expect(response, isA()); + }); - final response = await teams.getPrefs( - teamId: '', - ); - expect(response, isA()); + test('test method updateMembership()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembership( + teamId: '', + membershipId: '', + roles: [], + ); + expect(response, isA()); + }); - }); + test('test method deleteMembership()', () async { + final data = ''; - test('test method updatePrefs()', () async { + when(client.call( + HttpMethod.delete, + )).thenAnswer((_) async => Response(data: data)); - final Map data = { + final response = await teams.deleteMembership( + teamId: '', + membershipId: '', + ); + }); - }; + test('test method updateMembershipStatus()', () async { + final Map data = { + '\$id': '5e5ea5c16897e', + '\$createdAt': '2020-10-15T06:38:00.000+00:00', + '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + 'userId': '5e5ea5c16897e', + 'userName': 'John Doe', + 'userEmail': 'john@appwrite.io', + 'userPhone': '+1 555 555 5555', + 'teamId': '5e5ea5c16897e', + 'teamName': 'VIP', + 'invited': '2020-10-15T06:38:00.000+00:00', + 'joined': '2020-10-15T06:38:00.000+00:00', + 'confirm': true, + 'mfa': true, + 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'roles': [], + }; + + when(client.call( + HttpMethod.patch, + )).thenAnswer((_) async => Response(data: data)); + + final response = await teams.updateMembershipStatus( + teamId: '', + membershipId: '', + userId: '', + secret: '', + ); + expect(response, isA()); + }); + test('test method getPrefs()', () async { + final Map data = {}; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.getPrefs( + teamId: '', + ); + expect(response, isA()); + }); - final response = await teams.updatePrefs( - teamId: '', - prefs: {}, - ); - expect(response, isA()); + test('test method updatePrefs()', () async { + final Map data = {}; - }); + when(client.call( + HttpMethod.put, + )).thenAnswer((_) async => Response(data: data)); + final response = await teams.updatePrefs( + teamId: '', + prefs: {}, + ); + expect(response, isA()); }); + }); } diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 15e85f5a..261daa46 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); - expect(result.memoryCost, 65536); - expect(result.timeCost, 4); - expect(result.threads, 3); - }); + expect(result.type, 'argon2'); + expect(result.memoryCost, 65536); + expect(result.timeCost, 4); + expect(result.threads, 3); + }); }); } diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 87a3ca3c..3da36624 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); - }); + expect(result.type, 'bcrypt'); + }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index 3b842e6c..e58fa5b5 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); - }); + expect(result.type, 'md5'); + }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 49b1e22c..3bcbb488 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); - }); + expect(result.type, 'phpass'); + }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index dd7fa8c3..b2084927 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -8,16 +8,18 @@ void main() { type: 'scryptMod', salt: 'UxLMreBr6tYyjQ==', saltSeparator: 'Bw==', - signerKey: 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + signerKey: + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); - }); + expect(result.type, 'scryptMod'); + expect(result.salt, 'UxLMreBr6tYyjQ=='); + expect(result.saltSeparator, 'Bw=='); + expect(result.signerKey, + 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index c7d9cdbf..8c131568 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -15,11 +15,11 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); - expect(result.costCpu, 8); - expect(result.costMemory, 14); - expect(result.costParallel, 1); - expect(result.length, 64); - }); + expect(result.type, 'scrypt'); + expect(result.costCpu, 8); + expect(result.costMemory, 14); + expect(result.costParallel, 1); + expect(result.length, 64); + }); }); } diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index ae58b57e..d080569c 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); - }); + expect(result.type, 'sha'); + }); }); } diff --git a/test/src/models/app_installation_list_test.dart b/test/src/models/app_installation_list_test.dart index 0cc780a1..9a9955d4 100644 --- a/test/src/models/app_installation_list_test.dart +++ b/test/src/models/app_installation_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = AppInstallationList.fromMap(map); - expect(result.total, 5); - expect(result.installations, []); - }); + expect(result.total, 5); + expect(result.installations, []); + }); }); } diff --git a/test/src/models/app_installation_test.dart b/test/src/models/app_installation_test.dart index 3afac34b..dc0ec63c 100644 --- a/test/src/models/app_installation_test.dart +++ b/test/src/models/app_installation_test.dart @@ -19,15 +19,15 @@ void main() { final map = model.toMap(); final result = AppInstallation.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.scopes, []); - expect(result.authorizationDetails, {}); - expect(result.createdById, '5e5ea5c16897e'); - expect(result.createdByName, 'Walter White'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.scopes, []); + expect(result.authorizationDetails, {}); + expect(result.createdById, '5e5ea5c16897e'); + expect(result.createdByName, 'Walter White'); + }); }); } diff --git a/test/src/models/continent_list_test.dart b/test/src/models/continent_list_test.dart index 8de695b0..e71dcae1 100644 --- a/test/src/models/continent_list_test.dart +++ b/test/src/models/continent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = ContinentList.fromMap(map); - expect(result.total, 5); - expect(result.continents, []); - }); + expect(result.total, 5); + expect(result.continents, []); + }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index d5242a4e..85e559f5 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); - }); + expect(result.name, 'Europe'); + expect(result.code, 'EU'); + }); }); } diff --git a/test/src/models/country_list_test.dart b/test/src/models/country_list_test.dart index 869f5db6..6df5c584 100644 --- a/test/src/models/country_list_test.dart +++ b/test/src/models/country_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CountryList.fromMap(map); - expect(result.total, 5); - expect(result.countries, []); - }); + expect(result.total, 5); + expect(result.countries, []); + }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index bc66ab7b..d5404a7f 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); - }); + expect(result.name, 'United States'); + expect(result.code, 'US'); + }); }); } diff --git a/test/src/models/currency_list_test.dart b/test/src/models/currency_list_test.dart index 09da675c..d7410db8 100644 --- a/test/src/models/currency_list_test.dart +++ b/test/src/models/currency_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = CurrencyList.fromMap(map); - expect(result.total, 5); - expect(result.currencies, []); - }); + expect(result.total, 5); + expect(result.currencies, []); + }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 29890008..00e046c7 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); - expect(result.decimalDigits, 2); - expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); - }); + expect(result.symbol, '\$'); + expect(result.name, 'US dollar'); + expect(result.symbolNative, '\$'); + expect(result.decimalDigits, 2); + expect(result.rounding, 0); + expect(result.code, 'USD'); + expect(result.namePlural, 'US dollars'); + }); }); } diff --git a/test/src/models/document_list_test.dart b/test/src/models/document_list_test.dart index f1a5b3cc..217d37e8 100644 --- a/test/src/models/document_list_test.dart +++ b/test/src/models/document_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = DocumentList.fromMap(map); - expect(result.total, 5); - expect(result.documents, []); - }); + expect(result.total, 5); + expect(result.documents, []); + }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 6c1fbb77..397b5fab 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$collectionId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/execution_list_test.dart b/test/src/models/execution_list_test.dart index cb10c58e..8d209722 100644 --- a/test/src/models/execution_list_test.dart +++ b/test/src/models/execution_list_test.dart @@ -13,8 +13,8 @@ void main() { final map = model.toMap(); final result = ExecutionList.fromMap(map); - expect(result.total, 5); - expect(result.executions, []); - }); + expect(result.total, 5); + expect(result.executions, []); + }); }); } diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 6d9bf33c..80ef508a 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -28,23 +28,23 @@ void main() { final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); - expect(result.trigger, ExecutionTrigger.http); - expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); - expect(result.requestHeaders, []); - expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); - expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); - expect(result.duration, 0.4); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.functionId, '5e5ea6g16897e'); + expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.trigger, ExecutionTrigger.http); + expect(result.status, ExecutionStatus.waiting); + expect(result.requestMethod, 'GET'); + expect(result.requestPath, '/articles?id=5'); + expect(result.requestHeaders, []); + expect(result.responseStatusCode, 200); + expect(result.responseBody, ''); + expect(result.responseHeaders, []); + expect(result.logs, ''); + expect(result.errors, ''); + expect(result.duration, 0.4); + }); }); } diff --git a/test/src/models/file_list_test.dart b/test/src/models/file_list_test.dart index d8e6c95c..8e02f65e 100644 --- a/test/src/models/file_list_test.dart +++ b/test/src/models/file_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = FileList.fromMap(map); - expect(result.total, 5); - expect(result.files, []); - }); + expect(result.total, 5); + expect(result.files, []); + }); }); } diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 037b5e4d..7bf20fce 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -26,22 +26,22 @@ void main() { final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.folder, 'photos/2026/'); - expect(result.key, 'photos/2026/Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); - expect(result.sizeOriginal, 17890); - expect(result.sizeActual, 12345); - expect(result.chunksTotal, 17890); - expect(result.chunksUploaded, 17890); - expect(result.encryption, true); - expect(result.compression, 'gzip'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.bucketId, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.name, 'Pink.png'); + expect(result.folder, 'photos/2026/'); + expect(result.key, 'photos/2026/Pink.png'); + expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); + expect(result.mimeType, 'image/png'); + expect(result.sizeOriginal, 17890); + expect(result.sizeActual, 12345); + expect(result.chunksTotal, 17890); + expect(result.chunksUploaded, 17890); + expect(result.encryption, true); + expect(result.compression, 'gzip'); + }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 489891d4..9252b469 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); - }); + expect(result.name, 'Content-Type'); + expect(result.value, 'application/json'); + }); }); } diff --git a/test/src/models/identity_list_test.dart b/test/src/models/identity_list_test.dart index 65f562a7..8c35afec 100644 --- a/test/src/models/identity_list_test.dart +++ b/test/src/models/identity_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = IdentityList.fromMap(map); - expect(result.total, 5); - expect(result.identities, []); - }); + expect(result.total, 5); + expect(result.identities, []); + }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 708c8c60..525af4ea 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -20,16 +20,16 @@ void main() { final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.provider, 'email'); + expect(result.providerUid, '5e5bb8c16897e'); + expect(result.providerEmail, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index e616a956..93376af1 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -5,13 +5,15 @@ void main() { group('Jwt', () { test('model', () { final model = Jwt( - jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + jwt: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); - }); + expect(result.jwt, + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + }); }); } diff --git a/test/src/models/language_list_test.dart b/test/src/models/language_list_test.dart index 94c1e33f..a07c0b5f 100644 --- a/test/src/models/language_list_test.dart +++ b/test/src/models/language_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LanguageList.fromMap(map); - expect(result.total, 5); - expect(result.languages, []); - }); + expect(result.total, 5); + expect(result.languages, []); + }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index d4087d5e..4a6c96c1 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); - }); + expect(result.name, 'Italian'); + expect(result.code, 'it'); + expect(result.nativeName, 'Italiano'); + }); }); } diff --git a/test/src/models/locale_code_list_test.dart b/test/src/models/locale_code_list_test.dart index b6de5137..65b44ad1 100644 --- a/test/src/models/locale_code_list_test.dart +++ b/test/src/models/locale_code_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCodeList.fromMap(map); - expect(result.total, 5); - expect(result.localeCodes, []); - }); + expect(result.total, 5); + expect(result.localeCodes, []); + }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index f0fcdbce..88cf157b 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); - }); + expect(result.code, 'en-us'); + expect(result.name, 'US'); + }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 72102045..49cb1fc9 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -17,13 +17,13 @@ void main() { final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); - expect(result.eu, true); - expect(result.currency, 'USD'); - }); + expect(result.ip, '127.0.0.1'); + expect(result.countryCode, 'US'); + expect(result.country, 'United States'); + expect(result.continentCode, 'NA'); + expect(result.continent, 'North America'); + expect(result.eu, true); + expect(result.currency, 'USD'); + }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart index 84c560c8..b07ca8ee 100644 --- a/test/src/models/log_list_test.dart +++ b/test/src/models/log_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = LogList.fromMap(map); - expect(result.total, 5); - expect(result.logs, []); - }); + expect(result.total, 5); + expect(result.logs, []); + }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index 1b463633..c8211d3b 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -32,28 +32,28 @@ void main() { final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.event, 'account.sessions.create'); + expect(result.userId, '610fc2f985ee0'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userName, 'John Doe'); + expect(result.mode, 'admin'); + expect(result.userType, 'user'); + expect(result.ip, '127.0.0.1'); + expect(result.time, '2020-10-15T06:38:00.000+00:00'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/membership_list_test.dart b/test/src/models/membership_list_test.dart index bb1f0946..4f30c48e 100644 --- a/test/src/models/membership_list_test.dart +++ b/test/src/models/membership_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = MembershipList.fromMap(map); - expect(result.total, 5); - expect(result.memberships, []); - }); + expect(result.total, 5); + expect(result.memberships, []); + }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index ab136c24..b2b8bd3d 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -25,21 +25,21 @@ void main() { final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); - expect(result.confirm, true); - expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.roles, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'John Doe'); + expect(result.userEmail, 'john@appwrite.io'); + expect(result.userPhone, '+1 555 555 5555'); + expect(result.teamId, '5e5ea5c16897e'); + expect(result.teamName, 'VIP'); + expect(result.invited, '2020-10-15T06:38:00.000+00:00'); + expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.confirm, true); + expect(result.mfa, true); + expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.roles, []); + }); }); } diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 9410baa3..5d3febca 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index ed6467d3..64cc55e4 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -14,10 +14,10 @@ void main() { final map = model.toMap(); final result = MfaFactors.fromMap(map); - expect(result.totp, true); - expect(result.phone, true); - expect(result.email, true); - expect(result.recoveryCode, true); - }); + expect(result.totp, true); + expect(result.phone, true); + expect(result.email, true); + expect(result.recoveryCode, true); + }); }); } diff --git a/test/src/models/mfa_recovery_codes_test.dart b/test/src/models/mfa_recovery_codes_test.dart index fa097a49..500913c8 100644 --- a/test/src/models/mfa_recovery_codes_test.dart +++ b/test/src/models/mfa_recovery_codes_test.dart @@ -11,7 +11,7 @@ void main() { final map = model.toMap(); final result = MfaRecoveryCodes.fromMap(map); - expect(result.recoveryCodes, []); - }); + expect(result.recoveryCodes, []); + }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 3f45d288..81657394 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -6,14 +6,16 @@ void main() { test('model', () { final model = MfaType( secret: '[SHARED_SECRET]', - uri: 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + uri: + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); - }); + expect(result.secret, '[SHARED_SECRET]'); + expect(result.uri, + 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + }); }); } diff --git a/test/src/models/oauth2_consent_list_test.dart b/test/src/models/oauth2_consent_list_test.dart index 07406f01..be54297f 100644 --- a/test/src/models/oauth2_consent_list_test.dart +++ b/test/src/models/oauth2_consent_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Oauth2ConsentList.fromMap(map); - expect(result.total, 5); - expect(result.consents, []); - }); + expect(result.total, 5); + expect(result.consents, []); + }); }); } diff --git a/test/src/models/oauth2_consent_test.dart b/test/src/models/oauth2_consent_test.dart index 5a89ec43..32456d3c 100644 --- a/test/src/models/oauth2_consent_test.dart +++ b/test/src/models/oauth2_consent_test.dart @@ -13,23 +13,26 @@ void main() { cimdUrl: 'https://example.com/.well-known/client-metadata.json', scopes: [], resources: [], - authorizationDetails: '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + authorizationDetails: + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', expire: '2020-10-15T06:38:00.000+00:00', ); final map = model.toMap(); final result = Oauth2Consent.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.cimdUrl, 'https://example.com/.well-known/client-metadata.json'); - expect(result.scopes, []); - expect(result.resources, []); - expect(result.authorizationDetails, '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.cimdUrl, + 'https://example.com/.well-known/client-metadata.json'); + expect(result.scopes, []); + expect(result.resources, []); + expect(result.authorizationDetails, + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/oauth2_consent_token_list_test.dart b/test/src/models/oauth2_consent_token_list_test.dart index a2271e56..1048af89 100644 --- a/test/src/models/oauth2_consent_token_list_test.dart +++ b/test/src/models/oauth2_consent_token_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = Oauth2ConsentTokenList.fromMap(map); - expect(result.total, 5); - expect(result.tokens, []); - }); + expect(result.total, 5); + expect(result.tokens, []); + }); }); } diff --git a/test/src/models/oauth2_consent_token_test.dart b/test/src/models/oauth2_consent_token_test.dart index 39dda758..e8a7b94b 100644 --- a/test/src/models/oauth2_consent_token_test.dart +++ b/test/src/models/oauth2_consent_token_test.dart @@ -14,24 +14,27 @@ void main() { cimdUrl: 'https://example.com/.well-known/client-metadata.json', scopes: [], resources: [], - authorizationDetails: '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', + authorizationDetails: + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', expire: '2020-10-15T06:38:00.000+00:00', ); final map = model.toMap(); final result = Oauth2ConsentToken.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.consentId, '5e5ea5c16897e'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.cimdUrl, 'https://example.com/.well-known/client-metadata.json'); - expect(result.scopes, []); - expect(result.resources, []); - expect(result.authorizationDetails, '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.consentId, '5e5ea5c16897e'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.appId, '5e5ea5c16897e'); + expect(result.cimdUrl, + 'https://example.com/.well-known/client-metadata.json'); + expect(result.scopes, []); + expect(result.resources, []); + expect(result.authorizationDetails, + '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/phone_list_test.dart b/test/src/models/phone_list_test.dart index 6ca46a63..bf22a5c7 100644 --- a/test/src/models/phone_list_test.dart +++ b/test/src/models/phone_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PhoneList.fromMap(map); - expect(result.total, 5); - expect(result.phones, []); - }); + expect(result.total, 5); + expect(result.phones, []); + }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index d0e5333b..f70db0e3 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -13,9 +13,9 @@ void main() { final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - }); + expect(result.code, '+1'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + }); }); } diff --git a/test/src/models/preferences_test.dart b/test/src/models/preferences_test.dart index acde349c..9db30b03 100644 --- a/test/src/models/preferences_test.dart +++ b/test/src/models/preferences_test.dart @@ -10,7 +10,6 @@ void main() { final map = model.toMap(); final result = Preferences.fromMap(map); - }); }); } diff --git a/test/src/models/presence_list_test.dart b/test/src/models/presence_list_test.dart index 57a86348..46f69af6 100644 --- a/test/src/models/presence_list_test.dart +++ b/test/src/models/presence_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = PresenceList.fromMap(map); - expect(result.total, 5); - expect(result.presences, []); - }); + expect(result.total, 5); + expect(result.presences, []); + }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index edcfe5f5..ef2ebe31 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + expect(result.userId, '674af8f3e12a5f9ac0be'); + expect(result.source, 'HTTP'); + }); }); } diff --git a/test/src/models/row_list_test.dart b/test/src/models/row_list_test.dart index d4900dd4..12693926 100644 --- a/test/src/models/row_list_test.dart +++ b/test/src/models/row_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = RowList.fromMap(map); - expect(result.total, 5); - expect(result.rows, []); - }); + expect(result.total, 5); + expect(result.rows, []); + }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 4e72a449..564bf303 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -18,13 +18,13 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$permissions, []); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$sequence, '1'); + expect(result.$tableId, '5e5ea5c15117e'); + expect(result.$databaseId, '5e5ea5c15117e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$permissions, []); + }); }); } diff --git a/test/src/models/session_list_test.dart b/test/src/models/session_list_test.dart index eaab249e..708e0583 100644 --- a/test/src/models/session_list_test.dart +++ b/test/src/models/session_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = SessionList.fromMap(map); - expect(result.total, 5); - expect(result.sessions, []); - }); + expect(result.total, 5); + expect(result.sessions, []); + }); }); } diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 0177e477..689e6048 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -39,35 +39,35 @@ void main() { final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); - expect(result.current, true); - expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5bb8c16897e'); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.provider, 'email'); + expect(result.providerUid, 'user@example.com'); + expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); + expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.ip, '127.0.0.1'); + expect(result.osCode, 'Mac'); + expect(result.osName, 'Mac'); + expect(result.osVersion, 'Mac'); + expect(result.clientType, 'browser'); + expect(result.clientCode, 'CM'); + expect(result.clientName, 'Chrome Mobile iOS'); + expect(result.clientVersion, '84.0'); + expect(result.clientEngine, 'WebKit'); + expect(result.clientEngineVersion, '605.1.15'); + expect(result.deviceName, 'smartphone'); + expect(result.deviceBrand, 'Google'); + expect(result.deviceModel, 'Nexus 5'); + expect(result.countryCode, 'US'); + expect(result.countryName, 'United States'); + expect(result.current, true); + expect(result.factors, []); + expect(result.secret, '5e5bb8c16897e'); + expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 94c6a502..7445514c 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -10,15 +10,15 @@ void main() { $updatedAt: '2020-10-15T06:38:00.000+00:00', targetId: '259125845563242502', target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', - expired: true, - ), + $id: '259125845563242502', + $createdAt: '2020-10-15T06:38:00.000+00:00', + $updatedAt: '2020-10-15T06:38:00.000+00:00', + name: 'Apple iPhone 12', + userId: '259125845563242502', + providerType: 'email', + identifier: 'token', + expired: true, + ), userId: '5e5ea5c16897e', userName: 'Aegon Targaryen', topicId: '259125845563242502', @@ -28,14 +28,14 @@ void main() { final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.targetId, '259125845563242502'); + expect(result.userId, '5e5ea5c16897e'); + expect(result.userName, 'Aegon Targaryen'); + expect(result.topicId, '259125845563242502'); + expect(result.providerType, 'email'); + }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index a49f3def..49f1e75e 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -18,14 +18,14 @@ void main() { final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); - expect(result.expired, true); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'Apple iPhone 12'); + expect(result.userId, '259125845563242502'); + expect(result.providerType, 'email'); + expect(result.identifier, 'token'); + expect(result.expired, true); + }); }); } diff --git a/test/src/models/team_list_test.dart b/test/src/models/team_list_test.dart index a19b667d..fe2f4a85 100644 --- a/test/src/models/team_list_test.dart +++ b/test/src/models/team_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TeamList.fromMap(map); - expect(result.total, 5); - expect(result.teams, []); - }); + expect(result.total, 5); + expect(result.teams, []); + }); }); } diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index 43b2e45c..f652f2c1 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -16,11 +16,11 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); - expect(result.total, 7); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'VIP'); + expect(result.total, 7); + }); }); } diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 7ee4b268..8f0957c9 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); - }); + expect(result.$id, 'bb8ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userId, '5e5ea5c168bb8'); + expect(result.secret, ''); + expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.phrase, 'Golden Fox'); + }); }); } diff --git a/test/src/models/transaction_list_test.dart b/test/src/models/transaction_list_test.dart index 68023e18..a524ef71 100644 --- a/test/src/models/transaction_list_test.dart +++ b/test/src/models/transaction_list_test.dart @@ -12,8 +12,8 @@ void main() { final map = model.toMap(); final result = TransactionList.fromMap(map); - expect(result.total, 5); - expect(result.transactions, []); - }); + expect(result.total, 5); + expect(result.transactions, []); + }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 723ebac2..0169427f 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -16,12 +16,12 @@ void main() { final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); - expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '259125845563242502'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, 'pending'); + expect(result.operations, 5); + expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index c058ea26..77c7dd97 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -26,21 +26,21 @@ void main() { final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, true); - expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); - expect(result.emailVerification, true); - expect(result.phoneVerification, true); - expect(result.mfa, true); - expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); - }); + expect(result.$id, '5e5ea5c16897e'); + expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.name, 'John Doe'); + expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); + expect(result.email, 'john@appwrite.io'); + expect(result.phone, '+4930901820'); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + }); }); } From ab4db8c97db033419bf22e7fba54c74236351a97 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 24 Aug 2026 13:47:52 +0530 Subject: [PATCH 07/17] chore: update Flutter SDK to 25.5.0 --- CHANGELOG.md | 11 + README.md | 2 +- analysis_options.yaml | 5 +- docs/examples/avatars/get-browser.md | 25 +- docs/examples/avatars/get-credit-card.md | 25 +- docs/examples/avatars/get-favicon.md | 19 +- docs/examples/avatars/get-flag.md | 25 +- docs/examples/avatars/get-image.md | 23 +- docs/examples/avatars/get-initials.md | 25 +- docs/examples/avatars/get-photo.md | 40 + docs/examples/avatars/get-qr.md | 25 +- docs/examples/avatars/get-screenshot.md | 59 +- docs/examples/storage/get-file-download.md | 23 +- docs/examples/storage/get-file-preview.md | 45 +- docs/examples/storage/get-file-view.md | 23 +- lib/enums.dart | 1 + lib/query.dart | 36 +- lib/services/account.dart | 986 +++++++---- lib/services/avatars.dart | 262 +-- lib/services/databases.dart | 448 +++-- lib/services/functions.dart | 78 +- lib/services/graphql.dart | 24 +- lib/services/locale.dart | 64 +- lib/services/messaging.dart | 47 +- lib/services/organization.dart | 88 +- lib/services/presences.dart | 112 +- lib/services/storage.dart | 240 ++- lib/services/tables_db.dart | 406 +++-- lib/services/teams.dart | 405 +++-- lib/src/client_browser.dart | 10 +- lib/src/client_io.dart | 28 +- lib/src/client_mixin.dart | 15 +- lib/src/enums/authentication_factor.dart | 9 +- lib/src/enums/authenticator_type.dart | 2 +- lib/src/enums/browser.dart | 28 +- lib/src/enums/browser_permission.dart | 40 +- lib/src/enums/browser_theme.dart | 4 +- lib/src/enums/credit_card.dart | 34 +- lib/src/enums/execution_method.dart | 14 +- lib/src/enums/execution_resource_type.dart | 12 + lib/src/enums/execution_status.dart | 10 +- lib/src/enums/execution_trigger.dart | 6 +- lib/src/enums/flag.dart | 390 ++--- lib/src/enums/image_format.dart | 14 +- lib/src/enums/image_gravity.dart | 18 +- lib/src/enums/o_auth_provider.dart | 89 +- lib/src/enums/timezone.dart | 838 +++++----- lib/src/models/algo_argon2.dart | 5 +- lib/src/models/algo_bcrypt.dart | 5 +- lib/src/models/algo_md5.dart | 5 +- lib/src/models/algo_phpass.dart | 5 +- lib/src/models/algo_scrypt.dart | 5 +- lib/src/models/algo_scrypt_modified.dart | 5 +- lib/src/models/algo_sha.dart | 5 +- lib/src/models/app_installation.dart | 9 +- lib/src/models/app_installation_list.dart | 8 +- lib/src/models/continent.dart | 5 +- lib/src/models/continent_list.dart | 8 +- lib/src/models/country.dart | 5 +- lib/src/models/country_list.dart | 10 +- lib/src/models/currency.dart | 5 +- lib/src/models/currency_list.dart | 8 +- lib/src/models/document.dart | 5 +- lib/src/models/document_list.dart | 10 +- lib/src/models/execution.dart | 49 +- lib/src/models/execution_list.dart | 8 +- lib/src/models/file.dart | 5 +- lib/src/models/file_list.dart | 9 +- lib/src/models/headers.dart | 5 +- lib/src/models/identity.dart | 5 +- lib/src/models/identity_list.dart | 8 +- lib/src/models/jwt.dart | 5 +- lib/src/models/language.dart | 5 +- lib/src/models/language_list.dart | 10 +- lib/src/models/locale.dart | 5 +- lib/src/models/locale_code.dart | 5 +- lib/src/models/locale_code_list.dart | 8 +- lib/src/models/log.dart | 5 +- lib/src/models/log_list.dart | 9 +- lib/src/models/membership.dart | 5 +- lib/src/models/membership_list.dart | 8 +- lib/src/models/mfa_challenge.dart | 5 +- lib/src/models/mfa_factors.dart | 11 +- lib/src/models/mfa_recovery_codes.dart | 5 +- lib/src/models/mfa_type.dart | 5 +- lib/src/models/oauth2_consent.dart | 5 +- lib/src/models/oauth2_consent_list.dart | 8 +- lib/src/models/oauth2_consent_token.dart | 5 +- lib/src/models/oauth2_consent_token_list.dart | 8 +- lib/src/models/phone.dart | 5 +- lib/src/models/phone_list.dart | 9 +- lib/src/models/preferences.dart | 5 +- lib/src/models/presence.dart | 5 +- lib/src/models/presence_list.dart | 10 +- lib/src/models/row.dart | 5 +- lib/src/models/row_list.dart | 9 +- lib/src/models/session.dart | 5 +- lib/src/models/session_list.dart | 10 +- lib/src/models/subscriber.dart | 9 +- lib/src/models/target.dart | 5 +- lib/src/models/team.dart | 9 +- lib/src/models/team_list.dart | 9 +- lib/src/models/token.dart | 5 +- lib/src/models/transaction.dart | 5 +- lib/src/models/transaction_list.dart | 8 +- lib/src/models/user.dart | 13 +- lib/src/realtime_response.dart | 22 +- pubspec.yaml | 9 +- test/services/account_test.dart | 1436 +++++++++-------- test/services/avatars_test.dart | 97 +- test/services/databases_test.dart | 280 ++-- test/services/functions_test.dart | 106 +- test/services/graphql_test.dart | 42 +- test/services/locale_test.dart | 90 +- test/services/messaging_test.dart | 82 +- test/services/organization_test.dart | 116 +- test/services/presences_test.dart | 100 +- test/services/storage_test.dart | 178 +- test/services/tables_db_test.dart | 280 ++-- test/services/teams_test.dart | 364 +++-- test/src/models/algo_argon2_test.dart | 4 +- test/src/models/algo_bcrypt_test.dart | 4 +- test/src/models/algo_md5_test.dart | 4 +- test/src/models/algo_phpass_test.dart | 4 +- .../src/models/algo_scrypt_modified_test.dart | 20 +- test/src/models/algo_scrypt_test.dart | 4 +- test/src/models/algo_sha_test.dart | 4 +- test/src/models/app_installation_test.dart | 32 +- test/src/models/continent_test.dart | 8 +- test/src/models/country_test.dart | 8 +- test/src/models/currency_test.dart | 20 +- test/src/models/document_test.dart | 24 +- test/src/models/execution_test.dart | 42 +- test/src/models/file_test.dart | 40 +- test/src/models/headers_test.dart | 8 +- test/src/models/identity_test.dart | 40 +- test/src/models/jwt_test.dart | 8 +- test/src/models/language_test.dart | 12 +- test/src/models/locale_code_test.dart | 8 +- test/src/models/locale_test.dart | 24 +- test/src/models/log_test.dart | 88 +- test/src/models/membership_test.dart | 48 +- test/src/models/mfa_challenge_test.dart | 16 +- test/src/models/mfa_factors_test.dart | 2 + test/src/models/mfa_type_test.dart | 12 +- test/src/models/oauth2_consent_test.dart | 40 +- .../src/models/oauth2_consent_token_test.dart | 44 +- test/src/models/phone_test.dart | 12 +- test/src/models/presence_test.dart | 20 +- test/src/models/row_test.dart | 24 +- test/src/models/session_test.dart | 108 +- test/src/models/subscriber_test.dart | 46 +- test/src/models/target_test.dart | 28 +- test/src/models/team_test.dart | 16 +- test/src/models/token_test.dart | 24 +- test/src/models/transaction_test.dart | 20 +- test/src/models/user_test.dart | 36 +- 157 files changed, 5628 insertions(+), 4049 deletions(-) create mode 100644 docs/examples/avatars/get-photo.md create mode 100644 lib/src/enums/execution_resource_type.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 99ca59f2..e34f7506 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change Log +## 25.5.0 + +* Added: `avatars.getPhoto` returning the user's best available profile photo +* Added: `huggingface` OAuth provider +* Added: `custom` authentication factor +* Added: `ExecutionResourceType` enum and `resourceType` attribute on the `Execution` model +* Fixed: OAuth2 failures now surface the error returned in the callback URL +* Fixed: empty JSON error responses no longer throw `FormatException` +* Updated: relaxed `device_info_plus` to `<14.0.0` and `package_info_plus` to `<11.0.0` +* Updated: minimum Dart SDK is now 3.7.0 and minimum Flutter 3.29.0 + ## 25.4.0 * Added: `Organization` service for managing app installations diff --git a/README.md b/README.md index d65b5309..5705a6cf 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^25.4.0 + appwrite: ^25.5.0 ``` You can install packages from the command line: diff --git a/analysis_options.yaml b/analysis_options.yaml index a3be6b82..85ac0167 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1 +1,4 @@ -include: package:flutter_lints/flutter.yaml \ No newline at end of file +include: package:flutter_lints/flutter.yaml + +formatter: + trailing_commas: preserve diff --git a/docs/examples/avatars/get-browser.md b/docs/examples/avatars/get-browser.md index 19026083..91cd7be6 100644 --- a/docs/examples/avatars/get-browser.md +++ b/docs/examples/avatars/get-browser.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/enums.dart' as enums; @@ -14,23 +17,23 @@ Uint8List bytes = await avatars.getBrowser( width: 0, // optional height: 0, // optional quality: -1, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getBrowser( - code: enums.Browser.avantBrowser, - width:0 , // optional - height:0 , // optional - quality:-1 , // optional -), // Works for both public file and private file, for private files you need to be logged in + code: enums.Browser.avantBrowser, + width: 0, // optional + height: 0, // optional + quality: -1, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-credit-card.md b/docs/examples/avatars/get-credit-card.md index 395608a4..4665fcce 100644 --- a/docs/examples/avatars/get-credit-card.md +++ b/docs/examples/avatars/get-credit-card.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/enums.dart' as enums; @@ -14,23 +17,23 @@ Uint8List bytes = await avatars.getCreditCard( width: 0, // optional height: 0, // optional quality: -1, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getCreditCard( - code: enums.CreditCard.americanExpress, - width:0 , // optional - height:0 , // optional - quality:-1 , // optional -), // Works for both public file and private file, for private files you need to be logged in + code: enums.CreditCard.americanExpress, + width: 0, // optional + height: 0, // optional + quality: -1, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-favicon.md b/docs/examples/avatars/get-favicon.md index fd1d0df7..5f523f81 100644 --- a/docs/examples/avatars/get-favicon.md +++ b/docs/examples/avatars/get-favicon.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -10,20 +13,20 @@ Avatars avatars = Avatars(client); // Downloading file Uint8List bytes = await avatars.getFavicon( url: 'https://example.com', -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getFavicon( - url:'https://example.com' , -), // Works for both public file and private file, for private files you need to be logged in + url: 'https://example.com', + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-flag.md b/docs/examples/avatars/get-flag.md index a5753f6c..552c22cc 100644 --- a/docs/examples/avatars/get-flag.md +++ b/docs/examples/avatars/get-flag.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/enums.dart' as enums; @@ -14,23 +17,23 @@ Uint8List bytes = await avatars.getFlag( width: 0, // optional height: 0, // optional quality: -1, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getFlag( - code: enums.Flag.afghanistan, - width:0 , // optional - height:0 , // optional - quality:-1 , // optional -), // Works for both public file and private file, for private files you need to be logged in + code: enums.Flag.afghanistan, + width: 0, // optional + height: 0, // optional + quality: -1, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-image.md b/docs/examples/avatars/get-image.md index 4e75bc7e..3f74cae0 100644 --- a/docs/examples/avatars/get-image.md +++ b/docs/examples/avatars/get-image.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -12,22 +15,22 @@ Uint8List bytes = await avatars.getImage( url: 'https://example.com', width: 0, // optional height: 0, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getImage( - url:'https://example.com' , - width:0 , // optional - height:0 , // optional -), // Works for both public file and private file, for private files you need to be logged in + url: 'https://example.com', + width: 0, // optional + height: 0, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index 3b5bb68e..c832a1c8 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -13,23 +16,23 @@ Uint8List bytes = await avatars.getInitials( width: 0, // optional height: 0, // optional background: '', // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getInitials( - name:'' , // optional - width:0 , // optional - height:0 , // optional - background:'' , // optional -), // Works for both public file and private file, for private files you need to be logged in + name: '', // optional + width: 0, // optional + height: 0, // optional + background: '', // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-photo.md b/docs/examples/avatars/get-photo.md new file mode 100644 index 00000000..d9baf564 --- /dev/null +++ b/docs/examples/avatars/get-photo.md @@ -0,0 +1,40 @@ +```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +// Downloading file +Uint8List bytes = await avatars.getPhoto( + width: 0, // optional + height: 0, // optional + quality: 0, // optional + output: 'png', // optional + rating: 'g', // optional +); + +final file = File('path_to_file/filename.ext'); +file.writeAsBytesSync(bytes); + +// Displaying image preview +FutureBuilder( + future: avatars.getPhoto( + width: 0, // optional + height: 0, // optional + quality: 0, // optional + output: 'png', // optional + rating: 'g', // optional + ), // 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!) + : const CircularProgressIndicator(); + }, +); +``` diff --git a/docs/examples/avatars/get-qr.md b/docs/examples/avatars/get-qr.md index 8a6dc770..3579f431 100644 --- a/docs/examples/avatars/get-qr.md +++ b/docs/examples/avatars/get-qr.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -13,23 +16,23 @@ Uint8List bytes = await avatars.getQR( size: 1, // optional margin: 0, // optional download: false, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getQR( - text:'' , - size:1 , // optional - margin:0 , // optional - download:false , // optional -), // Works for both public file and private file, for private files you need to be logged in + text: '', + size: 1, // optional + margin: 0, // optional + download: false, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/avatars/get-screenshot.md b/docs/examples/avatars/get-screenshot.md index 7de27d7b..daa38d17 100644 --- a/docs/examples/avatars/get-screenshot.md +++ b/docs/examples/avatars/get-screenshot.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/enums.dart' as enums; @@ -33,42 +36,42 @@ Uint8List bytes = await avatars.getScreenshot( height: 600, // optional quality: 85, // optional output: enums.ImageFormat.jpeg, // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: avatars.getScreenshot( - url:'https://example.com' , - headers:{ + url: 'https://example.com', + headers: { "Authorization": "Bearer token123", "X-Custom-Header": "value" - } , // optional - viewportWidth:1920 , // optional - viewportHeight:1080 , // optional - scale:2 , // optional - theme: enums.BrowserTheme.dark, // optional - userAgent:'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15' , // optional - fullpage:true , // optional - locale:'en-US' , // optional - timezone: enums.Timezone.africaAbidjan, // optional - latitude:37.7749 , // optional - longitude:-122.4194 , // optional - accuracy:100 , // optional - touch:true , // optional - permissions: [enums.BrowserPermission.geolocation, enums.BrowserPermission.notifications], // optional - sleep:3 , // optional - width:800 , // optional - height:600 , // optional - quality:85 , // optional - output: enums.ImageFormat.jpeg, // optional -), // Works for both public file and private file, for private files you need to be logged in + }, // optional + viewportWidth: 1920, // optional + viewportHeight: 1080, // optional + scale: 2, // optional + theme: enums.BrowserTheme.dark, // optional + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15', // optional + fullpage: true, // optional + locale: 'en-US', // optional + timezone: enums.Timezone.africaAbidjan, // optional + latitude: 37.7749, // optional + longitude: -122.4194, // optional + accuracy: 100, // optional + touch: true, // optional + permissions: [enums.BrowserPermission.geolocation, enums.BrowserPermission.notifications], // optional + sleep: 3, // optional + width: 800, // optional + height: 600, // optional + quality: 85, // optional + output: enums.ImageFormat.jpeg, // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/storage/get-file-download.md b/docs/examples/storage/get-file-download.md index 8fc48d15..8e6e75ef 100644 --- a/docs/examples/storage/get-file-download.md +++ b/docs/examples/storage/get-file-download.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -12,22 +15,22 @@ Uint8List bytes = await storage.getFileDownload( bucketId: '', fileId: '', token: '', // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: storage.getFileDownload( - bucketId:'' , - fileId:'' , - token:'' , // optional -), // Works for both public file and private file, for private files you need to be logged in + bucketId: '', + fileId: '', + token: '', // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 06e583a3..bfb15b91 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/enums.dart' as enums; @@ -24,33 +27,33 @@ Uint8List bytes = await storage.getFilePreview( background: '', // optional output: enums.ImageFormat.jpg, // optional token: '', // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: storage.getFilePreview( - bucketId:'' , - fileId:'' , - width:0 , // optional - height:0 , // optional - gravity: enums.ImageGravity.center, // optional - quality:-1 , // optional - borderWidth:0 , // optional - borderColor:'' , // optional - borderRadius:0 , // optional - opacity:0 , // optional - rotation:-360 , // optional - background:'' , // optional - output: enums.ImageFormat.jpg, // optional - token:'' , // optional -), // Works for both public file and private file, for private files you need to be logged in + bucketId: '', + fileId: '', + width: 0, // optional + height: 0, // optional + gravity: enums.ImageGravity.center, // optional + quality: -1, // optional + borderWidth: 0, // optional + borderColor: '', // optional + borderRadius: 0, // optional + opacity: 0, // optional + rotation: -360, // optional + background: '', // optional + output: enums.ImageFormat.jpg, // optional + token: '', // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/docs/examples/storage/get-file-view.md b/docs/examples/storage/get-file-view.md index 56d2652d..6cc01b65 100644 --- a/docs/examples/storage/get-file-view.md +++ b/docs/examples/storage/get-file-view.md @@ -1,4 +1,7 @@ ```dart +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; import 'package:appwrite/appwrite.dart'; Client client = Client() @@ -12,22 +15,22 @@ Uint8List bytes = await storage.getFileView( bucketId: '', fileId: '', token: '', // optional -) +); final file = File('path_to_file/filename.ext'); file.writeAsBytesSync(bytes); // Displaying image preview -FutureBuilder( +FutureBuilder( future: storage.getFileView( - bucketId:'' , - fileId:'' , - token:'' , // optional -), // Works for both public file and private file, for private files you need to be logged in + bucketId: '', + fileId: '', + token: '', // optional + ), // 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(); - } + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data!) + : const CircularProgressIndicator(); + }, ); ``` diff --git a/lib/enums.dart b/lib/enums.dart index f9b21727..a9677f03 100644 --- a/lib/enums.dart +++ b/lib/enums.dart @@ -13,5 +13,6 @@ part 'src/enums/browser_permission.dart'; part 'src/enums/image_format.dart'; part 'src/enums/execution_method.dart'; part 'src/enums/image_gravity.dart'; +part 'src/enums/execution_resource_type.dart'; part 'src/enums/execution_trigger.dart'; part 'src/enums/execution_status.dart'; diff --git a/lib/query.dart b/lib/query.dart index 2772116a..1ad97bdc 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -222,34 +222,46 @@ class Query { /// Filter resources where [attribute] is at a specific distance from the given coordinates. static String distanceEqual( - String attribute, List values, num distance, - [bool meters = true]) => + String attribute, + List values, + num distance, [ + bool meters = true, + ]) => Query._('distanceEqual', attribute, [ - [values, distance, meters] + [values, distance, meters], ]).toString(); /// Filter resources where [attribute] is not at a specific distance from the given coordinates. static String distanceNotEqual( - String attribute, List values, num distance, - [bool meters = true]) => + String attribute, + List values, + num distance, [ + bool meters = true, + ]) => Query._('distanceNotEqual', attribute, [ - [values, distance, meters] + [values, distance, meters], ]).toString(); /// Filter resources where [attribute] is at a distance greater than the specified value from the given coordinates. static String distanceGreaterThan( - String attribute, List values, num distance, - [bool meters = true]) => + String attribute, + List values, + num distance, [ + bool meters = true, + ]) => Query._('distanceGreaterThan', attribute, [ - [values, distance, meters] + [values, distance, meters], ]).toString(); /// Filter resources where [attribute] is at a distance less than the specified value from the given coordinates. static String distanceLessThan( - String attribute, List values, num distance, - [bool meters = true]) => + String attribute, + List values, + num distance, [ + bool meters = true, + ]) => Query._('distanceLessThan', attribute, [ - [values, distance, meters] + [values, distance, meters], ]).toString(); /// Filter resources using vector dot product similarity. diff --git a/lib/services/account.dart b/lib/services/account.dart index 3b8fbded..41a32f4a 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -16,8 +16,12 @@ class Account extends Service { 'accept': '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.User.fromMap(res.data); } @@ -29,11 +33,12 @@ class Account extends Service { /// 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 { + Future create({ + required String userId, + required String email, + required String password, + String? name, + }) async { final String apiPath = '/account'; final Map apiParams = { @@ -49,16 +54,22 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } /// Get a list of the OAuth2 consents the current user has given to third-party /// apps. - Future listConsents( - {List? queries, bool? total}) async { + Future listConsents({ + List? queries, + bool? total, + }) async { final String apiPath = '/account/consents'; final Map apiParams = { @@ -71,17 +82,25 @@ class Account extends Service { 'accept': '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.Oauth2ConsentList.fromMap(res.data); } /// Get an OAuth2 consent the current user has given to a third-party app by /// its unique ID. - Future getConsent({required String consentId}) async { - final String apiPath = - '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); + Future getConsent({ + required String consentId, + }) async { + final String apiPath = '/account/consents/{consentId}'.replaceAll( + '{consentId}', + consentId, + ); final Map apiParams = {}; @@ -90,8 +109,12 @@ class Account extends Service { 'accept': '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.Oauth2Consent.fromMap(res.data); } @@ -99,9 +122,13 @@ class Account extends Service { /// Delete an OAuth2 consent by its unique ID. All token families issued under /// the consent are revoked, and the app must ask for consent again to regain /// access. - Future deleteConsent({required String consentId}) async { - final String apiPath = - '/account/consents/{consentId}'.replaceAll('{consentId}', consentId); + Future deleteConsent({ + required String consentId, + }) async { + final String apiPath = '/account/consents/{consentId}'.replaceAll( + '{consentId}', + consentId, + ); final Map apiParams = {}; @@ -111,8 +138,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -120,10 +151,15 @@ class Account extends Service { /// Get a list of the token families issued under an OAuth2 consent. Each entry /// represents one authorized device or session; the token secrets themselves /// are never returned. - Future listConsentTokens( - {required String consentId, List? queries, bool? total}) async { - final String apiPath = '/account/consents/{consentId}/tokens' - .replaceAll('{consentId}', consentId); + Future listConsentTokens({ + required String consentId, + List? queries, + bool? total, + }) async { + final String apiPath = '/account/consents/{consentId}/tokens'.replaceAll( + '{consentId}', + consentId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -135,19 +171,31 @@ class Account extends Service { 'accept': '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.Oauth2ConsentTokenList.fromMap(res.data); } /// Get a token family issued under an OAuth2 consent by its unique ID. The /// token secrets themselves are never returned. - Future getConsentToken( - {required String consentId, required String tokenId}) async { + Future getConsentToken({ + required String consentId, + required String tokenId, + }) async { final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' - .replaceAll('{consentId}', consentId) - .replaceAll('{tokenId}', tokenId); + .replaceAll( + '{consentId}', + consentId, + ) + .replaceAll( + '{tokenId}', + tokenId, + ); final Map apiParams = {}; @@ -156,8 +204,12 @@ class Account extends Service { 'accept': '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.Oauth2ConsentToken.fromMap(res.data); } @@ -165,11 +217,19 @@ class Account extends Service { /// Delete a token family issued under an OAuth2 consent by its unique ID. The /// access and refresh tokens of the family stop working immediately; other /// token families and the consent itself are unaffected. - Future deleteConsentToken( - {required String consentId, required String tokenId}) async { + Future deleteConsentToken({ + required String consentId, + required String tokenId, + }) async { final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' - .replaceAll('{consentId}', consentId) - .replaceAll('{tokenId}', tokenId); + .replaceAll( + '{consentId}', + consentId, + ) + .replaceAll( + '{tokenId}', + tokenId, + ); final Map apiParams = {}; @@ -179,8 +239,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -192,9 +256,10 @@ class Account extends Service { /// 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 { + Future updateEmail({ + required String email, + required String password, + }) async { final String apiPath = '/account/email'; final Map apiParams = { @@ -208,15 +273,21 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } /// Get the list of identities for the currently logged in user. - Future listIdentities( - {List? queries, bool? total}) async { + Future listIdentities({ + List? queries, + bool? total, + }) async { final String apiPath = '/account/identities'; final Map apiParams = { @@ -229,16 +300,24 @@ class Account extends Service { 'accept': '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.IdentityList.fromMap(res.data); } /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); + Future deleteIdentity({ + required String identityId, + }) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll( + '{identityId}', + identityId, + ); final Map apiParams = {}; @@ -247,8 +326,12 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -258,7 +341,9 @@ class Account extends Service { /// 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({int? duration}) async { + Future createJWT({ + int? duration, + }) async { final String apiPath = '/account/jwts'; final Map apiParams = { @@ -271,15 +356,22 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Jwt.fromMap(res.data); } /// 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, bool? total}) async { + Future listLogs({ + List? queries, + bool? total, + }) async { final String apiPath = '/account/logs'; final Map apiParams = { @@ -292,14 +384,20 @@ class Account extends Service { 'accept': '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.LogList.fromMap(res.data); } /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { + Future updateMFA({ + required bool mfa, + }) async { final String apiPath = '/account/mfa'; final Map apiParams = { @@ -312,8 +410,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -323,11 +425,15 @@ class Account extends Service { /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) /// method. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.') - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.', + ) + Future createMfaAuthenticator({ + required enums.AuthenticatorType type, + }) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll( + '{type}', + type.value, + ); final Map apiParams = {}; @@ -337,8 +443,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaType.fromMap(res.data); } @@ -347,10 +457,13 @@ class Account extends Service { /// 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); + Future createMFAAuthenticator({ + required enums.AuthenticatorType type, + }) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll( + '{type}', + type.value, + ); final Map apiParams = {}; @@ -360,8 +473,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaType.fromMap(res.data); } @@ -370,11 +487,16 @@ class Account extends Service { /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) /// method. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.') - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.', + ) + 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, @@ -386,8 +508,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -395,10 +521,14 @@ class Account extends Service { /// 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); + 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, @@ -410,18 +540,27 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } /// Delete an authenticator for a user by ID. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.') - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + 'This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.', + ) + Future deleteMfaAuthenticator({ + required enums.AuthenticatorType type, + }) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll( + '{type}', + type.value, + ); final Map apiParams = {}; @@ -430,16 +569,24 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// 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); + Future deleteMFAAuthenticator({ + required enums.AuthenticatorType type, + }) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll( + '{type}', + type.value, + ); final Map apiParams = {}; @@ -448,8 +595,12 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -458,9 +609,11 @@ class Account extends Service { /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) /// method. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.') - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { + 'This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.', + ) + Future createMfaChallenge({ + required enums.AuthenticationFactor factor, + }) async { final String apiPath = '/account/mfa/challenges'; final Map apiParams = { @@ -473,8 +626,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaChallenge.fromMap(res.data); } @@ -482,8 +639,9 @@ class Account extends Service { /// 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 { + Future createMFAChallenge({ + required enums.AuthenticationFactor factor, + }) async { final String apiPath = '/account/mfa/challenges'; final Map apiParams = { @@ -496,8 +654,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaChallenge.fromMap(res.data); } @@ -508,9 +670,12 @@ class Account extends Service { /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.') - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.', + ) + Future updateMfaChallenge({ + required String challengeId, + required String otp, + }) async { final String apiPath = '/account/mfa/challenges'; final Map apiParams = { @@ -524,8 +689,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -535,8 +704,10 @@ class Account extends Service { /// the flow, use /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. - Future updateMFAChallenge( - {required String challengeId, required String otp}) async { + Future updateMFAChallenge({ + required String challengeId, + required String otp, + }) async { final String apiPath = '/account/mfa/challenges'; final Map apiParams = { @@ -550,15 +721,20 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } /// List the factors available on the account to be used as a MFA challange. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.') + 'This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.', + ) Future listMfaFactors() async { final String apiPath = '/account/mfa/factors'; @@ -569,8 +745,12 @@ class Account extends Service { 'accept': '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.MfaFactors.fromMap(res.data); } @@ -586,8 +766,12 @@ class Account extends Service { 'accept': '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.MfaFactors.fromMap(res.data); } @@ -597,7 +781,8 @@ class Account extends Service { /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) /// method. An OTP challenge is required to read recovery codes. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.') + 'This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.', + ) Future getMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; @@ -608,8 +793,12 @@ class Account extends Service { 'accept': '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.MfaRecoveryCodes.fromMap(res.data); } @@ -628,8 +817,12 @@ class Account extends Service { 'accept': '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.MfaRecoveryCodes.fromMap(res.data); } @@ -640,7 +833,8 @@ class Account extends Service { /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) /// method. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.') + 'This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.', + ) Future createMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; @@ -652,8 +846,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaRecoveryCodes.fromMap(res.data); } @@ -674,8 +872,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaRecoveryCodes.fromMap(res.data); } @@ -685,7 +887,8 @@ class Account extends Service { /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) /// method. An OTP challenge is required to regenreate recovery codes. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.') + 'This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.', + ) Future updateMfaRecoveryCodes() async { final String apiPath = '/account/mfa/recovery-codes'; @@ -697,8 +900,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaRecoveryCodes.fromMap(res.data); } @@ -718,14 +925,20 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.MfaRecoveryCodes.fromMap(res.data); } /// Update currently logged in user account name. - Future updateName({required String name}) async { + Future updateName({ + required String name, + }) async { final String apiPath = '/account/name'; final Map apiParams = { @@ -738,8 +951,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -747,8 +964,10 @@ class Account extends Service { /// 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 { + Future updatePassword({ + required String password, + String? oldPassword, + }) async { final String apiPath = '/account/password'; final Map apiParams = { @@ -762,8 +981,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -773,8 +996,10 @@ class Account extends Service { /// 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 { + Future updatePhone({ + required String phone, + required String password, + }) async { final String apiPath = '/account/phone'; final Map apiParams = { @@ -788,8 +1013,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -805,8 +1034,12 @@ class Account extends Service { 'accept': '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.Preferences.fromMap(res.data); } @@ -814,7 +1047,9 @@ class Account extends Service { /// 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 { + Future updatePrefs({ + required Map prefs, + }) async { final String apiPath = '/account/prefs'; final Map apiParams = { @@ -827,8 +1062,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -841,8 +1080,10 @@ class Account extends Service { /// /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 { + Future createRecovery({ + required String email, + required String url, + }) async { final String apiPath = '/account/recovery'; final Map apiParams = { @@ -856,8 +1097,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -872,10 +1117,11 @@ class Account extends Service { /// 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 { + Future updateRecovery({ + required String userId, + required String secret, + required String password, + }) async { final String apiPath = '/account/recovery'; final Map apiParams = { @@ -890,8 +1136,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -908,8 +1158,12 @@ class Account extends Service { 'accept': '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.SessionList.fromMap(res.data); } @@ -926,8 +1180,12 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -950,8 +1208,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -962,8 +1224,10 @@ class Account extends Service { /// A user 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 { + Future createEmailPasswordSession({ + required String email, + required String password, + }) async { final String apiPath = '/account/sessions/email'; final Map apiParams = { @@ -977,8 +1241,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -987,9 +1255,12 @@ class Account extends Service { /// and **secret** parameters from the successful response of authentication /// flows initiated by token creation. For example, magic URL and phone login. @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updateMagicURLSession( - {required String userId, required String secret}) async { + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.', + ) + Future updateMagicURLSession({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/sessions/magic-url'; final Map apiParams = { @@ -1003,8 +1274,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -1024,14 +1299,16 @@ class Account extends Service { /// A user 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); + 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 = { if (success != null) 'success': success, @@ -1046,20 +1323,22 @@ class Account extends Service { if (value is List) { for (var item in value) { query.add( - '${Uri.encodeComponent('$key[]')}=${Uri.encodeComponent(item)}'); + '${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('&')); + final Uri endpoint = Uri.parse(client.endPoint); + final 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); } @@ -1068,9 +1347,12 @@ class Account extends Service { /// and **secret** parameters from the successful response of authentication /// flows initiated by token creation. For example, magic URL and phone login. @Deprecated( - 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.') - Future updatePhoneSession( - {required String userId, required String secret}) async { + 'This API has been deprecated since 1.6.0. Please use `Account.createSession` instead.', + ) + Future updatePhoneSession({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/sessions/phone'; final Map apiParams = { @@ -1084,8 +1366,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -1093,8 +1379,10 @@ class Account extends Service { /// 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 { + Future createSession({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/sessions/token'; final Map apiParams = { @@ -1108,17 +1396,25 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } /// 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); + Future getSession({ + required String sessionId, + }) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( + '{sessionId}', + sessionId, + ); final Map apiParams = {}; @@ -1127,8 +1423,12 @@ class Account extends Service { 'accept': '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.Session.fromMap(res.data); } @@ -1136,9 +1436,13 @@ class Account extends Service { /// 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); + Future updateSession({ + required String sessionId, + }) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( + '{sessionId}', + sessionId, + ); final Map apiParams = {}; @@ -1148,8 +1452,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Session.fromMap(res.data); } @@ -1159,9 +1467,13 @@ class Account extends Service { /// 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); + Future deleteSession({ + required String sessionId, + }) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( + '{sessionId}', + sessionId, + ); final Map apiParams = {}; @@ -1170,8 +1482,12 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -1190,8 +1506,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.User.fromMap(res.data); } @@ -1201,10 +1521,11 @@ class Account extends Service { /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the /// current session and includes device information like brand and model. - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { + Future createPushTarget({ + required String targetId, + required String identifier, + String? providerId, + }) async { final String apiPath = '/account/targets/push'; final Map apiParams = { @@ -1219,8 +1540,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Target.fromMap(res.data); } @@ -1230,10 +1555,14 @@ class Account extends Service { /// email, phone etc.). The target must exist and belong to the current user. /// If you change the provider ID, notifications will be sent through the new /// messaging provider instead. - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + Future updatePushTarget({ + required String targetId, + required String identifier, + }) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll( + '{targetId}', + targetId, + ); final Map apiParams = { 'identifier': identifier, @@ -1245,8 +1574,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Target.fromMap(res.data); } @@ -1254,9 +1587,13 @@ class Account extends Service { /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target /// must exist and belong to the current user. - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + Future deletePushTarget({ + required String targetId, + }) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll( + '{targetId}', + targetId, + ); final Map apiParams = {}; @@ -1265,8 +1602,12 @@ class Account extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -1284,9 +1625,11 @@ class Account extends Service { /// A user 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 { + Future createEmailToken({ + required String userId, + required String email, + bool? phrase, + }) async { final String apiPath = '/account/tokens/email'; final Map apiParams = { @@ -1301,8 +1644,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1320,12 +1667,12 @@ class Account extends Service { /// A user 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 { + Future createMagicURLToken({ + required String userId, + required String email, + String? url, + bool? phrase, + }) async { final String apiPath = '/account/tokens/magic-url'; final Map apiParams = { @@ -1341,8 +1688,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1361,13 +1712,16 @@ class Account extends Service { /// A user 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); + 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 = { if (success != null) 'success': success, @@ -1382,20 +1736,22 @@ class Account extends Service { if (value is List) { for (var item in value) { query.add( - '${Uri.encodeComponent('$key[]')}=${Uri.encodeComponent(item)}'); + '${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('&')); + final Uri endpoint = Uri.parse(client.endPoint); + final 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); } @@ -1410,8 +1766,10 @@ class Account extends Service { /// A user 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 { + Future createPhoneToken({ + required String userId, + required String phone, + }) async { final String apiPath = '/account/tokens/phone'; final Map apiParams = { @@ -1425,8 +1783,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1445,8 +1807,9 @@ class Account extends Service { /// 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 createEmailVerification({required String url}) async { + Future createEmailVerification({ + required String url, + }) async { final String apiPath = '/account/verifications/email'; final Map apiParams = { @@ -1459,8 +1822,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1479,10 +1846,12 @@ class Account extends Service { /// 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. - /// @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.') - Future createVerification({required String url}) async { + 'This API has been deprecated since 1.8.0. Please use `Account.createEmailVerification` instead.', + ) + Future createVerification({ + required String url, + }) async { final String apiPath = '/account/verifications/email'; final Map apiParams = { @@ -1495,8 +1864,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1505,8 +1878,10 @@ class Account extends Service { /// 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 updateEmailVerification( - {required String userId, required String secret}) async { + Future updateEmailVerification({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/verifications/email'; final Map apiParams = { @@ -1520,8 +1895,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1531,9 +1910,12 @@ class Account extends Service { /// to verify the user email ownership. If confirmed this route will return a /// 200 status code. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.') - Future updateVerification( - {required String userId, required String secret}) async { + 'This API has been deprecated since 1.8.0. Please use `Account.updateEmailVerification` instead.', + ) + Future updateVerification({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/verifications/email'; final Map apiParams = { @@ -1547,8 +1929,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1572,8 +1958,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Token.fromMap(res.data); } @@ -1582,8 +1972,10 @@ class Account extends Service { /// **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 { + Future updatePhoneVerification({ + required String userId, + required String secret, + }) async { final String apiPath = '/account/verifications/phone'; final Map apiParams = { @@ -1597,8 +1989,12 @@ class Account extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + 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 2fe54e87..ba09d21e 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -16,13 +16,16 @@ class Avatars extends Service { /// with preserved aspect ratio. If 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); + 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 apiParams = { if (width != null) 'width': width, @@ -35,11 +38,13 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -51,14 +56,16 @@ class Avatars extends Service { /// with preserved aspect ratio. If 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); + 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 apiParams = { if (width != null) 'width': width, @@ -71,11 +78,13 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -83,7 +92,9 @@ class Avatars extends Service { /// website URL. /// /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { + Future getFavicon({ + required String url, + }) async { final String apiPath = '/avatars/favicon'; final Map apiParams = { @@ -95,11 +106,13 @@ class Avatars extends Service { 'accept': 'image/*', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -112,11 +125,16 @@ class Avatars extends Service { /// with preserved aspect ratio. If 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); + 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 apiParams = { if (width != null) 'width': width, @@ -129,11 +147,13 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -148,8 +168,11 @@ class Avatars extends Service { /// of image returned is 400x400px. /// /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { + Future getImage({ + required String url, + int? width, + int? height, + }) async { final String apiPath = '/avatars/image'; final Map apiParams = { @@ -163,11 +186,13 @@ class Avatars extends Service { 'accept': 'image/*', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -186,9 +211,12 @@ class Avatars extends Service { /// with preserved aspect ratio. If 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 { + Future getInitials({ + String? name, + int? width, + int? height, + String? background, + }) async { final String apiPath = '/avatars/initials'; final Map apiParams = { @@ -203,19 +231,60 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); + return res.data; + } + + /// Returns the best available profile photo for the currently authenticated + /// user. The endpoint tries each source in priority order and returns the + /// first successful result: Gravatar, Libavatar, Appwrite Initials, built-in + /// static fallback file. + Future getPhoto({ + int? width, + int? height, + int? quality, + String? output, + String? rating, + }) async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = { + if (width != null) 'width': width, + if (height != null) 'height': height, + if (quality != null) 'quality': quality, + if (output != null) 'output': output, + if (rating != null) 'rating': rating, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'image/*', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } /// 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 { + Future getQR({ + required String text, + int? size, + int? margin, + bool? download, + }) async { final String apiPath = '/avatars/qr'; final Map apiParams = { @@ -230,11 +299,13 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -248,27 +319,28 @@ class Avatars extends Service { /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. - Future getScreenshot( - {required String url, - Map? headers, - int? viewportWidth, - int? viewportHeight, - double? scale, - enums.BrowserTheme? theme, - String? userAgent, - bool? fullpage, - String? locale, - enums.Timezone? timezone, - double? latitude, - double? longitude, - double? accuracy, - bool? touch, - List? permissions, - int? sleep, - int? width, - int? height, - int? quality, - enums.ImageFormat? output}) async { + Future getScreenshot({ + required String url, + Map? headers, + int? viewportWidth, + int? viewportHeight, + double? scale, + enums.BrowserTheme? theme, + String? userAgent, + bool? fullpage, + String? locale, + enums.Timezone? timezone, + double? latitude, + double? longitude, + double? accuracy, + bool? touch, + List? permissions, + int? sleep, + int? width, + int? height, + int? quality, + enums.ImageFormat? output, + }) async { final String apiPath = '/avatars/screenshots'; final Map apiParams = { @@ -277,22 +349,22 @@ class Avatars extends Service { if (viewportWidth != null) 'viewportWidth': viewportWidth, if (viewportHeight != null) 'viewportHeight': viewportHeight, if (scale != null) 'scale': scale, - if (theme != null) 'theme': theme.value, + if (theme != null) 'theme': theme?.value, if (userAgent != null) 'userAgent': userAgent, if (fullpage != null) 'fullpage': fullpage, if (locale != null) 'locale': locale, - if (timezone != null) 'timezone': timezone.value, + if (timezone != null) 'timezone': timezone?.value, if (latitude != null) 'latitude': latitude, if (longitude != null) 'longitude': longitude, if (accuracy != null) 'accuracy': accuracy, if (touch != null) 'touch': touch, if (permissions != null) - 'permissions': permissions.map((e) => e.value).toList(), + 'permissions': permissions?.map((e) => e.value).toList(), if (sleep != null) 'sleep': sleep, if (width != null) 'width': width, if (height != null) 'height': height, if (quality != null) 'quality': quality, - if (output != null) 'output': output.value, + if (output != null) 'output': output?.value, }; final Map apiHeaders = { @@ -300,11 +372,13 @@ class Avatars extends Service { 'accept': 'image/png', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } } diff --git a/lib/services/databases.dart b/lib/services/databases.dart index d298cec0..aaa74ff5 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -8,9 +8,11 @@ class Databases extends Service { /// List transactions across all databases. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.') - Future listTransactions( - {List? queries}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listTransactions` instead.', + ) + Future listTransactions({ + List? queries, + }) async { final String apiPath = '/databases/transactions'; final Map apiParams = { @@ -22,16 +24,23 @@ class Databases extends Service { 'accept': '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.TransactionList.fromMap(res.data); } /// Create a new transaction. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.') - Future createTransaction({int? ttl}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createTransaction` instead.', + ) + Future createTransaction({ + int? ttl, + }) async { final String apiPath = '/databases/transactions'; final Map apiParams = { @@ -44,19 +53,27 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.') - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getTransaction` instead.', + ) + Future getTransaction({ + required String transactionId, + }) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -65,19 +82,29 @@ class Databases extends Service { 'accept': '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.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.') - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateTransaction` instead.', + ) + Future updateTransaction({ + required String transactionId, + bool? commit, + bool? rollback, + }) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (commit != null) 'commit': commit, @@ -90,18 +117,27 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.') - Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/databases/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteTransaction` instead.', + ) + Future deleteTransaction({ + required String transactionId, + }) async { + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -110,19 +146,29 @@ class Databases extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// Create multiple operations in a single transaction. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.') - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.', + ) + Future createOperations({ + required String transactionId, + List? operations, + }) async { + final String apiPath = + '/databases/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, @@ -134,8 +180,12 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } @@ -143,18 +193,26 @@ class Databases extends Service { /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.') - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.', + ) + Future listDocuments({ + required String databaseId, + required String collectionId, + List? queries, + String? transactionId, + bool? total, + int? ttl, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -168,8 +226,12 @@ class Databases extends Service { 'accept': '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.DocumentList.fromMap(res.data); } @@ -179,18 +241,26 @@ class Databases extends Service { /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) /// API or directly from your database console. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.') - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.', + ) + Future createDocument({ + required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); final Map apiParams = { 'documentId': documentId, @@ -205,8 +275,12 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Document.fromMap(res.data); } @@ -214,18 +288,29 @@ class Databases extends Service { /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.') - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.', + ) + Future getDocument({ + required String databaseId, + required String collectionId, + required String documentId, + List? queries, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -237,8 +322,12 @@ class Databases extends Service { 'accept': '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.Document.fromMap(res.data); } @@ -248,19 +337,30 @@ class Databases extends Service { /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) /// API or directly from your database console. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.') - Future upsertDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.', + ) + Future upsertDocument({ + required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); final Map apiParams = { if (data != null) 'data': data, @@ -274,8 +374,12 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Document.fromMap(res.data); } @@ -283,19 +387,30 @@ class Databases extends Service { /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.') - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.', + ) + Future updateDocument({ + required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); final Map apiParams = { if (data != null) 'data': data, @@ -309,25 +424,40 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Document.fromMap(res.data); } /// Delete a document by its unique ID. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.') - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.', + ) + Future deleteDocument({ + required String databaseId, + required String collectionId, + required String documentId, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); final Map apiParams = { if (transactionId != null) 'transactionId': transactionId, @@ -338,29 +468,47 @@ class Databases extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// Decrement a specific attribute of a document by a given value. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.') - Future decrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? min, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.', + ) + Future decrementDocumentAttribute({ + required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? min, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ) + .replaceAll( + '{attribute}', + attribute, + ); final Map apiParams = { if (value != null) 'value': value, @@ -374,29 +522,47 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Document.fromMap(res.data); } /// Increment a specific attribute of a document by a given value. @Deprecated( - 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.') - Future incrementDocumentAttribute( - {required String databaseId, - required String collectionId, - required String documentId, - required String attribute, - double? value, - double? max, - String? transactionId}) async { + 'This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.', + ) + Future incrementDocumentAttribute({ + required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? max, + String? transactionId, + }) async { final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId) - .replaceAll('{attribute}', attribute); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ) + .replaceAll( + '{attribute}', + attribute, + ); final Map apiParams = { if (value != null) 'value': value, @@ -410,8 +576,12 @@ class Databases extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Document.fromMap(res.data); } diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 6cde02ed..fc5f460e 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -8,10 +8,15 @@ class Functions extends Service { /// 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, bool? total}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); + Future listExecutions({ + required String functionId, + List? queries, + bool? total, + }) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll( + '{functionId}', + functionId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -23,8 +28,12 @@ class Functions extends Service { 'accept': '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.ExecutionList.fromMap(res.data); } @@ -33,22 +42,25 @@ 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 { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); + 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 = { if (body != null) 'body': body, if (xasync != null) 'async': xasync, if (path != null) 'path': path, - if (method != null) 'method': method.value, + if (method != null) 'method': method?.value, if (headers != null) 'headers': headers, if (scheduledAt != null) 'scheduledAt': scheduledAt, }; @@ -59,18 +71,30 @@ class Functions extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Execution.fromMap(res.data); } /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { + Future getExecution({ + required String functionId, + required String executionId, + }) async { final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); + .replaceAll( + '{functionId}', + functionId, + ) + .replaceAll( + '{executionId}', + executionId, + ); final Map apiParams = {}; @@ -79,8 +103,12 @@ class Functions extends Service { 'accept': '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.Execution.fromMap(res.data); } diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index c86f3719..c4a643db 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -7,7 +7,9 @@ class Graphql extends Service { Graphql(super.client); /// Execute a GraphQL mutation. - Future query({required Map query}) async { + Future query({ + required Map query, + }) async { final String apiPath = '/graphql'; final Map apiParams = { @@ -21,14 +23,20 @@ class Graphql extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { + Future mutation({ + required Map query, + }) async { final String apiPath = '/graphql/mutation'; final Map apiParams = { @@ -42,8 +50,12 @@ class Graphql extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + 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 87ea162e..d4831b74 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -22,8 +22,12 @@ class Locale extends Service { 'accept': '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); } @@ -40,8 +44,12 @@ class Locale extends Service { 'accept': '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); } @@ -58,8 +66,12 @@ class Locale extends Service { 'accept': '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.ContinentList.fromMap(res.data); } @@ -76,8 +88,12 @@ class Locale extends Service { 'accept': '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); } @@ -94,8 +110,12 @@ class Locale extends Service { 'accept': '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); } @@ -112,8 +132,12 @@ class Locale extends Service { 'accept': '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); } @@ -131,8 +155,12 @@ class Locale extends Service { 'accept': '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); } @@ -149,8 +177,12 @@ class Locale extends Service { 'accept': '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.LanguageList.fromMap(res.data); } diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 61ecefee..d213b55f 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -7,12 +7,15 @@ class Messaging extends Service { Messaging(super.client); /// 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); + 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, @@ -25,19 +28,31 @@ class Messaging extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Subscriber.fromMap(res.data); } /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { + Future deleteSubscriber({ + required String topicId, + required String subscriberId, + }) async { final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); + .replaceAll( + '{topicId}', + topicId, + ) + .replaceAll( + '{subscriberId}', + subscriberId, + ); final Map apiParams = {}; @@ -46,8 +61,12 @@ class Messaging extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 68275296..1dd88dac 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -7,8 +7,10 @@ class Organization extends Service { /// List app installations on the organization. Any organization member can /// read installations. - Future listInstallations( - {List? queries, bool? total}) async { + Future listInstallations({ + List? queries, + bool? total, + }) async { final String apiPath = '/organization/installations'; final Map apiParams = { @@ -21,8 +23,12 @@ class Organization extends Service { 'accept': '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.AppInstallationList.fromMap(res.data); } @@ -30,8 +36,10 @@ class Organization extends Service { /// Install an app on the organization. Only organization members with the /// owner role can install apps. The installation is granted the scopes the app /// currently requests. - Future createInstallation( - {required String appId, String? authorizationDetails}) async { + Future createInstallation({ + required String appId, + String? authorizationDetails, + }) async { final String apiPath = '/organization/installations'; final Map apiParams = { @@ -46,18 +54,26 @@ class Organization extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } /// Get an app installation on the organization by its unique ID. Any /// organization member can read installations. - Future getInstallation( - {required String installationId}) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll('{installationId}', installationId); + Future getInstallation({ + required String installationId, + }) async { + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -66,8 +82,12 @@ class Organization extends Service { 'accept': '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.AppInstallation.fromMap(res.data); } @@ -76,10 +96,15 @@ class Organization extends Service { /// with the owner role can update installations. The installation's granted /// scopes are refreshed to the scopes the app currently requests; previously /// issued installation access tokens are revoked. - Future updateInstallation( - {required String installationId, String? authorizationDetails}) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll('{installationId}', installationId); + Future updateInstallation({ + required String installationId, + String? authorizationDetails, + }) async { + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -92,8 +117,12 @@ class Organization extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } @@ -101,9 +130,14 @@ class Organization extends Service { /// Uninstall an app from the organization by its installation ID. Only /// organization members with the owner role can remove installations. /// Previously issued installation access tokens are revoked. - Future deleteInstallation({required String installationId}) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll('{installationId}', installationId); + Future deleteInstallation({ + required String installationId, + }) async { + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -113,8 +147,12 @@ class Organization extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } diff --git a/lib/services/presences.dart b/lib/services/presences.dart index fd5d6be2..f40c07e3 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -7,9 +7,11 @@ class Presences extends Service { Presences(super.client); /// List presence logs. Expired entries are filtered out automatically. - /// - Future list( - {List? queries, bool? total, int? ttl}) async { + Future list({ + List? queries, + bool? total, + int? ttl, + }) async { final String apiPath = '/presences'; final Map apiParams = { @@ -23,18 +25,25 @@ class Presences extends Service { 'accept': '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.PresenceList.fromMap(res.data); } /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// - Future get({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + Future get({ + required String presenceId, + }) async { + final String apiPath = '/presences/{presenceId}'.replaceAll( + '{presenceId}', + presenceId, + ); final Map apiParams = {}; @@ -43,22 +52,28 @@ class Presences extends Service { 'accept': '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.Presence.fromMap(res.data); } /// Create or update a presence log by its user ID. - /// - Future upsert( - {required String presenceId, - required String status, - List? permissions, - String? expiresAt, - Map? metadata}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + Future upsert({ + required String presenceId, + required String status, + List? permissions, + String? expiresAt, + Map? metadata, + }) async { + final String apiPath = '/presences/{presenceId}'.replaceAll( + '{presenceId}', + presenceId, + ); final Map apiParams = { 'status': status, @@ -73,24 +88,30 @@ class Presences extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Presence.fromMap(res.data); } /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// - Future update( - {required String presenceId, - String? status, - String? expiresAt, - Map? metadata, - List? permissions, - bool? purge}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + Future update({ + required String presenceId, + String? status, + String? expiresAt, + Map? metadata, + List? permissions, + bool? purge, + }) async { + final String apiPath = '/presences/{presenceId}'.replaceAll( + '{presenceId}', + presenceId, + ); final Map apiParams = { if (status != null) 'status': status, @@ -106,17 +127,24 @@ class Presences extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Presence.fromMap(res.data); } /// Delete a presence log by its unique ID. - /// - Future delete({required String presenceId}) async { - final String apiPath = - '/presences/{presenceId}'.replaceAll('{presenceId}', presenceId); + Future delete({ + required String presenceId, + }) async { + final String apiPath = '/presences/{presenceId}'.replaceAll( + '{presenceId}', + presenceId, + ); final Map apiParams = {}; @@ -125,8 +153,12 @@ class Presences extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + 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 d261ef17..77f156dd 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -7,13 +7,16 @@ class Storage extends Service { /// 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, - bool? total}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + Future listFiles({ + required String bucketId, + List? queries, + String? search, + bool? total, + }) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll( + '{bucketId}', + bucketId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -26,8 +29,12 @@ class Storage extends Service { 'accept': '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.FileList.fromMap(res.data); } @@ -49,16 +56,18 @@ class Storage extends Service { /// /// 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, - String? folder, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + Future createFile({ + required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + String? folder, + Function(UploadProgress)? onProgress, + }) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll( + '{bucketId}', + bucketId, + ); final Map apiParams = { 'fileId': fileId, @@ -74,8 +83,8 @@ class Storage extends Service { }; String idParamName = ''; - idParamName = 'fileId'; final paramName = 'file'; + idParamName = 'fileId'; final res = await client.chunkedUpload( path: apiPath, params: apiParams, @@ -90,11 +99,19 @@ class Storage extends Service { /// 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 { + Future getFile({ + required String bucketId, + required String fileId, + }) async { final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = {}; @@ -103,22 +120,33 @@ class Storage extends Service { 'accept': '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.File.fromMap(res.data); } /// 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 { + 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); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = { if (name != null) 'name': name, @@ -131,18 +159,31 @@ class Storage extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.File.fromMap(res.data); } /// 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 { + Future deleteFile({ + required String bucketId, + required String fileId, + }) async { final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = {}; @@ -151,8 +192,12 @@ class Storage extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -160,11 +205,20 @@ class Storage extends Service { /// 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, String? token}) async { + Future getFileDownload({ + required String bucketId, + required String fileId, + String? token, + }) async { final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = { if (token != null) 'token': token, @@ -175,11 +229,13 @@ class Storage extends Service { 'accept': '*/*', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } @@ -188,29 +244,36 @@ class Storage extends Service { /// 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, - String? token}) async { + 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, + String? token, + }) async { final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = { if (width != null) 'width': width, if (height != null) 'height': height, - if (gravity != null) 'gravity': gravity.value, + if (gravity != null) 'gravity': gravity?.value, if (quality != null) 'quality': quality, if (borderWidth != null) 'borderWidth': borderWidth, if (borderColor != null) 'borderColor': borderColor, @@ -218,7 +281,7 @@ class Storage extends Service { if (opacity != null) 'opacity': opacity, if (rotation != null) 'rotation': rotation, if (background != null) 'background': background, - if (output != null) 'output': output.value, + if (output != null) 'output': output?.value, if (token != null) 'token': token, }; @@ -227,22 +290,33 @@ class Storage extends Service { 'accept': 'image/*', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } /// 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, String? token}) async { + Future getFileView({ + required String bucketId, + required String fileId, + String? token, + }) async { final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); + .replaceAll( + '{bucketId}', + bucketId, + ) + .replaceAll( + '{fileId}', + fileId, + ); final Map apiParams = { if (token != null) 'token': token, @@ -253,11 +327,13 @@ class Storage extends Service { 'accept': '*/*', }; - final res = await client.call(HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - responseType: ResponseType.bytes); + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + responseType: ResponseType.bytes, + ); return res.data; } } diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 45c239e6..d7f23f39 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -7,8 +7,9 @@ class TablesDB extends Service { TablesDB(super.client); /// List transactions across all databases. - Future listTransactions( - {List? queries}) async { + Future listTransactions({ + List? queries, + }) async { final String apiPath = '/tablesdb/transactions'; final Map apiParams = { @@ -20,14 +21,20 @@ class TablesDB extends Service { 'accept': '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.TransactionList.fromMap(res.data); } /// Create a new transaction. - Future createTransaction({int? ttl}) async { + Future createTransaction({ + int? ttl, + }) async { final String apiPath = '/tablesdb/transactions'; final Map apiParams = { @@ -40,17 +47,24 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } /// Get a transaction by its unique ID. - Future getTransaction( - {required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future getTransaction({ + required String transactionId, + }) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -59,17 +73,26 @@ class TablesDB extends Service { 'accept': '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.Transaction.fromMap(res.data); } /// Update a transaction, to either commit or roll back its operations. - Future updateTransaction( - {required String transactionId, bool? commit, bool? rollback}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future updateTransaction({ + required String transactionId, + bool? commit, + bool? rollback, + }) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (commit != null) 'commit': commit, @@ -82,16 +105,24 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } /// Delete a transaction by its unique ID. - Future deleteTransaction({required String transactionId}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}' - .replaceAll('{transactionId}', transactionId); + Future deleteTransaction({ + required String transactionId, + }) async { + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -100,17 +131,26 @@ class TablesDB extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// Create multiple operations in a single transaction. - Future createOperations( - {required String transactionId, List? operations}) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll('{transactionId}', transactionId); + Future createOperations({ + required String transactionId, + List? operations, + }) async { + final String apiPath = + '/tablesdb/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, @@ -122,24 +162,35 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Transaction.fromMap(res.data); } /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. - Future listRows( - {required String databaseId, - required String tableId, - List? queries, - String? transactionId, - bool? total, - int? ttl}) async { + Future listRows({ + required String databaseId, + required String tableId, + List? queries, + String? transactionId, + bool? total, + int? ttl, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -153,8 +204,12 @@ class TablesDB extends Service { 'accept': '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.RowList.fromMap(res.data); } @@ -163,16 +218,23 @@ class TablesDB extends Service { /// resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future createRow( - {required String databaseId, - required String tableId, - required String rowId, - required Map data, - List? permissions, - String? transactionId}) async { + Future createRow({ + required String databaseId, + required String tableId, + required String rowId, + required Map data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ); final Map apiParams = { 'rowId': rowId, @@ -187,25 +249,39 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Row.fromMap(res.data); } /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. - Future getRow( - {required String databaseId, - required String tableId, - required String rowId, - List? queries, - String? transactionId}) async { + Future getRow({ + required String databaseId, + required String tableId, + required String rowId, + List? queries, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -217,8 +293,12 @@ class TablesDB extends Service { 'accept': '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.Row.fromMap(res.data); } @@ -227,18 +307,28 @@ class TablesDB extends Service { /// table resource using either a [server /// integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable) /// API or directly from your database console. - Future upsertRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { + Future upsertRow({ + required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ); final Map apiParams = { if (data != null) 'data': data, @@ -252,26 +342,40 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Row.fromMap(res.data); } /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. - Future updateRow( - {required String databaseId, - required String tableId, - required String rowId, - Map? data, - List? permissions, - String? transactionId}) async { + Future updateRow({ + required String databaseId, + required String tableId, + required String rowId, + Map? data, + List? permissions, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ); final Map apiParams = { if (data != null) 'data': data, @@ -285,23 +389,37 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Row.fromMap(res.data); } /// Delete a row by its unique ID. - Future deleteRow( - {required String databaseId, - required String tableId, - required String rowId, - String? transactionId}) async { + Future deleteRow({ + required String databaseId, + required String tableId, + required String rowId, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ); final Map apiParams = { if (transactionId != null) 'transactionId': transactionId, @@ -312,27 +430,44 @@ class TablesDB extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// Decrement a specific column of a row by a given value. - Future decrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? min, - String? transactionId}) async { + Future decrementRowColumn({ + required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? min, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ) + .replaceAll( + '{column}', + column, + ); final Map apiParams = { if (value != null) 'value': value, @@ -346,27 +481,44 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Row.fromMap(res.data); } /// Increment a specific column of a row by a given value. - Future incrementRowColumn( - {required String databaseId, - required String tableId, - required String rowId, - required String column, - double? value, - double? max, - String? transactionId}) async { + Future incrementRowColumn({ + required String databaseId, + required String tableId, + required String rowId, + required String column, + double? value, + double? max, + String? transactionId, + }) async { final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{tableId}', tableId) - .replaceAll('{rowId}', rowId) - .replaceAll('{column}', column); + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{tableId}', + tableId, + ) + .replaceAll( + '{rowId}', + rowId, + ) + .replaceAll( + '{column}', + column, + ); final Map apiParams = { if (value != null) 'value': value, @@ -380,8 +532,12 @@ class TablesDB extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Row.fromMap(res.data); } diff --git a/lib/services/teams.dart b/lib/services/teams.dart index c9b7b646..99190fc1 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -8,8 +8,11 @@ class Teams extends Service { /// 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, bool? total}) async { + Future list({ + List? queries, + String? search, + bool? total, + }) async { final String apiPath = '/teams'; final Map apiParams = { @@ -23,8 +26,12 @@ class Teams extends Service { 'accept': '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.TeamList.fromMap(res.data); } @@ -32,10 +39,11 @@ class Teams extends Service { /// 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 { + Future create({ + required String teamId, + required String name, + List? roles, + }) async { final String apiPath = '/teams'; final Map apiParams = { @@ -50,15 +58,24 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Team.fromMap(res.data); } /// 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); + Future get({ + required String teamId, + }) async { + final String apiPath = '/teams/{teamId}'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = {}; @@ -67,16 +84,25 @@ class Teams extends Service { 'accept': '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.Team.fromMap(res.data); } /// 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); + Future updateName({ + required String teamId, + required String name, + }) async { + final String apiPath = '/teams/{teamId}'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { 'name': name, @@ -88,16 +114,25 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Team.fromMap(res.data); } /// 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); + Future delete({ + required String teamId, + }) async { + final String apiPath = '/teams/{teamId}'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = {}; @@ -106,17 +141,26 @@ class Teams extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } /// List app installations on a team. Any team member can read installations. - Future listInstallations( - {required String teamId, List? queries, bool? total}) async { - final String apiPath = - '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + Future listInstallations({ + required String teamId, + List? queries, + bool? total, + }) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -128,8 +172,12 @@ class Teams extends Service { 'accept': '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.AppInstallationList.fromMap(res.data); } @@ -138,12 +186,15 @@ class Teams extends Service { /// with the owner role can install apps. Requests using an API key or in admin /// mode can install apps on any team. The installation is granted the scopes /// the app currently requests. - Future createInstallation( - {required String teamId, - required String appId, - String? authorizationDetails}) async { - final String apiPath = - '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + Future createInstallation({ + required String teamId, + required String appId, + String? authorizationDetails, + }) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { 'appId': appId, @@ -157,19 +208,31 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } /// Get an app installation on a team by its unique ID. Any team member can /// read installations. - Future getInstallation( - {required String teamId, required String installationId}) async { + Future getInstallation({ + required String teamId, + required String installationId, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -178,8 +241,12 @@ class Teams extends Service { 'accept': '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.AppInstallation.fromMap(res.data); } @@ -188,13 +255,20 @@ class Teams extends Service { /// can update installations. The installation's granted scopes are refreshed /// to the scopes the app currently requests; previously issued installation /// access tokens are revoked. - Future updateInstallation( - {required String teamId, - required String installationId, - String? authorizationDetails}) async { + Future updateInstallation({ + required String teamId, + required String installationId, + String? authorizationDetails, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -207,8 +281,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } @@ -216,11 +294,19 @@ class Teams extends Service { /// Uninstall an app from a team by its installation ID. Only team members with /// the owner role can remove installations. Previously issued installation /// access tokens are revoked. - Future deleteInstallation( - {required String teamId, required String installationId}) async { + Future deleteInstallation({ + required String teamId, + required String installationId, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -230,8 +316,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -239,13 +329,16 @@ class Teams extends Service { /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. - Future listMemberships( - {required String teamId, - List? queries, - String? search, - bool? total}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + Future listMemberships({ + required String teamId, + List? queries, + String? search, + bool? total, + }) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -258,8 +351,12 @@ class Teams extends Service { 'accept': '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.MembershipList.fromMap(res.data); } @@ -284,17 +381,19 @@ class Teams extends Service { /// 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); + 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 = { if (email != null) 'email': email, @@ -311,8 +410,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Membership.fromMap(res.data); } @@ -320,11 +423,19 @@ class Teams extends Service { /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by /// toggling membership privacy in the Console. - Future getMembership( - {required String teamId, required String membershipId}) async { + Future getMembership({ + required String teamId, + required String membershipId, + }) async { final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{membershipId}', + membershipId, + ); final Map apiParams = {}; @@ -333,8 +444,12 @@ class Teams extends Service { 'accept': '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.Membership.fromMap(res.data); } @@ -342,14 +457,20 @@ class Teams extends Service { /// 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 { + 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); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{membershipId}', + membershipId, + ); final Map apiParams = { 'roles': roles, @@ -361,8 +482,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Membership.fromMap(res.data); } @@ -370,11 +495,19 @@ class Teams extends Service { /// 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 { + Future deleteMembership({ + required String teamId, + required String membershipId, + }) async { final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{membershipId}', + membershipId, + ); final Map apiParams = {}; @@ -383,8 +516,12 @@ class Teams extends Service { 'content-type': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } @@ -395,15 +532,21 @@ class Teams extends Service { /// /// 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 { + 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); + .replaceAll( + '{teamId}', + teamId, + ) + .replaceAll( + '{membershipId}', + membershipId, + ); final Map apiParams = { 'userId': userId, @@ -416,8 +559,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.Membership.fromMap(res.data); } @@ -425,9 +572,13 @@ class Teams extends Service { /// 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); + Future getPrefs({ + required String teamId, + }) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = {}; @@ -436,8 +587,12 @@ class Teams extends Service { 'accept': '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.Preferences.fromMap(res.data); } @@ -445,10 +600,14 @@ class Teams extends Service { /// 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); + Future updatePrefs({ + required String teamId, + required Map prefs, + }) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { 'prefs': prefs, @@ -460,8 +619,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + 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_browser.dart b/lib/src/client_browser.dart index 47d38062..279868ed 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.4.0', + 'x-sdk-version': '25.5.0', 'X-Appwrite-Response-Format': '1.9.6', }; @@ -215,7 +215,7 @@ class ClientBrowser extends ClientBase with ClientMixin { var offset = 0; String? uploadId; - if (idParamName.isNotEmpty) { + if (idParamName.isNotEmpty && params[idParamName] != null) { //make a request to check if a file already exists try { res = await call( @@ -236,7 +236,11 @@ class ClientBrowser extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); Future uploadChunk( - int index, int start, int end, String? id) async { + int index, + int start, + int end, + String? id, + ) async { List chunk = []; chunk = file.bytes!.getRange(start, end).toList(); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index c675f9e1..9566820e 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:cookie_jar/cookie_jar.dart'; @@ -58,7 +59,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.4.0', + 'x-sdk-version': '25.5.0', 'X-Appwrite-Response-Format': '1.9.6', }; @@ -336,7 +337,7 @@ class ClientIO extends ClientBase with ClientMixin { var offset = 0; String? uploadId; - if (idParamName.isNotEmpty) { + if (idParamName.isNotEmpty && params[idParamName] != null) { //make a request to check if a file already exists try { res = await call( @@ -492,6 +493,29 @@ class ClientIO extends ClientBase with ClientMixin { final key = url.queryParameters['key']; final secret = url.queryParameters['secret']; if (key == null || secret == null) { + final error = url.queryParameters['error']; + if (error != null && error.isNotEmpty) { + try { + final parsed = jsonDecode(error); + if (parsed is Map) { + final codeValue = parsed['code']; + final int? code = codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); + throw AppwriteException( + parsed['message']?.toString() ?? error, + code, + parsed['type']?.toString(), + error, + ); + } + } on AppwriteException { + rethrow; + } catch (_) { + // Fall through to a plain-string error when JSON is malformed. + } + throw AppwriteException(error); + } throw AppwriteException( "Invalid OAuth2 Response. Key and Secret not available.", 500, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 89aad359..952d7114 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -92,7 +92,11 @@ mixin ClientMixin { } if (res.statusCode >= 400) { - if ((res.headers['content-type'] ?? '').contains('application/json')) { + final isJson = + (res.headers['content-type'] ?? '').contains('application/json'); + // Empty bodies still arrive with application/json (e.g. truncated + // proxy/edge errors). Avoid FormatException from json.decode(''). + if (isJson && res.body.isNotEmpty) { final response = json.decode(res.body); throw AppwriteException( response['message'], @@ -101,7 +105,14 @@ mixin ClientMixin { res.body, ); } else { - throw AppwriteException(res.body, res.statusCode, '', res.body); + throw AppwriteException( + res.body.isEmpty + ? 'Unexpected empty response with status ${res.statusCode}' + : res.body, + res.statusCode, + '', + res.body, + ); } } dynamic data; diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..99019503 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,10 +1,11 @@ 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"), + custom(value: "custom"); const AuthenticationFactor({required this.value}); diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..c173d98b 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,7 +1,7 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: "totp"); const AuthenticatorType({required this.value}); diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..5c31e055 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,20 +1,20 @@ 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}); diff --git a/lib/src/enums/browser_permission.dart b/lib/src/enums/browser_permission.dart index fb4983db..6bd74622 100644 --- a/lib/src/enums/browser_permission.dart +++ b/lib/src/enums/browser_permission.dart @@ -1,26 +1,26 @@ part of '../../enums.dart'; enum BrowserPermission { - geolocation(value: 'geolocation'), - camera(value: 'camera'), - microphone(value: 'microphone'), - notifications(value: 'notifications'), - midi(value: 'midi'), - push(value: 'push'), - clipboardRead(value: 'clipboard-read'), - clipboardWrite(value: 'clipboard-write'), - paymentHandler(value: 'payment-handler'), - usb(value: 'usb'), - bluetooth(value: 'bluetooth'), - accelerometer(value: 'accelerometer'), - gyroscope(value: 'gyroscope'), - magnetometer(value: 'magnetometer'), - ambientLightSensor(value: 'ambient-light-sensor'), - backgroundSync(value: 'background-sync'), - persistentStorage(value: 'persistent-storage'), - screenWakeLock(value: 'screen-wake-lock'), - webShare(value: 'web-share'), - xrSpatialTracking(value: 'xr-spatial-tracking'); + geolocation(value: "geolocation"), + camera(value: "camera"), + microphone(value: "microphone"), + notifications(value: "notifications"), + midi(value: "midi"), + push(value: "push"), + clipboardRead(value: "clipboard-read"), + clipboardWrite(value: "clipboard-write"), + paymentHandler(value: "payment-handler"), + usb(value: "usb"), + bluetooth(value: "bluetooth"), + accelerometer(value: "accelerometer"), + gyroscope(value: "gyroscope"), + magnetometer(value: "magnetometer"), + ambientLightSensor(value: "ambient-light-sensor"), + backgroundSync(value: "background-sync"), + persistentStorage(value: "persistent-storage"), + screenWakeLock(value: "screen-wake-lock"), + webShare(value: "web-share"), + xrSpatialTracking(value: "xr-spatial-tracking"); const BrowserPermission({required this.value}); diff --git a/lib/src/enums/browser_theme.dart b/lib/src/enums/browser_theme.dart index 1e059c2c..48a3e464 100644 --- a/lib/src/enums/browser_theme.dart +++ b/lib/src/enums/browser_theme.dart @@ -1,8 +1,8 @@ part of '../../enums.dart'; enum BrowserTheme { - light(value: 'light'), - dark(value: 'dark'); + light(value: "light"), + dark(value: "dark"); const BrowserTheme({required this.value}); diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 28c2a1b3..bb40ecae 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,23 +1,23 @@ 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'), - unionPay(value: 'unionpay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'), - rupay(value: 'rupay'); + 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"), + unionPay(value: "unionpay"), + visa(value: "visa"), + mIR(value: "mir"), + maestro(value: "maestro"), + rupay(value: "rupay"); const CreditCard({required this.value}); diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 44de4907..80abd2da 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,13 +1,13 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'), - hEAD(value: 'HEAD'); + gET(value: "GET"), + pOST(value: "POST"), + pUT(value: "PUT"), + pATCH(value: "PATCH"), + dELETE(value: "DELETE"), + oPTIONS(value: "OPTIONS"), + hEAD(value: "HEAD"); const ExecutionMethod({required this.value}); diff --git a/lib/src/enums/execution_resource_type.dart b/lib/src/enums/execution_resource_type.dart new file mode 100644 index 00000000..d59d2a50 --- /dev/null +++ b/lib/src/enums/execution_resource_type.dart @@ -0,0 +1,12 @@ +part of '../../enums.dart'; + +enum ExecutionResourceType { + functions(value: "functions"), + sites(value: "sites"); + + const ExecutionResourceType({required this.value}); + + final String value; + + String toJson() => value; +} diff --git a/lib/src/enums/execution_status.dart b/lib/src/enums/execution_status.dart index 7ea9865e..d65d4981 100644 --- a/lib/src/enums/execution_status.dart +++ b/lib/src/enums/execution_status.dart @@ -1,11 +1,11 @@ part of '../../enums.dart'; enum ExecutionStatus { - waiting(value: 'waiting'), - processing(value: 'processing'), - completed(value: 'completed'), - failed(value: 'failed'), - scheduled(value: 'scheduled'); + waiting(value: "waiting"), + processing(value: "processing"), + completed(value: "completed"), + failed(value: "failed"), + scheduled(value: "scheduled"); const ExecutionStatus({required this.value}); diff --git a/lib/src/enums/execution_trigger.dart b/lib/src/enums/execution_trigger.dart index fb05eb7d..a0816b66 100644 --- a/lib/src/enums/execution_trigger.dart +++ b/lib/src/enums/execution_trigger.dart @@ -1,9 +1,9 @@ part of '../../enums.dart'; enum ExecutionTrigger { - http(value: 'http'), - schedule(value: 'schedule'), - event(value: 'event'); + http(value: "http"), + schedule(value: "schedule"), + event(value: "event"); const ExecutionTrigger({required this.value}); diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..3c6a9695 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,201 +1,201 @@ 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}); diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 55f4c5db..aa1e7a92 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,13 +1,13 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - png(value: 'png'), - webp(value: 'webp'), - heic(value: 'heic'), - avif(value: 'avif'), - gif(value: 'gif'); + jpg(value: "jpg"), + jpeg(value: "jpeg"), + png(value: "png"), + webp(value: "webp"), + heic(value: "heic"), + avif(value: "avif"), + gif(value: "gif"); const ImageFormat({required this.value}); diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..dbcef202 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,15 +1,15 @@ 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}); diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 6c8dbc70..1bd23697 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,50 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - appwrite(value: 'appwrite'), - 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'), - figma(value: 'figma'), - fusionauth(value: 'fusionauth'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - keycloak(value: 'keycloak'), - kick(value: 'kick'), - 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'), - x(value: 'x'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'); + amazon(value: "amazon"), + apple(value: "apple"), + appwrite(value: "appwrite"), + 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"), + figma(value: "figma"), + fusionauth(value: "fusionauth"), + github(value: "github"), + gitlab(value: "gitlab"), + google(value: "google"), + huggingface(value: "huggingface"), + keycloak(value: "keycloak"), + kick(value: "kick"), + 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"), + x(value: "x"), + yahoo(value: "yahoo"), + yammer(value: "yammer"), + yandex(value: "yandex"), + zoho(value: "zoho"), + zoom(value: "zoom"); const OAuthProvider({required this.value}); diff --git a/lib/src/enums/timezone.dart b/lib/src/enums/timezone.dart index d5d8d94a..2f49d305 100644 --- a/lib/src/enums/timezone.dart +++ b/lib/src/enums/timezone.dart @@ -1,425 +1,425 @@ part of '../../enums.dart'; enum Timezone { - africaAbidjan(value: 'africa/abidjan'), - africaAccra(value: 'africa/accra'), - africaAddisAbaba(value: 'africa/addis_ababa'), - africaAlgiers(value: 'africa/algiers'), - africaAsmara(value: 'africa/asmara'), - africaBamako(value: 'africa/bamako'), - africaBangui(value: 'africa/bangui'), - africaBanjul(value: 'africa/banjul'), - africaBissau(value: 'africa/bissau'), - africaBlantyre(value: 'africa/blantyre'), - africaBrazzaville(value: 'africa/brazzaville'), - africaBujumbura(value: 'africa/bujumbura'), - africaCairo(value: 'africa/cairo'), - africaCasablanca(value: 'africa/casablanca'), - africaCeuta(value: 'africa/ceuta'), - africaConakry(value: 'africa/conakry'), - africaDakar(value: 'africa/dakar'), - africaDarEsSalaam(value: 'africa/dar_es_salaam'), - africaDjibouti(value: 'africa/djibouti'), - africaDouala(value: 'africa/douala'), - africaElAaiun(value: 'africa/el_aaiun'), - africaFreetown(value: 'africa/freetown'), - africaGaborone(value: 'africa/gaborone'), - africaHarare(value: 'africa/harare'), - africaJohannesburg(value: 'africa/johannesburg'), - africaJuba(value: 'africa/juba'), - africaKampala(value: 'africa/kampala'), - africaKhartoum(value: 'africa/khartoum'), - africaKigali(value: 'africa/kigali'), - africaKinshasa(value: 'africa/kinshasa'), - africaLagos(value: 'africa/lagos'), - africaLibreville(value: 'africa/libreville'), - africaLome(value: 'africa/lome'), - africaLuanda(value: 'africa/luanda'), - africaLubumbashi(value: 'africa/lubumbashi'), - africaLusaka(value: 'africa/lusaka'), - africaMalabo(value: 'africa/malabo'), - africaMaputo(value: 'africa/maputo'), - africaMaseru(value: 'africa/maseru'), - africaMbabane(value: 'africa/mbabane'), - africaMogadishu(value: 'africa/mogadishu'), - africaMonrovia(value: 'africa/monrovia'), - africaNairobi(value: 'africa/nairobi'), - africaNdjamena(value: 'africa/ndjamena'), - africaNiamey(value: 'africa/niamey'), - africaNouakchott(value: 'africa/nouakchott'), - africaOuagadougou(value: 'africa/ouagadougou'), - africaPortoNovo(value: 'africa/porto-novo'), - africaSaoTome(value: 'africa/sao_tome'), - africaTripoli(value: 'africa/tripoli'), - africaTunis(value: 'africa/tunis'), - africaWindhoek(value: 'africa/windhoek'), - americaAdak(value: 'america/adak'), - americaAnchorage(value: 'america/anchorage'), - americaAnguilla(value: 'america/anguilla'), - americaAntigua(value: 'america/antigua'), - americaAraguaina(value: 'america/araguaina'), - americaArgentinaBuenosAires(value: 'america/argentina/buenos_aires'), - americaArgentinaCatamarca(value: 'america/argentina/catamarca'), - americaArgentinaCordoba(value: 'america/argentina/cordoba'), - americaArgentinaJujuy(value: 'america/argentina/jujuy'), - americaArgentinaLaRioja(value: 'america/argentina/la_rioja'), - americaArgentinaMendoza(value: 'america/argentina/mendoza'), - americaArgentinaRioGallegos(value: 'america/argentina/rio_gallegos'), - americaArgentinaSalta(value: 'america/argentina/salta'), - americaArgentinaSanJuan(value: 'america/argentina/san_juan'), - americaArgentinaSanLuis(value: 'america/argentina/san_luis'), - americaArgentinaTucuman(value: 'america/argentina/tucuman'), - americaArgentinaUshuaia(value: 'america/argentina/ushuaia'), - americaAruba(value: 'america/aruba'), - americaAsuncion(value: 'america/asuncion'), - americaAtikokan(value: 'america/atikokan'), - americaBahia(value: 'america/bahia'), - americaBahiaBanderas(value: 'america/bahia_banderas'), - americaBarbados(value: 'america/barbados'), - americaBelem(value: 'america/belem'), - americaBelize(value: 'america/belize'), - americaBlancSablon(value: 'america/blanc-sablon'), - americaBoaVista(value: 'america/boa_vista'), - americaBogota(value: 'america/bogota'), - americaBoise(value: 'america/boise'), - americaCambridgeBay(value: 'america/cambridge_bay'), - americaCampoGrande(value: 'america/campo_grande'), - americaCancun(value: 'america/cancun'), - americaCaracas(value: 'america/caracas'), - americaCayenne(value: 'america/cayenne'), - americaCayman(value: 'america/cayman'), - americaChicago(value: 'america/chicago'), - americaChihuahua(value: 'america/chihuahua'), - americaCiudadJuarez(value: 'america/ciudad_juarez'), - americaCostaRica(value: 'america/costa_rica'), - americaCoyhaique(value: 'america/coyhaique'), - americaCreston(value: 'america/creston'), - americaCuiaba(value: 'america/cuiaba'), - americaCuracao(value: 'america/curacao'), - americaDanmarkshavn(value: 'america/danmarkshavn'), - americaDawson(value: 'america/dawson'), - americaDawsonCreek(value: 'america/dawson_creek'), - americaDenver(value: 'america/denver'), - americaDetroit(value: 'america/detroit'), - americaDominica(value: 'america/dominica'), - americaEdmonton(value: 'america/edmonton'), - americaEirunepe(value: 'america/eirunepe'), - americaElSalvador(value: 'america/el_salvador'), - americaFortNelson(value: 'america/fort_nelson'), - americaFortaleza(value: 'america/fortaleza'), - americaGlaceBay(value: 'america/glace_bay'), - americaGooseBay(value: 'america/goose_bay'), - americaGrandTurk(value: 'america/grand_turk'), - americaGrenada(value: 'america/grenada'), - americaGuadeloupe(value: 'america/guadeloupe'), - americaGuatemala(value: 'america/guatemala'), - americaGuayaquil(value: 'america/guayaquil'), - americaGuyana(value: 'america/guyana'), - americaHalifax(value: 'america/halifax'), - americaHavana(value: 'america/havana'), - americaHermosillo(value: 'america/hermosillo'), - americaIndianaIndianapolis(value: 'america/indiana/indianapolis'), - americaIndianaKnox(value: 'america/indiana/knox'), - americaIndianaMarengo(value: 'america/indiana/marengo'), - americaIndianaPetersburg(value: 'america/indiana/petersburg'), - americaIndianaTellCity(value: 'america/indiana/tell_city'), - americaIndianaVevay(value: 'america/indiana/vevay'), - americaIndianaVincennes(value: 'america/indiana/vincennes'), - americaIndianaWinamac(value: 'america/indiana/winamac'), - americaInuvik(value: 'america/inuvik'), - americaIqaluit(value: 'america/iqaluit'), - americaJamaica(value: 'america/jamaica'), - americaJuneau(value: 'america/juneau'), - americaKentuckyLouisville(value: 'america/kentucky/louisville'), - americaKentuckyMonticello(value: 'america/kentucky/monticello'), - americaKralendijk(value: 'america/kralendijk'), - americaLaPaz(value: 'america/la_paz'), - americaLima(value: 'america/lima'), - americaLosAngeles(value: 'america/los_angeles'), - americaLowerPrinces(value: 'america/lower_princes'), - americaMaceio(value: 'america/maceio'), - americaManagua(value: 'america/managua'), - americaManaus(value: 'america/manaus'), - americaMarigot(value: 'america/marigot'), - americaMartinique(value: 'america/martinique'), - americaMatamoros(value: 'america/matamoros'), - americaMazatlan(value: 'america/mazatlan'), - americaMenominee(value: 'america/menominee'), - americaMerida(value: 'america/merida'), - americaMetlakatla(value: 'america/metlakatla'), - americaMexicoCity(value: 'america/mexico_city'), - americaMiquelon(value: 'america/miquelon'), - americaMoncton(value: 'america/moncton'), - americaMonterrey(value: 'america/monterrey'), - americaMontevideo(value: 'america/montevideo'), - americaMontserrat(value: 'america/montserrat'), - americaNassau(value: 'america/nassau'), - americaNewYork(value: 'america/new_york'), - americaNome(value: 'america/nome'), - americaNoronha(value: 'america/noronha'), - americaNorthDakotaBeulah(value: 'america/north_dakota/beulah'), - americaNorthDakotaCenter(value: 'america/north_dakota/center'), - americaNorthDakotaNewSalem(value: 'america/north_dakota/new_salem'), - americaNuuk(value: 'america/nuuk'), - americaOjinaga(value: 'america/ojinaga'), - americaPanama(value: 'america/panama'), - americaParamaribo(value: 'america/paramaribo'), - americaPhoenix(value: 'america/phoenix'), - americaPortAuPrince(value: 'america/port-au-prince'), - americaPortOfSpain(value: 'america/port_of_spain'), - americaPortoVelho(value: 'america/porto_velho'), - americaPuertoRico(value: 'america/puerto_rico'), - americaPuntaArenas(value: 'america/punta_arenas'), - americaRankinInlet(value: 'america/rankin_inlet'), - americaRecife(value: 'america/recife'), - americaRegina(value: 'america/regina'), - americaResolute(value: 'america/resolute'), - americaRioBranco(value: 'america/rio_branco'), - americaSantarem(value: 'america/santarem'), - americaSantiago(value: 'america/santiago'), - americaSantoDomingo(value: 'america/santo_domingo'), - americaSaoPaulo(value: 'america/sao_paulo'), - americaScoresbysund(value: 'america/scoresbysund'), - americaSitka(value: 'america/sitka'), - americaStBarthelemy(value: 'america/st_barthelemy'), - americaStJohns(value: 'america/st_johns'), - americaStKitts(value: 'america/st_kitts'), - americaStLucia(value: 'america/st_lucia'), - americaStThomas(value: 'america/st_thomas'), - americaStVincent(value: 'america/st_vincent'), - americaSwiftCurrent(value: 'america/swift_current'), - americaTegucigalpa(value: 'america/tegucigalpa'), - americaThule(value: 'america/thule'), - americaTijuana(value: 'america/tijuana'), - americaToronto(value: 'america/toronto'), - americaTortola(value: 'america/tortola'), - americaVancouver(value: 'america/vancouver'), - americaWhitehorse(value: 'america/whitehorse'), - americaWinnipeg(value: 'america/winnipeg'), - americaYakutat(value: 'america/yakutat'), - antarcticaCasey(value: 'antarctica/casey'), - antarcticaDavis(value: 'antarctica/davis'), - antarcticaDumontdurville(value: 'antarctica/dumontdurville'), - antarcticaMacquarie(value: 'antarctica/macquarie'), - antarcticaMawson(value: 'antarctica/mawson'), - antarcticaMcmurdo(value: 'antarctica/mcmurdo'), - antarcticaPalmer(value: 'antarctica/palmer'), - antarcticaRothera(value: 'antarctica/rothera'), - antarcticaSyowa(value: 'antarctica/syowa'), - antarcticaTroll(value: 'antarctica/troll'), - antarcticaVostok(value: 'antarctica/vostok'), - arcticLongyearbyen(value: 'arctic/longyearbyen'), - asiaAden(value: 'asia/aden'), - asiaAlmaty(value: 'asia/almaty'), - asiaAmman(value: 'asia/amman'), - asiaAnadyr(value: 'asia/anadyr'), - asiaAqtau(value: 'asia/aqtau'), - asiaAqtobe(value: 'asia/aqtobe'), - asiaAshgabat(value: 'asia/ashgabat'), - asiaAtyrau(value: 'asia/atyrau'), - asiaBaghdad(value: 'asia/baghdad'), - asiaBahrain(value: 'asia/bahrain'), - asiaBaku(value: 'asia/baku'), - asiaBangkok(value: 'asia/bangkok'), - asiaBarnaul(value: 'asia/barnaul'), - asiaBeirut(value: 'asia/beirut'), - asiaBishkek(value: 'asia/bishkek'), - asiaBrunei(value: 'asia/brunei'), - asiaChita(value: 'asia/chita'), - asiaColombo(value: 'asia/colombo'), - asiaDamascus(value: 'asia/damascus'), - asiaDhaka(value: 'asia/dhaka'), - asiaDili(value: 'asia/dili'), - asiaDubai(value: 'asia/dubai'), - asiaDushanbe(value: 'asia/dushanbe'), - asiaFamagusta(value: 'asia/famagusta'), - asiaGaza(value: 'asia/gaza'), - asiaHebron(value: 'asia/hebron'), - asiaHoChiMinh(value: 'asia/ho_chi_minh'), - asiaHongKong(value: 'asia/hong_kong'), - asiaHovd(value: 'asia/hovd'), - asiaIrkutsk(value: 'asia/irkutsk'), - asiaJakarta(value: 'asia/jakarta'), - asiaJayapura(value: 'asia/jayapura'), - asiaJerusalem(value: 'asia/jerusalem'), - asiaKabul(value: 'asia/kabul'), - asiaKamchatka(value: 'asia/kamchatka'), - asiaKarachi(value: 'asia/karachi'), - asiaKathmandu(value: 'asia/kathmandu'), - asiaKhandyga(value: 'asia/khandyga'), - asiaKolkata(value: 'asia/kolkata'), - asiaKrasnoyarsk(value: 'asia/krasnoyarsk'), - asiaKualaLumpur(value: 'asia/kuala_lumpur'), - asiaKuching(value: 'asia/kuching'), - asiaKuwait(value: 'asia/kuwait'), - asiaMacau(value: 'asia/macau'), - asiaMagadan(value: 'asia/magadan'), - asiaMakassar(value: 'asia/makassar'), - asiaManila(value: 'asia/manila'), - asiaMuscat(value: 'asia/muscat'), - asiaNicosia(value: 'asia/nicosia'), - asiaNovokuznetsk(value: 'asia/novokuznetsk'), - asiaNovosibirsk(value: 'asia/novosibirsk'), - asiaOmsk(value: 'asia/omsk'), - asiaOral(value: 'asia/oral'), - asiaPhnomPenh(value: 'asia/phnom_penh'), - asiaPontianak(value: 'asia/pontianak'), - asiaPyongyang(value: 'asia/pyongyang'), - asiaQatar(value: 'asia/qatar'), - asiaQostanay(value: 'asia/qostanay'), - asiaQyzylorda(value: 'asia/qyzylorda'), - asiaRiyadh(value: 'asia/riyadh'), - asiaSakhalin(value: 'asia/sakhalin'), - asiaSamarkand(value: 'asia/samarkand'), - asiaSeoul(value: 'asia/seoul'), - asiaShanghai(value: 'asia/shanghai'), - asiaSingapore(value: 'asia/singapore'), - asiaSrednekolymsk(value: 'asia/srednekolymsk'), - asiaTaipei(value: 'asia/taipei'), - asiaTashkent(value: 'asia/tashkent'), - asiaTbilisi(value: 'asia/tbilisi'), - asiaTehran(value: 'asia/tehran'), - asiaThimphu(value: 'asia/thimphu'), - asiaTokyo(value: 'asia/tokyo'), - asiaTomsk(value: 'asia/tomsk'), - asiaUlaanbaatar(value: 'asia/ulaanbaatar'), - asiaUrumqi(value: 'asia/urumqi'), - asiaUstNera(value: 'asia/ust-nera'), - asiaVientiane(value: 'asia/vientiane'), - asiaVladivostok(value: 'asia/vladivostok'), - asiaYakutsk(value: 'asia/yakutsk'), - asiaYangon(value: 'asia/yangon'), - asiaYekaterinburg(value: 'asia/yekaterinburg'), - asiaYerevan(value: 'asia/yerevan'), - atlanticAzores(value: 'atlantic/azores'), - atlanticBermuda(value: 'atlantic/bermuda'), - atlanticCanary(value: 'atlantic/canary'), - atlanticCapeVerde(value: 'atlantic/cape_verde'), - atlanticFaroe(value: 'atlantic/faroe'), - atlanticMadeira(value: 'atlantic/madeira'), - atlanticReykjavik(value: 'atlantic/reykjavik'), - atlanticSouthGeorgia(value: 'atlantic/south_georgia'), - atlanticStHelena(value: 'atlantic/st_helena'), - atlanticStanley(value: 'atlantic/stanley'), - australiaAdelaide(value: 'australia/adelaide'), - australiaBrisbane(value: 'australia/brisbane'), - australiaBrokenHill(value: 'australia/broken_hill'), - australiaDarwin(value: 'australia/darwin'), - australiaEucla(value: 'australia/eucla'), - australiaHobart(value: 'australia/hobart'), - australiaLindeman(value: 'australia/lindeman'), - australiaLordHowe(value: 'australia/lord_howe'), - australiaMelbourne(value: 'australia/melbourne'), - australiaPerth(value: 'australia/perth'), - australiaSydney(value: 'australia/sydney'), - europeAmsterdam(value: 'europe/amsterdam'), - europeAndorra(value: 'europe/andorra'), - europeAstrakhan(value: 'europe/astrakhan'), - europeAthens(value: 'europe/athens'), - europeBelgrade(value: 'europe/belgrade'), - europeBerlin(value: 'europe/berlin'), - europeBratislava(value: 'europe/bratislava'), - europeBrussels(value: 'europe/brussels'), - europeBucharest(value: 'europe/bucharest'), - europeBudapest(value: 'europe/budapest'), - europeBusingen(value: 'europe/busingen'), - europeChisinau(value: 'europe/chisinau'), - europeCopenhagen(value: 'europe/copenhagen'), - europeDublin(value: 'europe/dublin'), - europeGibraltar(value: 'europe/gibraltar'), - europeGuernsey(value: 'europe/guernsey'), - europeHelsinki(value: 'europe/helsinki'), - europeIsleOfMan(value: 'europe/isle_of_man'), - europeIstanbul(value: 'europe/istanbul'), - europeJersey(value: 'europe/jersey'), - europeKaliningrad(value: 'europe/kaliningrad'), - europeKirov(value: 'europe/kirov'), - europeKyiv(value: 'europe/kyiv'), - europeLisbon(value: 'europe/lisbon'), - europeLjubljana(value: 'europe/ljubljana'), - europeLondon(value: 'europe/london'), - europeLuxembourg(value: 'europe/luxembourg'), - europeMadrid(value: 'europe/madrid'), - europeMalta(value: 'europe/malta'), - europeMariehamn(value: 'europe/mariehamn'), - europeMinsk(value: 'europe/minsk'), - europeMonaco(value: 'europe/monaco'), - europeMoscow(value: 'europe/moscow'), - europeOslo(value: 'europe/oslo'), - europeParis(value: 'europe/paris'), - europePodgorica(value: 'europe/podgorica'), - europePrague(value: 'europe/prague'), - europeRiga(value: 'europe/riga'), - europeRome(value: 'europe/rome'), - europeSamara(value: 'europe/samara'), - europeSanMarino(value: 'europe/san_marino'), - europeSarajevo(value: 'europe/sarajevo'), - europeSaratov(value: 'europe/saratov'), - europeSimferopol(value: 'europe/simferopol'), - europeSkopje(value: 'europe/skopje'), - europeSofia(value: 'europe/sofia'), - europeStockholm(value: 'europe/stockholm'), - europeTallinn(value: 'europe/tallinn'), - europeTirane(value: 'europe/tirane'), - europeUlyanovsk(value: 'europe/ulyanovsk'), - europeVaduz(value: 'europe/vaduz'), - europeVatican(value: 'europe/vatican'), - europeVienna(value: 'europe/vienna'), - europeVilnius(value: 'europe/vilnius'), - europeVolgograd(value: 'europe/volgograd'), - europeWarsaw(value: 'europe/warsaw'), - europeZagreb(value: 'europe/zagreb'), - europeZurich(value: 'europe/zurich'), - indianAntananarivo(value: 'indian/antananarivo'), - indianChagos(value: 'indian/chagos'), - indianChristmas(value: 'indian/christmas'), - indianCocos(value: 'indian/cocos'), - indianComoro(value: 'indian/comoro'), - indianKerguelen(value: 'indian/kerguelen'), - indianMahe(value: 'indian/mahe'), - indianMaldives(value: 'indian/maldives'), - indianMauritius(value: 'indian/mauritius'), - indianMayotte(value: 'indian/mayotte'), - indianReunion(value: 'indian/reunion'), - pacificApia(value: 'pacific/apia'), - pacificAuckland(value: 'pacific/auckland'), - pacificBougainville(value: 'pacific/bougainville'), - pacificChatham(value: 'pacific/chatham'), - pacificChuuk(value: 'pacific/chuuk'), - pacificEaster(value: 'pacific/easter'), - pacificEfate(value: 'pacific/efate'), - pacificFakaofo(value: 'pacific/fakaofo'), - pacificFiji(value: 'pacific/fiji'), - pacificFunafuti(value: 'pacific/funafuti'), - pacificGalapagos(value: 'pacific/galapagos'), - pacificGambier(value: 'pacific/gambier'), - pacificGuadalcanal(value: 'pacific/guadalcanal'), - pacificGuam(value: 'pacific/guam'), - pacificHonolulu(value: 'pacific/honolulu'), - pacificKanton(value: 'pacific/kanton'), - pacificKiritimati(value: 'pacific/kiritimati'), - pacificKosrae(value: 'pacific/kosrae'), - pacificKwajalein(value: 'pacific/kwajalein'), - pacificMajuro(value: 'pacific/majuro'), - pacificMarquesas(value: 'pacific/marquesas'), - pacificMidway(value: 'pacific/midway'), - pacificNauru(value: 'pacific/nauru'), - pacificNiue(value: 'pacific/niue'), - pacificNorfolk(value: 'pacific/norfolk'), - pacificNoumea(value: 'pacific/noumea'), - pacificPagoPago(value: 'pacific/pago_pago'), - pacificPalau(value: 'pacific/palau'), - pacificPitcairn(value: 'pacific/pitcairn'), - pacificPohnpei(value: 'pacific/pohnpei'), - pacificPortMoresby(value: 'pacific/port_moresby'), - pacificRarotonga(value: 'pacific/rarotonga'), - pacificSaipan(value: 'pacific/saipan'), - pacificTahiti(value: 'pacific/tahiti'), - pacificTarawa(value: 'pacific/tarawa'), - pacificTongatapu(value: 'pacific/tongatapu'), - pacificWake(value: 'pacific/wake'), - pacificWallis(value: 'pacific/wallis'), - utc(value: 'utc'); + africaAbidjan(value: "africa/abidjan"), + africaAccra(value: "africa/accra"), + africaAddisAbaba(value: "africa/addis_ababa"), + africaAlgiers(value: "africa/algiers"), + africaAsmara(value: "africa/asmara"), + africaBamako(value: "africa/bamako"), + africaBangui(value: "africa/bangui"), + africaBanjul(value: "africa/banjul"), + africaBissau(value: "africa/bissau"), + africaBlantyre(value: "africa/blantyre"), + africaBrazzaville(value: "africa/brazzaville"), + africaBujumbura(value: "africa/bujumbura"), + africaCairo(value: "africa/cairo"), + africaCasablanca(value: "africa/casablanca"), + africaCeuta(value: "africa/ceuta"), + africaConakry(value: "africa/conakry"), + africaDakar(value: "africa/dakar"), + africaDarEsSalaam(value: "africa/dar_es_salaam"), + africaDjibouti(value: "africa/djibouti"), + africaDouala(value: "africa/douala"), + africaElAaiun(value: "africa/el_aaiun"), + africaFreetown(value: "africa/freetown"), + africaGaborone(value: "africa/gaborone"), + africaHarare(value: "africa/harare"), + africaJohannesburg(value: "africa/johannesburg"), + africaJuba(value: "africa/juba"), + africaKampala(value: "africa/kampala"), + africaKhartoum(value: "africa/khartoum"), + africaKigali(value: "africa/kigali"), + africaKinshasa(value: "africa/kinshasa"), + africaLagos(value: "africa/lagos"), + africaLibreville(value: "africa/libreville"), + africaLome(value: "africa/lome"), + africaLuanda(value: "africa/luanda"), + africaLubumbashi(value: "africa/lubumbashi"), + africaLusaka(value: "africa/lusaka"), + africaMalabo(value: "africa/malabo"), + africaMaputo(value: "africa/maputo"), + africaMaseru(value: "africa/maseru"), + africaMbabane(value: "africa/mbabane"), + africaMogadishu(value: "africa/mogadishu"), + africaMonrovia(value: "africa/monrovia"), + africaNairobi(value: "africa/nairobi"), + africaNdjamena(value: "africa/ndjamena"), + africaNiamey(value: "africa/niamey"), + africaNouakchott(value: "africa/nouakchott"), + africaOuagadougou(value: "africa/ouagadougou"), + africaPortoNovo(value: "africa/porto-novo"), + africaSaoTome(value: "africa/sao_tome"), + africaTripoli(value: "africa/tripoli"), + africaTunis(value: "africa/tunis"), + africaWindhoek(value: "africa/windhoek"), + americaAdak(value: "america/adak"), + americaAnchorage(value: "america/anchorage"), + americaAnguilla(value: "america/anguilla"), + americaAntigua(value: "america/antigua"), + americaAraguaina(value: "america/araguaina"), + americaArgentinaBuenosAires(value: "america/argentina/buenos_aires"), + americaArgentinaCatamarca(value: "america/argentina/catamarca"), + americaArgentinaCordoba(value: "america/argentina/cordoba"), + americaArgentinaJujuy(value: "america/argentina/jujuy"), + americaArgentinaLaRioja(value: "america/argentina/la_rioja"), + americaArgentinaMendoza(value: "america/argentina/mendoza"), + americaArgentinaRioGallegos(value: "america/argentina/rio_gallegos"), + americaArgentinaSalta(value: "america/argentina/salta"), + americaArgentinaSanJuan(value: "america/argentina/san_juan"), + americaArgentinaSanLuis(value: "america/argentina/san_luis"), + americaArgentinaTucuman(value: "america/argentina/tucuman"), + americaArgentinaUshuaia(value: "america/argentina/ushuaia"), + americaAruba(value: "america/aruba"), + americaAsuncion(value: "america/asuncion"), + americaAtikokan(value: "america/atikokan"), + americaBahia(value: "america/bahia"), + americaBahiaBanderas(value: "america/bahia_banderas"), + americaBarbados(value: "america/barbados"), + americaBelem(value: "america/belem"), + americaBelize(value: "america/belize"), + americaBlancSablon(value: "america/blanc-sablon"), + americaBoaVista(value: "america/boa_vista"), + americaBogota(value: "america/bogota"), + americaBoise(value: "america/boise"), + americaCambridgeBay(value: "america/cambridge_bay"), + americaCampoGrande(value: "america/campo_grande"), + americaCancun(value: "america/cancun"), + americaCaracas(value: "america/caracas"), + americaCayenne(value: "america/cayenne"), + americaCayman(value: "america/cayman"), + americaChicago(value: "america/chicago"), + americaChihuahua(value: "america/chihuahua"), + americaCiudadJuarez(value: "america/ciudad_juarez"), + americaCostaRica(value: "america/costa_rica"), + americaCoyhaique(value: "america/coyhaique"), + americaCreston(value: "america/creston"), + americaCuiaba(value: "america/cuiaba"), + americaCuracao(value: "america/curacao"), + americaDanmarkshavn(value: "america/danmarkshavn"), + americaDawson(value: "america/dawson"), + americaDawsonCreek(value: "america/dawson_creek"), + americaDenver(value: "america/denver"), + americaDetroit(value: "america/detroit"), + americaDominica(value: "america/dominica"), + americaEdmonton(value: "america/edmonton"), + americaEirunepe(value: "america/eirunepe"), + americaElSalvador(value: "america/el_salvador"), + americaFortNelson(value: "america/fort_nelson"), + americaFortaleza(value: "america/fortaleza"), + americaGlaceBay(value: "america/glace_bay"), + americaGooseBay(value: "america/goose_bay"), + americaGrandTurk(value: "america/grand_turk"), + americaGrenada(value: "america/grenada"), + americaGuadeloupe(value: "america/guadeloupe"), + americaGuatemala(value: "america/guatemala"), + americaGuayaquil(value: "america/guayaquil"), + americaGuyana(value: "america/guyana"), + americaHalifax(value: "america/halifax"), + americaHavana(value: "america/havana"), + americaHermosillo(value: "america/hermosillo"), + americaIndianaIndianapolis(value: "america/indiana/indianapolis"), + americaIndianaKnox(value: "america/indiana/knox"), + americaIndianaMarengo(value: "america/indiana/marengo"), + americaIndianaPetersburg(value: "america/indiana/petersburg"), + americaIndianaTellCity(value: "america/indiana/tell_city"), + americaIndianaVevay(value: "america/indiana/vevay"), + americaIndianaVincennes(value: "america/indiana/vincennes"), + americaIndianaWinamac(value: "america/indiana/winamac"), + americaInuvik(value: "america/inuvik"), + americaIqaluit(value: "america/iqaluit"), + americaJamaica(value: "america/jamaica"), + americaJuneau(value: "america/juneau"), + americaKentuckyLouisville(value: "america/kentucky/louisville"), + americaKentuckyMonticello(value: "america/kentucky/monticello"), + americaKralendijk(value: "america/kralendijk"), + americaLaPaz(value: "america/la_paz"), + americaLima(value: "america/lima"), + americaLosAngeles(value: "america/los_angeles"), + americaLowerPrinces(value: "america/lower_princes"), + americaMaceio(value: "america/maceio"), + americaManagua(value: "america/managua"), + americaManaus(value: "america/manaus"), + americaMarigot(value: "america/marigot"), + americaMartinique(value: "america/martinique"), + americaMatamoros(value: "america/matamoros"), + americaMazatlan(value: "america/mazatlan"), + americaMenominee(value: "america/menominee"), + americaMerida(value: "america/merida"), + americaMetlakatla(value: "america/metlakatla"), + americaMexicoCity(value: "america/mexico_city"), + americaMiquelon(value: "america/miquelon"), + americaMoncton(value: "america/moncton"), + americaMonterrey(value: "america/monterrey"), + americaMontevideo(value: "america/montevideo"), + americaMontserrat(value: "america/montserrat"), + americaNassau(value: "america/nassau"), + americaNewYork(value: "america/new_york"), + americaNome(value: "america/nome"), + americaNoronha(value: "america/noronha"), + americaNorthDakotaBeulah(value: "america/north_dakota/beulah"), + americaNorthDakotaCenter(value: "america/north_dakota/center"), + americaNorthDakotaNewSalem(value: "america/north_dakota/new_salem"), + americaNuuk(value: "america/nuuk"), + americaOjinaga(value: "america/ojinaga"), + americaPanama(value: "america/panama"), + americaParamaribo(value: "america/paramaribo"), + americaPhoenix(value: "america/phoenix"), + americaPortAuPrince(value: "america/port-au-prince"), + americaPortOfSpain(value: "america/port_of_spain"), + americaPortoVelho(value: "america/porto_velho"), + americaPuertoRico(value: "america/puerto_rico"), + americaPuntaArenas(value: "america/punta_arenas"), + americaRankinInlet(value: "america/rankin_inlet"), + americaRecife(value: "america/recife"), + americaRegina(value: "america/regina"), + americaResolute(value: "america/resolute"), + americaRioBranco(value: "america/rio_branco"), + americaSantarem(value: "america/santarem"), + americaSantiago(value: "america/santiago"), + americaSantoDomingo(value: "america/santo_domingo"), + americaSaoPaulo(value: "america/sao_paulo"), + americaScoresbysund(value: "america/scoresbysund"), + americaSitka(value: "america/sitka"), + americaStBarthelemy(value: "america/st_barthelemy"), + americaStJohns(value: "america/st_johns"), + americaStKitts(value: "america/st_kitts"), + americaStLucia(value: "america/st_lucia"), + americaStThomas(value: "america/st_thomas"), + americaStVincent(value: "america/st_vincent"), + americaSwiftCurrent(value: "america/swift_current"), + americaTegucigalpa(value: "america/tegucigalpa"), + americaThule(value: "america/thule"), + americaTijuana(value: "america/tijuana"), + americaToronto(value: "america/toronto"), + americaTortola(value: "america/tortola"), + americaVancouver(value: "america/vancouver"), + americaWhitehorse(value: "america/whitehorse"), + americaWinnipeg(value: "america/winnipeg"), + americaYakutat(value: "america/yakutat"), + antarcticaCasey(value: "antarctica/casey"), + antarcticaDavis(value: "antarctica/davis"), + antarcticaDumontdurville(value: "antarctica/dumontdurville"), + antarcticaMacquarie(value: "antarctica/macquarie"), + antarcticaMawson(value: "antarctica/mawson"), + antarcticaMcmurdo(value: "antarctica/mcmurdo"), + antarcticaPalmer(value: "antarctica/palmer"), + antarcticaRothera(value: "antarctica/rothera"), + antarcticaSyowa(value: "antarctica/syowa"), + antarcticaTroll(value: "antarctica/troll"), + antarcticaVostok(value: "antarctica/vostok"), + arcticLongyearbyen(value: "arctic/longyearbyen"), + asiaAden(value: "asia/aden"), + asiaAlmaty(value: "asia/almaty"), + asiaAmman(value: "asia/amman"), + asiaAnadyr(value: "asia/anadyr"), + asiaAqtau(value: "asia/aqtau"), + asiaAqtobe(value: "asia/aqtobe"), + asiaAshgabat(value: "asia/ashgabat"), + asiaAtyrau(value: "asia/atyrau"), + asiaBaghdad(value: "asia/baghdad"), + asiaBahrain(value: "asia/bahrain"), + asiaBaku(value: "asia/baku"), + asiaBangkok(value: "asia/bangkok"), + asiaBarnaul(value: "asia/barnaul"), + asiaBeirut(value: "asia/beirut"), + asiaBishkek(value: "asia/bishkek"), + asiaBrunei(value: "asia/brunei"), + asiaChita(value: "asia/chita"), + asiaColombo(value: "asia/colombo"), + asiaDamascus(value: "asia/damascus"), + asiaDhaka(value: "asia/dhaka"), + asiaDili(value: "asia/dili"), + asiaDubai(value: "asia/dubai"), + asiaDushanbe(value: "asia/dushanbe"), + asiaFamagusta(value: "asia/famagusta"), + asiaGaza(value: "asia/gaza"), + asiaHebron(value: "asia/hebron"), + asiaHoChiMinh(value: "asia/ho_chi_minh"), + asiaHongKong(value: "asia/hong_kong"), + asiaHovd(value: "asia/hovd"), + asiaIrkutsk(value: "asia/irkutsk"), + asiaJakarta(value: "asia/jakarta"), + asiaJayapura(value: "asia/jayapura"), + asiaJerusalem(value: "asia/jerusalem"), + asiaKabul(value: "asia/kabul"), + asiaKamchatka(value: "asia/kamchatka"), + asiaKarachi(value: "asia/karachi"), + asiaKathmandu(value: "asia/kathmandu"), + asiaKhandyga(value: "asia/khandyga"), + asiaKolkata(value: "asia/kolkata"), + asiaKrasnoyarsk(value: "asia/krasnoyarsk"), + asiaKualaLumpur(value: "asia/kuala_lumpur"), + asiaKuching(value: "asia/kuching"), + asiaKuwait(value: "asia/kuwait"), + asiaMacau(value: "asia/macau"), + asiaMagadan(value: "asia/magadan"), + asiaMakassar(value: "asia/makassar"), + asiaManila(value: "asia/manila"), + asiaMuscat(value: "asia/muscat"), + asiaNicosia(value: "asia/nicosia"), + asiaNovokuznetsk(value: "asia/novokuznetsk"), + asiaNovosibirsk(value: "asia/novosibirsk"), + asiaOmsk(value: "asia/omsk"), + asiaOral(value: "asia/oral"), + asiaPhnomPenh(value: "asia/phnom_penh"), + asiaPontianak(value: "asia/pontianak"), + asiaPyongyang(value: "asia/pyongyang"), + asiaQatar(value: "asia/qatar"), + asiaQostanay(value: "asia/qostanay"), + asiaQyzylorda(value: "asia/qyzylorda"), + asiaRiyadh(value: "asia/riyadh"), + asiaSakhalin(value: "asia/sakhalin"), + asiaSamarkand(value: "asia/samarkand"), + asiaSeoul(value: "asia/seoul"), + asiaShanghai(value: "asia/shanghai"), + asiaSingapore(value: "asia/singapore"), + asiaSrednekolymsk(value: "asia/srednekolymsk"), + asiaTaipei(value: "asia/taipei"), + asiaTashkent(value: "asia/tashkent"), + asiaTbilisi(value: "asia/tbilisi"), + asiaTehran(value: "asia/tehran"), + asiaThimphu(value: "asia/thimphu"), + asiaTokyo(value: "asia/tokyo"), + asiaTomsk(value: "asia/tomsk"), + asiaUlaanbaatar(value: "asia/ulaanbaatar"), + asiaUrumqi(value: "asia/urumqi"), + asiaUstNera(value: "asia/ust-nera"), + asiaVientiane(value: "asia/vientiane"), + asiaVladivostok(value: "asia/vladivostok"), + asiaYakutsk(value: "asia/yakutsk"), + asiaYangon(value: "asia/yangon"), + asiaYekaterinburg(value: "asia/yekaterinburg"), + asiaYerevan(value: "asia/yerevan"), + atlanticAzores(value: "atlantic/azores"), + atlanticBermuda(value: "atlantic/bermuda"), + atlanticCanary(value: "atlantic/canary"), + atlanticCapeVerde(value: "atlantic/cape_verde"), + atlanticFaroe(value: "atlantic/faroe"), + atlanticMadeira(value: "atlantic/madeira"), + atlanticReykjavik(value: "atlantic/reykjavik"), + atlanticSouthGeorgia(value: "atlantic/south_georgia"), + atlanticStHelena(value: "atlantic/st_helena"), + atlanticStanley(value: "atlantic/stanley"), + australiaAdelaide(value: "australia/adelaide"), + australiaBrisbane(value: "australia/brisbane"), + australiaBrokenHill(value: "australia/broken_hill"), + australiaDarwin(value: "australia/darwin"), + australiaEucla(value: "australia/eucla"), + australiaHobart(value: "australia/hobart"), + australiaLindeman(value: "australia/lindeman"), + australiaLordHowe(value: "australia/lord_howe"), + australiaMelbourne(value: "australia/melbourne"), + australiaPerth(value: "australia/perth"), + australiaSydney(value: "australia/sydney"), + europeAmsterdam(value: "europe/amsterdam"), + europeAndorra(value: "europe/andorra"), + europeAstrakhan(value: "europe/astrakhan"), + europeAthens(value: "europe/athens"), + europeBelgrade(value: "europe/belgrade"), + europeBerlin(value: "europe/berlin"), + europeBratislava(value: "europe/bratislava"), + europeBrussels(value: "europe/brussels"), + europeBucharest(value: "europe/bucharest"), + europeBudapest(value: "europe/budapest"), + europeBusingen(value: "europe/busingen"), + europeChisinau(value: "europe/chisinau"), + europeCopenhagen(value: "europe/copenhagen"), + europeDublin(value: "europe/dublin"), + europeGibraltar(value: "europe/gibraltar"), + europeGuernsey(value: "europe/guernsey"), + europeHelsinki(value: "europe/helsinki"), + europeIsleOfMan(value: "europe/isle_of_man"), + europeIstanbul(value: "europe/istanbul"), + europeJersey(value: "europe/jersey"), + europeKaliningrad(value: "europe/kaliningrad"), + europeKirov(value: "europe/kirov"), + europeKyiv(value: "europe/kyiv"), + europeLisbon(value: "europe/lisbon"), + europeLjubljana(value: "europe/ljubljana"), + europeLondon(value: "europe/london"), + europeLuxembourg(value: "europe/luxembourg"), + europeMadrid(value: "europe/madrid"), + europeMalta(value: "europe/malta"), + europeMariehamn(value: "europe/mariehamn"), + europeMinsk(value: "europe/minsk"), + europeMonaco(value: "europe/monaco"), + europeMoscow(value: "europe/moscow"), + europeOslo(value: "europe/oslo"), + europeParis(value: "europe/paris"), + europePodgorica(value: "europe/podgorica"), + europePrague(value: "europe/prague"), + europeRiga(value: "europe/riga"), + europeRome(value: "europe/rome"), + europeSamara(value: "europe/samara"), + europeSanMarino(value: "europe/san_marino"), + europeSarajevo(value: "europe/sarajevo"), + europeSaratov(value: "europe/saratov"), + europeSimferopol(value: "europe/simferopol"), + europeSkopje(value: "europe/skopje"), + europeSofia(value: "europe/sofia"), + europeStockholm(value: "europe/stockholm"), + europeTallinn(value: "europe/tallinn"), + europeTirane(value: "europe/tirane"), + europeUlyanovsk(value: "europe/ulyanovsk"), + europeVaduz(value: "europe/vaduz"), + europeVatican(value: "europe/vatican"), + europeVienna(value: "europe/vienna"), + europeVilnius(value: "europe/vilnius"), + europeVolgograd(value: "europe/volgograd"), + europeWarsaw(value: "europe/warsaw"), + europeZagreb(value: "europe/zagreb"), + europeZurich(value: "europe/zurich"), + indianAntananarivo(value: "indian/antananarivo"), + indianChagos(value: "indian/chagos"), + indianChristmas(value: "indian/christmas"), + indianCocos(value: "indian/cocos"), + indianComoro(value: "indian/comoro"), + indianKerguelen(value: "indian/kerguelen"), + indianMahe(value: "indian/mahe"), + indianMaldives(value: "indian/maldives"), + indianMauritius(value: "indian/mauritius"), + indianMayotte(value: "indian/mayotte"), + indianReunion(value: "indian/reunion"), + pacificApia(value: "pacific/apia"), + pacificAuckland(value: "pacific/auckland"), + pacificBougainville(value: "pacific/bougainville"), + pacificChatham(value: "pacific/chatham"), + pacificChuuk(value: "pacific/chuuk"), + pacificEaster(value: "pacific/easter"), + pacificEfate(value: "pacific/efate"), + pacificFakaofo(value: "pacific/fakaofo"), + pacificFiji(value: "pacific/fiji"), + pacificFunafuti(value: "pacific/funafuti"), + pacificGalapagos(value: "pacific/galapagos"), + pacificGambier(value: "pacific/gambier"), + pacificGuadalcanal(value: "pacific/guadalcanal"), + pacificGuam(value: "pacific/guam"), + pacificHonolulu(value: "pacific/honolulu"), + pacificKanton(value: "pacific/kanton"), + pacificKiritimati(value: "pacific/kiritimati"), + pacificKosrae(value: "pacific/kosrae"), + pacificKwajalein(value: "pacific/kwajalein"), + pacificMajuro(value: "pacific/majuro"), + pacificMarquesas(value: "pacific/marquesas"), + pacificMidway(value: "pacific/midway"), + pacificNauru(value: "pacific/nauru"), + pacificNiue(value: "pacific/niue"), + pacificNorfolk(value: "pacific/norfolk"), + pacificNoumea(value: "pacific/noumea"), + pacificPagoPago(value: "pacific/pago_pago"), + pacificPalau(value: "pacific/palau"), + pacificPitcairn(value: "pacific/pitcairn"), + pacificPohnpei(value: "pacific/pohnpei"), + pacificPortMoresby(value: "pacific/port_moresby"), + pacificRarotonga(value: "pacific/rarotonga"), + pacificSaipan(value: "pacific/saipan"), + pacificTahiti(value: "pacific/tahiti"), + pacificTarawa(value: "pacific/tarawa"), + pacificTongatapu(value: "pacific/tongatapu"), + pacificWake(value: "pacific/wake"), + pacificWallis(value: "pacific/wallis"), + utc(value: "utc"); const Timezone({required this.value}); diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 344a8770..e1274375 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -20,8 +20,9 @@ class AlgoArgon2 implements Model { required this.timeCost, required this.threads, }); - - factory AlgoArgon2.fromMap(Map map) { + factory AlgoArgon2.fromMap( + Map map, + ) { return AlgoArgon2( type: map['type'].toString(), memoryCost: map['memoryCost'], diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 9909265e..27992237 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -8,8 +8,9 @@ class AlgoBcrypt implements Model { AlgoBcrypt({ required this.type, }); - - factory AlgoBcrypt.fromMap(Map map) { + factory AlgoBcrypt.fromMap( + Map map, + ) { return AlgoBcrypt( type: map['type'].toString(), ); diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 746fbd52..de131b77 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -8,8 +8,9 @@ class AlgoMd5 implements Model { AlgoMd5({ required this.type, }); - - factory AlgoMd5.fromMap(Map map) { + factory AlgoMd5.fromMap( + Map map, + ) { return AlgoMd5( type: map['type'].toString(), ); diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index cab45e49..f189e140 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -8,8 +8,9 @@ class AlgoPhpass implements Model { AlgoPhpass({ required this.type, }); - - factory AlgoPhpass.fromMap(Map map) { + factory AlgoPhpass.fromMap( + Map map, + ) { return AlgoPhpass( type: map['type'].toString(), ); diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index a1648843..b62a31f6 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -24,8 +24,9 @@ class AlgoScrypt implements Model { required this.costParallel, required this.length, }); - - factory AlgoScrypt.fromMap(Map map) { + factory AlgoScrypt.fromMap( + Map map, + ) { return AlgoScrypt( type: map['type'].toString(), costCpu: map['costCpu'], diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 33ef4a6f..0fa9ae47 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -20,8 +20,9 @@ class AlgoScryptModified implements Model { required this.saltSeparator, required this.signerKey, }); - - factory AlgoScryptModified.fromMap(Map map) { + factory AlgoScryptModified.fromMap( + Map map, + ) { return AlgoScryptModified( type: map['type'].toString(), salt: map['salt'].toString(), diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 4984df75..b1cb54cc 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -8,8 +8,9 @@ class AlgoSha implements Model { AlgoSha({ required this.type, }); - - factory AlgoSha.fromMap(Map map) { + factory AlgoSha.fromMap( + Map map, + ) { return AlgoSha( type: map['type'].toString(), ); diff --git a/lib/src/models/app_installation.dart b/lib/src/models/app_installation.dart index 3ed121ec..47c742ab 100644 --- a/lib/src/models/app_installation.dart +++ b/lib/src/models/app_installation.dart @@ -21,7 +21,7 @@ class AppInstallation implements Model { final List scopes; /// Authorization details granted to the application. Rich authorization request (RFC 9396) style entries; the Appwrite Console stores authorized project IDs here. - final Map authorizationDetails; + final List authorizationDetails; /// ID of the user who created the installation. final String createdById; @@ -44,8 +44,9 @@ class AppInstallation implements Model { required this.createdByName, this.lastAccessedAt, }); - - factory AppInstallation.fromMap(Map map) { + factory AppInstallation.fromMap( + Map map, + ) { return AppInstallation( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), @@ -53,7 +54,7 @@ class AppInstallation implements Model { appId: map['appId'].toString(), teamId: map['teamId'].toString(), scopes: List.from(map['scopes'] ?? []), - authorizationDetails: map['authorizationDetails'], + authorizationDetails: List.from(map['authorizationDetails'] ?? []), createdById: map['createdById'].toString(), createdByName: map['createdByName'].toString(), lastAccessedAt: map['lastAccessedAt']?.toString(), diff --git a/lib/src/models/app_installation_list.dart b/lib/src/models/app_installation_list.dart index c55f831f..2902bf06 100644 --- a/lib/src/models/app_installation_list.dart +++ b/lib/src/models/app_installation_list.dart @@ -12,12 +12,14 @@ class AppInstallationList implements Model { required this.total, required this.installations, }); - - factory AppInstallationList.fromMap(Map map) { + factory AppInstallationList.fromMap( + Map map, + ) { return AppInstallationList( total: map['total'], installations: List.from( - map['installations'].map((p) => AppInstallation.fromMap(p))), + map['installations'].map((p) => AppInstallation.fromMap(p)), + ), ); } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index ec3c41be..5696d1aa 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -12,8 +12,9 @@ class Continent implements Model { required this.name, required this.code, }); - - factory Continent.fromMap(Map map) { + factory Continent.fromMap( + Map map, + ) { return Continent( name: map['name'].toString(), code: map['code'].toString(), diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index df28f04b..ca2cbcfe 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -12,12 +12,14 @@ class ContinentList implements Model { required this.total, required this.continents, }); - - factory ContinentList.fromMap(Map map) { + factory ContinentList.fromMap( + Map map, + ) { return ContinentList( total: map['total'], continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), + map['continents'].map((p) => Continent.fromMap(p)), + ), ); } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index 3bcbb76d..5a2aaa1a 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -12,8 +12,9 @@ class Country implements Model { required this.name, required this.code, }); - - factory Country.fromMap(Map map) { + factory Country.fromMap( + Map map, + ) { return Country( name: map['name'].toString(), code: map['code'].toString(), diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 79cb1256..9c1b4f7b 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -12,12 +12,14 @@ class CountryList implements Model { required this.total, required this.countries, }); - - factory CountryList.fromMap(Map map) { + factory CountryList.fromMap( + Map map, + ) { return CountryList( total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), + countries: List.from( + map['countries'].map((p) => Country.fromMap(p)), + ), ); } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index f2b18093..1b6362a0 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -32,8 +32,9 @@ class Currency implements Model { required this.code, required this.namePlural, }); - - factory Currency.fromMap(Map map) { + factory Currency.fromMap( + Map map, + ) { return Currency( symbol: map['symbol'].toString(), name: map['name'].toString(), diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index 6c39ae2e..beb1abc1 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -12,12 +12,14 @@ class CurrencyList implements Model { required this.total, required this.currencies, }); - - factory CurrencyList.fromMap(Map map) { + factory CurrencyList.fromMap( + Map map, + ) { return CurrencyList( total: map['total'], currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), + map['currencies'].map((p) => Currency.fromMap(p)), + ), ); } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index be08d599..6886acd0 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -35,8 +35,9 @@ class Document implements Model { required this.$permissions, required this.data, }); - - factory Document.fromMap(Map map) { + factory Document.fromMap( + Map map, + ) { return Document( $id: map['\$id'].toString(), $sequence: map['\$sequence'].toString(), diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 76a07309..c9e020a4 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -12,12 +12,14 @@ class DocumentList implements Model { required this.total, required this.documents, }); - - factory DocumentList.fromMap(Map map) { + factory DocumentList.fromMap( + Map map, + ) { return DocumentList( total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), + documents: List.from( + map['documents'].map((p) => Document.fromMap(p)), + ), ); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 3629e1d6..2b07213b 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -14,16 +14,19 @@ class Execution implements Model { /// Execution roles. final List $permissions; - /// Function ID. - final String functionId; + /// Function or site ID. + final String resourceId; - /// Function's deployment ID used to create the execution. + /// Execution resource type. + final enums.ExecutionResourceType resourceType; + + /// Deployment ID used to create the execution. final String deploymentId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + /// The trigger that caused the resource to execute. Possible values can be: `http`, `schedule`, or `event`. final enums.ExecutionTrigger trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + /// The status of the resource execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. final enums.ExecutionStatus status; /// HTTP request method type. @@ -44,10 +47,10 @@ class Execution implements Model { /// 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. + /// Resource 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. + /// Resource 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; /// Resource(function/site) execution duration in seconds. @@ -61,7 +64,8 @@ class Execution implements Model { required this.$createdAt, required this.$updatedAt, required this.$permissions, - required this.functionId, + required this.resourceId, + required this.resourceType, required this.deploymentId, required this.trigger, required this.status, @@ -76,27 +80,35 @@ class Execution implements Model { required this.duration, this.scheduledAt, }); - - factory Execution.fromMap(Map map) { + factory Execution.fromMap( + Map map, + ) { return Execution( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), $updatedAt: map['\$updatedAt'].toString(), $permissions: List.from(map['\$permissions'] ?? []), - functionId: map['functionId'].toString(), + resourceId: map['resourceId'].toString(), + resourceType: enums.ExecutionResourceType.values.firstWhere( + (e) => e.value == map['resourceType'], + ), deploymentId: map['deploymentId'].toString(), - trigger: enums.ExecutionTrigger.values - .firstWhere((e) => e.value == map['trigger']), - status: enums.ExecutionStatus.values - .firstWhere((e) => e.value == map['status']), + trigger: enums.ExecutionTrigger.values.firstWhere( + (e) => e.value == map['trigger'], + ), + status: enums.ExecutionStatus.values.firstWhere( + (e) => e.value == map['status'], + ), requestMethod: map['requestMethod'].toString(), requestPath: map['requestPath'].toString(), requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), + map['requestHeaders'].map((p) => Headers.fromMap(p)), + ), responseStatusCode: map['responseStatusCode'], responseBody: map['responseBody'].toString(), responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), + map['responseHeaders'].map((p) => Headers.fromMap(p)), + ), logs: map['logs'].toString(), errors: map['errors'].toString(), duration: map['duration'].toDouble(), @@ -111,7 +123,8 @@ class Execution implements Model { "\$createdAt": $createdAt, "\$updatedAt": $updatedAt, "\$permissions": $permissions, - "functionId": functionId, + "resourceId": resourceId, + "resourceType": resourceType.value, "deploymentId": deploymentId, "trigger": trigger.value, "status": status.value, diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 63c2ad7e..c1d911ef 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -12,12 +12,14 @@ class ExecutionList implements Model { required this.total, required this.executions, }); - - factory ExecutionList.fromMap(Map map) { + factory ExecutionList.fromMap( + Map map, + ) { return ExecutionList( total: map['total'], executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), + map['executions'].map((p) => Execution.fromMap(p)), + ), ); } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 91c5e945..393c91a6 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -68,8 +68,9 @@ class File implements Model { required this.encryption, required this.compression, }); - - factory File.fromMap(Map map) { + factory File.fromMap( + Map map, + ) { return File( $id: map['\$id'].toString(), bucketId: map['bucketId'].toString(), diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 1157554a..7df9e94e 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -12,11 +12,14 @@ class FileList implements Model { required this.total, required this.files, }); - - factory FileList.fromMap(Map map) { + factory FileList.fromMap( + Map map, + ) { return FileList( total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), + files: List.from( + map['files'].map((p) => File.fromMap(p)), + ), ); } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index fa054420..4993b177 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -12,8 +12,9 @@ class Headers implements Model { required this.name, required this.value, }); - - factory Headers.fromMap(Map map) { + factory Headers.fromMap( + Map map, + ) { return Headers( name: map['name'].toString(), value: map['value'].toString(), diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index cc659043..2f32c7f9 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -44,8 +44,9 @@ class Identity implements Model { required this.providerAccessTokenExpiry, required this.providerRefreshToken, }); - - factory Identity.fromMap(Map map) { + factory Identity.fromMap( + Map map, + ) { return Identity( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index a5d39ea0..81442c4e 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -12,12 +12,14 @@ class IdentityList implements Model { required this.total, required this.identities, }); - - factory IdentityList.fromMap(Map map) { + factory IdentityList.fromMap( + Map map, + ) { return IdentityList( total: map['total'], identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), + map['identities'].map((p) => Identity.fromMap(p)), + ), ); } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index cda66c70..a7c8e671 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -8,8 +8,9 @@ class Jwt implements Model { Jwt({ required this.jwt, }); - - factory Jwt.fromMap(Map map) { + factory Jwt.fromMap( + Map map, + ) { return Jwt( jwt: map['jwt'].toString(), ); diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 87dc3606..d4bc2020 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -16,8 +16,9 @@ class Language implements Model { required this.code, required this.nativeName, }); - - factory Language.fromMap(Map map) { + factory Language.fromMap( + Map map, + ) { return Language( name: map['name'].toString(), code: map['code'].toString(), diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 6198d61e..c25345b9 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -12,12 +12,14 @@ class LanguageList implements Model { required this.total, required this.languages, }); - - factory LanguageList.fromMap(Map map) { + factory LanguageList.fromMap( + Map map, + ) { return LanguageList( total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), + languages: List.from( + map['languages'].map((p) => Language.fromMap(p)), + ), ); } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index c29b9e25..8bb3715a 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -76,8 +76,9 @@ class Locale implements Model { this.connectionUsageType, this.connectionOrganization, }); - - factory Locale.fromMap(Map map) { + factory Locale.fromMap( + Map map, + ) { return Locale( ip: map['ip'].toString(), countryCode: map['countryCode'].toString(), diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 21405aff..6f1cbe09 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -12,8 +12,9 @@ class LocaleCode implements Model { required this.code, required this.name, }); - - factory LocaleCode.fromMap(Map map) { + factory LocaleCode.fromMap( + Map map, + ) { return LocaleCode( code: map['code'].toString(), name: map['name'].toString(), diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 202355a4..4a5606b9 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -12,12 +12,14 @@ class LocaleCodeList implements Model { required this.total, required this.localeCodes, }); - - factory LocaleCodeList.fromMap(Map map) { + factory LocaleCodeList.fromMap( + Map map, + ) { return LocaleCodeList( total: map['total'], localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + map['localeCodes'].map((p) => LocaleCode.fromMap(p)), + ), ); } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index d754130d..296fe5f8 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -92,8 +92,9 @@ class Log implements Model { required this.countryCode, required this.countryName, }); - - factory Log.fromMap(Map map) { + factory Log.fromMap( + Map map, + ) { return Log( event: map['event'].toString(), userId: map['userId'].toString(), diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 3494b111..07828c75 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -12,11 +12,14 @@ class LogList implements Model { required this.total, required this.logs, }); - - factory LogList.fromMap(Map map) { + factory LogList.fromMap( + Map map, + ) { return LogList( total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + logs: List.from( + map['logs'].map((p) => Log.fromMap(p)), + ), ); } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 4d8a2f9b..e34a2320 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -64,8 +64,9 @@ class Membership implements Model { required this.userAccessedAt, required this.roles, }); - - factory Membership.fromMap(Map map) { + factory Membership.fromMap( + Map map, + ) { return Membership( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index cc664c9f..4a1c4e0e 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -12,12 +12,14 @@ class MembershipList implements Model { required this.total, required this.memberships, }); - - factory MembershipList.fromMap(Map map) { + factory MembershipList.fromMap( + Map map, + ) { return MembershipList( total: map['total'], memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), + map['memberships'].map((p) => Membership.fromMap(p)), + ), ); } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index fa385541..3c4f7ac7 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -20,8 +20,9 @@ class MfaChallenge implements Model { required this.userId, required this.expire, }); - - factory MfaChallenge.fromMap(Map map) { + factory MfaChallenge.fromMap( + Map map, + ) { return MfaChallenge( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index 2777de7f..9344e198 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -14,19 +14,25 @@ class MfaFactors implements Model { /// Can recovery code be used for MFA challenge for this account. final bool recoveryCode; + /// Can custom factor be used for MFA challenge for this account. + final bool custom; + MfaFactors({ required this.totp, required this.phone, required this.email, required this.recoveryCode, + required this.custom, }); - - factory MfaFactors.fromMap(Map map) { + factory MfaFactors.fromMap( + Map map, + ) { return MfaFactors( totp: map['totp'], phone: map['phone'], email: map['email'], recoveryCode: map['recoveryCode'], + custom: map['custom'], ); } @@ -37,6 +43,7 @@ class MfaFactors implements Model { "phone": phone, "email": email, "recoveryCode": recoveryCode, + "custom": custom, }; } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 864a5db8..3693487f 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -8,8 +8,9 @@ class MfaRecoveryCodes implements Model { MfaRecoveryCodes({ required this.recoveryCodes, }); - - factory MfaRecoveryCodes.fromMap(Map map) { + factory MfaRecoveryCodes.fromMap( + Map map, + ) { return MfaRecoveryCodes( recoveryCodes: List.from(map['recoveryCodes'] ?? []), ); diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index fe5327fc..2901f8b4 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -12,8 +12,9 @@ class MfaType implements Model { required this.secret, required this.uri, }); - - factory MfaType.fromMap(Map map) { + factory MfaType.fromMap( + Map map, + ) { return MfaType( secret: map['secret'].toString(), uri: map['uri'].toString(), diff --git a/lib/src/models/oauth2_consent.dart b/lib/src/models/oauth2_consent.dart index 0f71fac2..409f872c 100644 --- a/lib/src/models/oauth2_consent.dart +++ b/lib/src/models/oauth2_consent.dart @@ -44,8 +44,9 @@ class Oauth2Consent implements Model { required this.authorizationDetails, required this.expire, }); - - factory Oauth2Consent.fromMap(Map map) { + factory Oauth2Consent.fromMap( + Map map, + ) { return Oauth2Consent( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/oauth2_consent_list.dart b/lib/src/models/oauth2_consent_list.dart index a5f355e1..852174f0 100644 --- a/lib/src/models/oauth2_consent_list.dart +++ b/lib/src/models/oauth2_consent_list.dart @@ -12,12 +12,14 @@ class Oauth2ConsentList implements Model { required this.total, required this.consents, }); - - factory Oauth2ConsentList.fromMap(Map map) { + factory Oauth2ConsentList.fromMap( + Map map, + ) { return Oauth2ConsentList( total: map['total'], consents: List.from( - map['consents'].map((p) => Oauth2Consent.fromMap(p))), + map['consents'].map((p) => Oauth2Consent.fromMap(p)), + ), ); } diff --git a/lib/src/models/oauth2_consent_token.dart b/lib/src/models/oauth2_consent_token.dart index adbee89f..86d935e5 100644 --- a/lib/src/models/oauth2_consent_token.dart +++ b/lib/src/models/oauth2_consent_token.dart @@ -48,8 +48,9 @@ class Oauth2ConsentToken implements Model { required this.authorizationDetails, required this.expire, }); - - factory Oauth2ConsentToken.fromMap(Map map) { + factory Oauth2ConsentToken.fromMap( + Map map, + ) { return Oauth2ConsentToken( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/oauth2_consent_token_list.dart b/lib/src/models/oauth2_consent_token_list.dart index cc5cdc16..a64e80b0 100644 --- a/lib/src/models/oauth2_consent_token_list.dart +++ b/lib/src/models/oauth2_consent_token_list.dart @@ -12,12 +12,14 @@ class Oauth2ConsentTokenList implements Model { required this.total, required this.tokens, }); - - factory Oauth2ConsentTokenList.fromMap(Map map) { + factory Oauth2ConsentTokenList.fromMap( + Map map, + ) { return Oauth2ConsentTokenList( total: map['total'], tokens: List.from( - map['tokens'].map((p) => Oauth2ConsentToken.fromMap(p))), + map['tokens'].map((p) => Oauth2ConsentToken.fromMap(p)), + ), ); } diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 60e2abd9..27c2f62d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -16,8 +16,9 @@ class Phone implements Model { required this.countryCode, required this.countryName, }); - - factory Phone.fromMap(Map map) { + factory Phone.fromMap( + Map map, + ) { return Phone( code: map['code'].toString(), countryCode: map['countryCode'].toString(), diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1a197fc7..0e0e8ae0 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -12,11 +12,14 @@ class PhoneList implements Model { required this.total, required this.phones, }); - - factory PhoneList.fromMap(Map map) { + factory PhoneList.fromMap( + Map map, + ) { return PhoneList( total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + phones: List.from( + map['phones'].map((p) => Phone.fromMap(p)), + ), ); } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3ca04118..992e6f92 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -7,8 +7,9 @@ class Preferences implements Model { Preferences({ required this.data, }); - - factory Preferences.fromMap(Map map) { + factory Preferences.fromMap( + Map map, + ) { return Preferences( data: map["data"] ?? map, ); diff --git a/lib/src/models/presence.dart b/lib/src/models/presence.dart index d31911de..4c1ac972 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -40,8 +40,9 @@ class Presence implements Model { this.expiresAt, this.metadata, }); - - factory Presence.fromMap(Map map) { + factory Presence.fromMap( + Map map, + ) { return Presence( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/presence_list.dart b/lib/src/models/presence_list.dart index 3d010b1c..fe011b7b 100644 --- a/lib/src/models/presence_list.dart +++ b/lib/src/models/presence_list.dart @@ -12,12 +12,14 @@ class PresenceList implements Model { required this.total, required this.presences, }); - - factory PresenceList.fromMap(Map map) { + factory PresenceList.fromMap( + Map map, + ) { return PresenceList( total: map['total'], - presences: - List.from(map['presences'].map((p) => Presence.fromMap(p))), + presences: List.from( + map['presences'].map((p) => Presence.fromMap(p)), + ), ); } diff --git a/lib/src/models/row.dart b/lib/src/models/row.dart index a825eab0..bbf94f42 100644 --- a/lib/src/models/row.dart +++ b/lib/src/models/row.dart @@ -35,8 +35,9 @@ class Row implements Model { required this.$permissions, required this.data, }); - - factory Row.fromMap(Map map) { + factory Row.fromMap( + Map map, + ) { return Row( $id: map['\$id'].toString(), $sequence: map['\$sequence'].toString(), diff --git a/lib/src/models/row_list.dart b/lib/src/models/row_list.dart index 5023c633..ca3c9f8c 100644 --- a/lib/src/models/row_list.dart +++ b/lib/src/models/row_list.dart @@ -12,11 +12,14 @@ class RowList implements Model { required this.total, required this.rows, }); - - factory RowList.fromMap(Map map) { + factory RowList.fromMap( + Map map, + ) { return RowList( total: map['total'], - rows: List.from(map['rows'].map((p) => Row.fromMap(p))), + rows: List.from( + map['rows'].map((p) => Row.fromMap(p)), + ), ); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 92e4034e..821f1fe0 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -120,8 +120,9 @@ class Session implements Model { required this.secret, required this.mfaUpdatedAt, }); - - factory Session.fromMap(Map map) { + factory Session.fromMap( + Map map, + ) { return Session( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index 4ea12394..e1650b89 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -12,12 +12,14 @@ class SessionList implements Model { required this.total, required this.sessions, }); - - factory SessionList.fromMap(Map map) { + factory SessionList.fromMap( + Map map, + ) { return SessionList( total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), + sessions: List.from( + map['sessions'].map((p) => Session.fromMap(p)), + ), ); } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 450aafd1..377ada24 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -40,14 +40,17 @@ class Subscriber implements Model { required this.topicId, required this.providerType, }); - - factory Subscriber.fromMap(Map map) { + 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']), + target: Target.fromMap( + map['target'], + ), userId: map['userId'].toString(), userName: map['userName'].toString(), topicId: map['topicId'].toString(), diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index c2e8c4dc..9b2b9cd2 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -40,8 +40,9 @@ class Target implements Model { required this.identifier, required this.expired, }); - - factory Target.fromMap(Map map) { + factory Target.fromMap( + Map map, + ) { return Target( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 91b888b9..59647c35 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -28,15 +28,18 @@ class Team implements Model { required this.total, required this.prefs, }); - - factory Team.fromMap(Map map) { + 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']), + prefs: Preferences.fromMap( + map['prefs'], + ), ); } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index e8f1c621..2a6a60a2 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -12,11 +12,14 @@ class TeamList implements Model { required this.total, required this.teams, }); - - factory TeamList.fromMap(Map map) { + factory TeamList.fromMap( + Map map, + ) { return TeamList( total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + teams: List.from( + map['teams'].map((p) => Team.fromMap(p)), + ), ); } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index b5ea87c8..fb75327f 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -28,8 +28,9 @@ class Token implements Model { required this.expire, required this.phrase, }); - - factory Token.fromMap(Map map) { + factory Token.fromMap( + Map map, + ) { return Token( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/transaction.dart b/lib/src/models/transaction.dart index b0606dd8..9e3c1099 100644 --- a/lib/src/models/transaction.dart +++ b/lib/src/models/transaction.dart @@ -28,8 +28,9 @@ class Transaction implements Model { required this.operations, required this.expiresAt, }); - - factory Transaction.fromMap(Map map) { + factory Transaction.fromMap( + Map map, + ) { return Transaction( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), diff --git a/lib/src/models/transaction_list.dart b/lib/src/models/transaction_list.dart index 7f321175..6e92d163 100644 --- a/lib/src/models/transaction_list.dart +++ b/lib/src/models/transaction_list.dart @@ -12,12 +12,14 @@ class TransactionList implements Model { required this.total, required this.transactions, }); - - factory TransactionList.fromMap(Map map) { + factory TransactionList.fromMap( + Map map, + ) { return TransactionList( total: map['total'], transactions: List.from( - map['transactions'].map((p) => Transaction.fromMap(p))), + map['transactions'].map((p) => Transaction.fromMap(p)), + ), ); } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5a6cad30..8650dfd5 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -108,8 +108,9 @@ class User implements Model { this.impersonator, this.impersonatorUserId, }); - - factory User.fromMap(Map map) { + factory User.fromMap( + Map map, + ) { return User( $id: map['\$id'].toString(), $createdAt: map['\$createdAt'].toString(), @@ -132,8 +133,12 @@ class User implements Model { emailIsCanonical: map['emailIsCanonical'], phoneVerification: map['phoneVerification'], mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + prefs: Preferences.fromMap( + map['prefs'], + ), + targets: List.from( + map['targets'].map((p) => Target.fromMap(p)), + ), accessedAt: map['accessedAt'].toString(), impersonator: map['impersonator'], impersonatorUserId: map['impersonatorUserId']?.toString(), diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index b0356111..e444cd0b 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -4,26 +4,14 @@ import 'package:flutter/foundation.dart'; class RealtimeResponse { final String type; // error, event, connected, response final Map data; - RealtimeResponse({ - required this.type, - required this.data, - }); - - RealtimeResponse copyWith({ - String? type, - Map? data, - }) { - return RealtimeResponse( - type: type ?? this.type, - data: data ?? this.data, - ); + RealtimeResponse({required this.type, required this.data}); + + RealtimeResponse copyWith({String? type, Map? data}) { + return RealtimeResponse(type: type ?? this.type, data: data ?? this.data); } Map toMap() { - return { - 'type': type, - 'data': data, - }; + return {'type': type, 'data': data}; } factory RealtimeResponse.fromMap(Map map) { diff --git a/pubspec.yaml b/pubspec.yaml index 98866f5c..ee810a5f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 25.4.0 +version: 25.5.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -13,16 +13,17 @@ platforms: web: windows: environment: - sdk: '>=2.17.0 <4.0.0' + sdk: '>=3.7.0 <4.0.0' + flutter: '>=3.29.0' dependencies: flutter: sdk: flutter cookie_jar: ^4.0.8 - device_info_plus: '>=11.5.0 <13.0.0' + device_info_plus: '>=11.5.0 <14.0.0' flutter_web_auth_2: ^5.0.0 http: '>=0.13.6 <2.0.0' - package_info_plus: '>=8.0.2 <10.0.0' + package_info_plus: '>=8.0.2 <11.0.0' path_provider: ^2.1.4 web_socket_channel: ^3.0.1 web: ^1.0.0 diff --git a/test/services/account_test.dart b/test/services/account_test.dart index 2752044f..00c1e68e 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -59,27 +67,27 @@ void main() { test('test method get()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.get(); expect(response, isA()); @@ -87,32 +95,32 @@ void main() { test('test method create()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.create( - userId: '', - email: 'email@example.com', - password: 'password', + userId: "", + email: "email@example.com", + password: "password", ); expect(response, isA()); }); @@ -123,9 +131,9 @@ void main() { 'consents': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listConsents(); expect(response, isA()); @@ -133,25 +141,25 @@ void main() { test('test method getConsent()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'appId': '5e5ea5c16897e', - 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'cimdUrl': "https://example.com/.well-known/client-metadata.json", 'scopes': [], 'resources': [], 'authorizationDetails': - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - 'expire': '2020-10-15T06:38:00.000+00:00', + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'expire': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getConsent( - consentId: '', + consentId: "", ); expect(response, isA()); }); @@ -159,12 +167,12 @@ void main() { test('test method deleteConsent()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteConsent( - consentId: '', + consentId: "", ); }); @@ -174,39 +182,39 @@ void main() { 'tokens': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listConsentTokens( - consentId: '', + consentId: "", ); expect(response, isA()); }); test('test method getConsentToken()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'consentId': '5e5ea5c16897e', - 'userId': '5e5ea5c16897e', - 'appId': '5e5ea5c16897e', - 'cimdUrl': 'https://example.com/.well-known/client-metadata.json', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'consentId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'cimdUrl': "https://example.com/.well-known/client-metadata.json", 'scopes': [], 'resources': [], 'authorizationDetails': - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - 'expire': '2020-10-15T06:38:00.000+00:00', + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'expire': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getConsentToken( - consentId: '', - tokenId: '', + consentId: "", + tokenId: "", ); expect(response, isA()); }); @@ -214,43 +222,43 @@ void main() { test('test method deleteConsentToken()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteConsentToken( - consentId: '', - tokenId: '', + consentId: "", + tokenId: "", ); }); test('test method updateEmail()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateEmail( - email: 'email@example.com', - password: 'password', + email: "email@example.com", + password: "password", ); expect(response, isA()); }); @@ -261,9 +269,9 @@ void main() { 'identities': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listIdentities(); expect(response, isA()); @@ -272,24 +280,24 @@ void main() { test('test method deleteIdentity()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteIdentity( - identityId: '', + identityId: "", ); }); test('test method createJWT()', () async { final Map data = { 'jwt': - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createJWT(); expect(response, isA()); @@ -301,9 +309,9 @@ void main() { 'logs': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listLogs(); expect(response, isA()); @@ -311,27 +319,27 @@ void main() { test('test method updateMFA()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMFA( mfa: true, @@ -341,14 +349,14 @@ void main() { test('test method createMfaAuthenticator()', () async { final Map data = { - 'secret': '[SHARED_SECRET]', + 'secret': "[SHARED_SECRET]", 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + "otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMfaAuthenticator( type: enums.AuthenticatorType.totp, @@ -358,14 +366,14 @@ void main() { test('test method createMFAAuthenticator()', () async { final Map data = { - 'secret': '[SHARED_SECRET]', + 'secret': "[SHARED_SECRET]", 'uri': - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + "otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMFAAuthenticator( type: enums.AuthenticatorType.totp, @@ -375,62 +383,62 @@ void main() { test('test method updateMfaAuthenticator()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMfaAuthenticator( type: enums.AuthenticatorType.totp, - otp: '', + otp: "", ); expect(response, isA()); }); test('test method updateMFAAuthenticator()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMFAAuthenticator( type: enums.AuthenticatorType.totp, - otp: '', + otp: "", ); expect(response, isA()); }); @@ -438,9 +446,9 @@ void main() { test('test method deleteMfaAuthenticator()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteMfaAuthenticator( type: enums.AuthenticatorType.totp, @@ -450,9 +458,9 @@ void main() { test('test method deleteMFAAuthenticator()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteMFAAuthenticator( type: enums.AuthenticatorType.totp, @@ -461,15 +469,15 @@ void main() { test('test method createMfaChallenge()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'expire': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMfaChallenge( factor: enums.AuthenticationFactor.email, @@ -479,15 +487,15 @@ void main() { test('test method createMFAChallenge()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'expire': '2020-10-15T06:38:00.000+00:00', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'expire': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMFAChallenge( factor: enums.AuthenticationFactor.email, @@ -497,88 +505,88 @@ void main() { test('test method updateMfaChallenge()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMfaChallenge( - challengeId: '', - otp: '', + challengeId: "", + otp: "", ); expect(response, isA()); }); test('test method updateMFAChallenge()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMFAChallenge( - challengeId: '', - otp: '', + challengeId: "", + otp: "", ); expect(response, isA()); }); @@ -589,11 +597,12 @@ void main() { 'phone': true, 'email': true, 'recoveryCode': true, + 'custom': true, }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listMfaFactors(); expect(response, isA()); @@ -605,11 +614,12 @@ void main() { 'phone': true, 'email': true, 'recoveryCode': true, + 'custom': true, }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listMFAFactors(); expect(response, isA()); @@ -620,9 +630,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getMfaRecoveryCodes(); expect(response, isA()); @@ -633,9 +643,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getMFARecoveryCodes(); expect(response, isA()); @@ -646,9 +656,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMfaRecoveryCodes(); expect(response, isA()); @@ -659,9 +669,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMFARecoveryCodes(); expect(response, isA()); @@ -672,9 +682,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMfaRecoveryCodes(); expect(response, isA()); @@ -685,9 +695,9 @@ void main() { 'recoveryCodes': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMFARecoveryCodes(); expect(response, isA()); @@ -695,91 +705,91 @@ void main() { test('test method updateName()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateName( - name: '', + name: "", ); expect(response, isA()); }); test('test method updatePassword()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePassword( - password: 'password', + password: "password", ); expect(response, isA()); }); test('test method updatePhone()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePhone( - phone: '+12065550100', - password: 'password', + phone: "+12065550100", + password: "password", ); expect(response, isA()); }); @@ -787,9 +797,9 @@ void main() { test('test method getPrefs()', () async { final Map data = {}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getPrefs(); expect(response, isA()); @@ -797,27 +807,27 @@ void main() { test('test method updatePrefs()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePrefs( prefs: {}, @@ -827,43 +837,43 @@ void main() { test('test method createRecovery()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createRecovery( - email: 'email@example.com', - url: 'https://example.com', + email: "email@example.com", + url: "https://example.com", ); expect(response, isA()); }); test('test method updateRecovery()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateRecovery( - userId: '', - secret: '', - password: 'password', + userId: "", + secret: "", + password: "password", ); expect(response, isA()); }); @@ -874,9 +884,9 @@ void main() { 'sessions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.listSessions(); expect(response, isA()); @@ -885,49 +895,49 @@ void main() { test('test method deleteSessions()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteSessions(); }); test('test method createAnonymousSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createAnonymousSession(); expect(response, isA()); @@ -935,96 +945,96 @@ void main() { test('test method createEmailPasswordSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createEmailPasswordSession( - email: 'email@example.com', - password: 'password', + email: "email@example.com", + password: "password", ); expect(response, isA()); }); test('test method updateMagicURLSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateMagicURLSession( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); test('test method createOAuth2Session()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final data = ''; + + when(client.webAuth(argThat(isNotNull))).thenAnswer((_) async => 'done'); final response = await account.createOAuth2Session( provider: enums.OAuthProvider.amazon, @@ -1034,174 +1044,174 @@ void main() { test('test method updatePhoneSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePhoneSession( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); test('test method createSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createSession( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); test('test method getSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await account.getSession( - sessionId: '', + sessionId: "", ); expect(response, isA()); }); test('test method updateSession()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5bb8c16897e', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'provider': 'email', - 'providerUid': 'user@example.com', - 'providerAccessToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'providerAccessTokenExpiry': '2020-10-15T06:38:00.000+00:00', - 'providerRefreshToken': 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - 'ip': '127.0.0.1', - 'osCode': 'Mac', - 'osName': 'Mac', - 'osVersion': 'Mac', - 'clientType': 'browser', - 'clientCode': 'CM', - 'clientName': 'Chrome Mobile iOS', - 'clientVersion': '84.0', - 'clientEngine': 'WebKit', - 'clientEngineVersion': '605.1.15', - 'deviceName': 'smartphone', - 'deviceBrand': 'Google', - 'deviceModel': 'Nexus 5', - 'countryCode': 'US', - 'countryName': 'United States', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", 'current': true, 'factors': [], - 'secret': '5e5bb8c16897e', - 'mfaUpdatedAt': '2020-10-15T06:38:00.000+00:00', + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateSession( - sessionId: '', + sessionId: "", ); expect(response, isA()); }); @@ -1209,38 +1219,38 @@ void main() { test('test method deleteSession()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deleteSession( - sessionId: '', + sessionId: "", ); }); test('test method updateStatus()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'John Doe', - 'registration': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", 'status': true, 'labels': [], - 'passwordUpdate': '2020-10-15T06:38:00.000+00:00', - 'email': 'john@appwrite.io', - 'phone': '+4930901820', + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", 'emailVerification': true, 'phoneVerification': true, 'mfa': true, 'prefs': {}, 'targets': [], - 'accessedAt': '2020-10-15T06:38:00.000+00:00', + 'accessedAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateStatus(); expect(response, isA()); @@ -1248,46 +1258,46 @@ void main() { test('test method createPushTarget()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "Apple iPhone 12", + 'userId': "259125845563242502", + 'providerType': "email", + 'identifier': "token", 'expired': true, }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createPushTarget( - targetId: '', - identifier: '', + targetId: "", + identifier: "", ); expect(response, isA()); }); test('test method updatePushTarget()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "Apple iPhone 12", + 'userId': "259125845563242502", + 'providerType': "email", + 'identifier': "token", 'expired': true, }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePushTarget( - targetId: '', - identifier: '', + targetId: "", + identifier: "", ); expect(response, isA()); }); @@ -1295,61 +1305,61 @@ void main() { test('test method deletePushTarget()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await account.deletePushTarget( - targetId: '', + targetId: "", ); }); test('test method createEmailToken()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createEmailToken( - userId: '', - email: 'email@example.com', + userId: "", + email: "email@example.com", ); expect(response, isA()); }); test('test method createMagicURLToken()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createMagicURLToken( - userId: '', - email: 'email@example.com', + userId: "", + email: "email@example.com", ); expect(response, isA()); }); test('test method createOAuth2Token()', () async { - when(client.webAuth( - argThat(isNotNull), - )).thenAnswer((_) async => 'done'); + final data = ''; + + when(client.webAuth(argThat(isNotNull))).thenAnswer((_) async => 'done'); final response = await account.createOAuth2Token( provider: enums.OAuthProvider.amazon, @@ -1359,120 +1369,120 @@ void main() { test('test method createPhoneToken()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createPhoneToken( - userId: '', - phone: '+12065550100', + userId: "", + phone: "+12065550100", ); expect(response, isA()); }); test('test method createEmailVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createEmailVerification( - url: 'https://example.com', + url: "https://example.com", ); expect(response, isA()); }); test('test method createVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createVerification( - url: 'https://example.com', + url: "https://example.com", ); expect(response, isA()); }); test('test method updateEmailVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateEmailVerification( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); test('test method updateVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updateVerification( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); test('test method createPhoneVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await account.createPhoneVerification(); expect(response, isA()); @@ -1480,21 +1490,21 @@ void main() { test('test method updatePhoneVerification()', () async { final Map data = { - '\$id': 'bb8ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c168bb8', - 'secret': '', - 'expire': '2020-10-15T06:38:00.000+00:00', - 'phrase': 'Golden Fox', + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await account.updatePhoneVerification( - userId: '', - secret: '', + userId: "", + secret: "", ); expect(response, isA()); }); diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 8d2c48fb..835e2951 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -60,9 +68,9 @@ void main() { test('test method getBrowser()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getBrowser( code: enums.Browser.avantBrowser, @@ -73,9 +81,9 @@ void main() { test('test method getCreditCard()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getCreditCard( code: enums.CreditCard.americanExpress, @@ -86,12 +94,12 @@ void main() { test('test method getFavicon()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getFavicon( - url: 'https://example.com', + url: "https://example.com", ); expect(response, isA()); }); @@ -99,9 +107,9 @@ void main() { test('test method getFlag()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getFlag( code: enums.Flag.afghanistan, @@ -112,12 +120,12 @@ void main() { test('test method getImage()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getImage( - url: 'https://example.com', + url: "https://example.com", ); expect(response, isA()); }); @@ -125,23 +133,34 @@ void main() { test('test method getInitials()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getInitials(); expect(response, isA()); }); + test('test method getPhoto()', () async { + final Uint8List data = Uint8List.fromList([]); + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.getPhoto(); + expect(response, isA()); + }); + test('test method getQR()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getQR( - text: '', + text: "", ); expect(response, isA()); }); @@ -149,12 +168,12 @@ void main() { test('test method getScreenshot()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await avatars.getScreenshot( - url: 'https://example.com', + url: "https://example.com", ); expect(response, isA()); }); diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index a3807093..d55be0c4 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,9 +71,9 @@ void main() { 'transactions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.listTransactions(); expect(response, isA()); @@ -73,17 +81,17 @@ void main() { test('test method createTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.createTransaction(); expect(response, isA()); @@ -91,40 +99,40 @@ void main() { test('test method getTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.getTransaction( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); test('test method updateTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.updateTransaction( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); @@ -132,31 +140,31 @@ void main() { test('test method deleteTransaction()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.deleteTransaction( - transactionId: '', + transactionId: "", ); }); test('test method createOperations()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.createOperations( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); @@ -167,36 +175,36 @@ void main() { 'documents': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.listDocuments( - databaseId: '', - collectionId: '', + databaseId: "", + collectionId: "", ); expect(response, isA()); }); test('test method createDocument()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.createDocument( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", data: {}, ); expect(response, isA()); @@ -204,69 +212,69 @@ void main() { test('test method getDocument()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.getDocument( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", ); expect(response, isA()); }); test('test method upsertDocument()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.upsertDocument( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", ); expect(response, isA()); }); test('test method updateDocument()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.updateDocument( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", ); expect(response, isA()); }); @@ -274,36 +282,36 @@ void main() { test('test method deleteDocument()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.deleteDocument( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", ); }); test('test method decrementDocumentAttribute()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.decrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", attribute: '', ); expect(response, isA()); @@ -311,23 +319,23 @@ void main() { test('test method incrementDocumentAttribute()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$collectionId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await databases.incrementDocumentAttribute( - databaseId: '', - collectionId: '', - documentId: '', + databaseId: "", + collectionId: "", + documentId: "", attribute: '', ); expect(response, isA()); diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index c6e50a50..aae489d9 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,75 +71,77 @@ void main() { 'executions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await functions.listExecutions( - functionId: '', + functionId: "", ); expect(response, isA()); }); test('test method createExecution()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', + 'resourceId': "5e5ea6g16897e", + 'resourceType': "functions", + 'deploymentId': "5e5ea5c16897e", + 'trigger': "http", + 'status': "processing", + 'requestMethod': "GET", + 'requestPath': "/articles?id=5", 'requestHeaders': [], 'responseStatusCode': 200, - 'responseBody': '', + 'responseBody': "", 'responseHeaders': [], - 'logs': '', - 'errors': '', + 'logs': "", + 'errors': "", 'duration': 0.4, }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await functions.createExecution( - functionId: '', + functionId: "", ); expect(response, isA()); }); test('test method getExecution()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'functionId': '5e5ea6g16897e', - 'deploymentId': '5e5ea5c16897e', - 'trigger': 'http', - 'status': 'processing', - 'requestMethod': 'GET', - 'requestPath': '/articles?id=5', + 'resourceId': "5e5ea6g16897e", + 'resourceType': "functions", + 'deploymentId': "5e5ea5c16897e", + 'trigger': "http", + 'status': "processing", + 'requestMethod': "GET", + 'requestPath': "/articles?id=5", 'requestHeaders': [], 'responseStatusCode': 200, - 'responseBody': '', + 'responseBody': "", 'responseHeaders': [], - 'logs': '', - 'errors': '', + 'logs': "", + 'errors': "", 'duration': 0.4, }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await functions.getExecution( - functionId: '', - executionId: '', + functionId: "", + executionId: "", ); expect(response, isA()); }); diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 84b7de1c..779767e3 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -60,9 +68,9 @@ void main() { test('test method query()', () async { final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await graphql.query( query: {}, @@ -72,9 +80,9 @@ void main() { test('test method mutation()', () async { final data = ''; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await graphql.mutation( query: {}, diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index f9f6489d..c9bb5236 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -59,18 +67,18 @@ void main() { test('test method get()', () async { final Map data = { - 'ip': '127.0.0.1', - 'countryCode': 'US', - 'country': 'United States', - 'continentCode': 'NA', - 'continent': 'North America', + 'ip': "127.0.0.1", + 'countryCode': "US", + 'country': "United States", + 'continentCode': "NA", + 'continent': "North America", 'eu': true, - 'currency': 'USD', + 'currency': "USD", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.get(); expect(response, isA()); @@ -82,9 +90,9 @@ void main() { 'localeCodes': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listCodes(); expect(response, isA()); @@ -96,9 +104,9 @@ void main() { 'continents': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listContinents(); expect(response, isA()); @@ -110,9 +118,9 @@ void main() { 'countries': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listCountries(); expect(response, isA()); @@ -124,9 +132,9 @@ void main() { 'countries': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listCountriesEU(); expect(response, isA()); @@ -138,9 +146,9 @@ void main() { 'phones': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listCountriesPhones(); expect(response, isA()); @@ -152,9 +160,9 @@ void main() { 'currencies': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listCurrencies(); expect(response, isA()); @@ -166,9 +174,9 @@ void main() { 'languages': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await locale.listLanguages(); expect(response, isA()); diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 0c938eff..823af01e 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -59,34 +67,34 @@ void main() { test('test method createSubscriber()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'targetId': '259125845563242502', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'targetId': "259125845563242502", 'target': { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'Apple iPhone 12', - 'userId': '259125845563242502', - 'providerType': 'email', - 'identifier': 'token', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "Apple iPhone 12", + 'userId': "259125845563242502", + 'providerType': "email", + 'identifier': "token", 'expired': true, }, - 'userId': '5e5ea5c16897e', - 'userName': 'Aegon Targaryen', - 'topicId': '259125845563242502', - 'providerType': 'email', + 'userId': "5e5ea5c16897e", + 'userName': "Aegon Targaryen", + 'topicId': "259125845563242502", + 'providerType': "email", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await messaging.createSubscriber( - topicId: '', - subscriberId: '', - targetId: '', + topicId: "", + subscriberId: "", + targetId: "", ); expect(response, isA()); }); @@ -94,13 +102,13 @@ void main() { test('test method deleteSubscriber()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await messaging.deleteSubscriber( - topicId: '', - subscriberId: '', + topicId: "", + subscriberId: "", ); }); }); diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart index 00455d84..a6ea2c70 100644 --- a/test/services/organization_test.dart +++ b/test/services/organization_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,9 +71,9 @@ void main() { 'installations': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await organization.listInstallations(); expect(response, isA()); @@ -73,69 +81,69 @@ void main() { test('test method createInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await organization.createInstallation( - appId: '', + appId: "", ); expect(response, isA()); }); test('test method getInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await organization.getInstallation( - installationId: '', + installationId: "", ); expect(response, isA()); }); test('test method updateInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await organization.updateInstallation( - installationId: '', + installationId: "", ); expect(response, isA()); }); @@ -143,12 +151,12 @@ void main() { test('test method deleteInstallation()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await organization.deleteInstallation( - installationId: '', + installationId: "", ); }); }); diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 7fed0439..9de09725 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,9 +71,9 @@ void main() { 'presences': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await presences.list(); expect(response, isA()); @@ -73,61 +81,61 @@ void main() { test('test method get()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', + 'userId': "674af8f3e12a5f9ac0be", + 'source': "HTTP", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await presences.get( - presenceId: '', + presenceId: "", ); expect(response, isA()); }); test('test method upsert()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', + 'userId': "674af8f3e12a5f9ac0be", + 'source': "HTTP", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await presences.upsert( - presenceId: '', - status: '', + presenceId: "", + status: "", ); expect(response, isA()); }); test('test method update()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'userId': '674af8f3e12a5f9ac0be', - 'source': 'HTTP', + 'userId': "674af8f3e12a5f9ac0be", + 'source': "HTTP", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await presences.update( - presenceId: '', + presenceId: "", ); expect(response, isA()); }); @@ -135,12 +143,12 @@ void main() { test('test method delete()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await presences.delete( - presenceId: '', + presenceId: "", ); }); }); diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 9ee2b2c2..92d858ee 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,47 +71,49 @@ void main() { 'files': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.listFiles( - bucketId: '', + bucketId: "", ); expect(response, isA()); }); test('test method createFile()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + 'bucketId': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', + 'name': "Pink.png", + 'folder': "photos/2026/", + 'key': "photos/2026/Pink.png", + 'signature': "5d529fd02b544198ae075bd57c1762bb", + 'mimeType': "image/png", 'sizeOriginal': 17890, 'sizeActual': 12345, 'chunksTotal': 17890, 'chunksUploaded': 17890, 'encryption': true, - 'compression': 'gzip', + 'compression': "gzip", }; - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), - )).thenAnswer((_) async => Response(data: data)); + when( + client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + ), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.createFile( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", file: InputFile.fromPath(path: './image.png'), ); expect(response, isA()); @@ -111,62 +121,62 @@ void main() { test('test method getFile()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + 'bucketId': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', + 'name': "Pink.png", + 'folder': "photos/2026/", + 'key': "photos/2026/Pink.png", + 'signature': "5d529fd02b544198ae075bd57c1762bb", + 'mimeType': "image/png", 'sizeOriginal': 17890, 'sizeActual': 12345, 'chunksTotal': 17890, 'chunksUploaded': 17890, 'encryption': true, - 'compression': 'gzip', + 'compression': "gzip", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.getFile( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); expect(response, isA()); }); test('test method updateFile()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - 'bucketId': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + 'bucketId': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], - 'name': 'Pink.png', - 'folder': 'photos/2026/', - 'key': 'photos/2026/Pink.png', - 'signature': '5d529fd02b544198ae075bd57c1762bb', - 'mimeType': 'image/png', + 'name': "Pink.png", + 'folder': "photos/2026/", + 'key': "photos/2026/Pink.png", + 'signature': "5d529fd02b544198ae075bd57c1762bb", + 'mimeType': "image/png", 'sizeOriginal': 17890, 'sizeActual': 12345, 'chunksTotal': 17890, 'chunksUploaded': 17890, 'encryption': true, - 'compression': 'gzip', + 'compression': "gzip", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.updateFile( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); expect(response, isA()); }); @@ -174,26 +184,26 @@ void main() { test('test method deleteFile()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.deleteFile( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); }); test('test method getFileDownload()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.getFileDownload( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); expect(response, isA()); }); @@ -201,13 +211,13 @@ void main() { test('test method getFilePreview()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.getFilePreview( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); expect(response, isA()); }); @@ -215,13 +225,13 @@ void main() { test('test method getFileView()', () async { final Uint8List data = Uint8List.fromList([]); - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await storage.getFileView( - bucketId: '', - fileId: '', + bucketId: "", + fileId: "", ); expect(response, isA()); }); diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index f318cad2..9cf7d024 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,9 +71,9 @@ void main() { 'transactions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.listTransactions(); expect(response, isA()); @@ -73,17 +81,17 @@ void main() { test('test method createTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.createTransaction(); expect(response, isA()); @@ -91,40 +99,40 @@ void main() { test('test method getTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.getTransaction( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); test('test method updateTransaction()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.updateTransaction( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); @@ -132,31 +140,31 @@ void main() { test('test method deleteTransaction()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.deleteTransaction( - transactionId: '', + transactionId: "", ); }); test('test method createOperations()', () async { final Map data = { - '\$id': '259125845563242502', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'status': 'pending', + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", 'operations': 5, - 'expiresAt': '2020-10-15T06:38:00.000+00:00', + 'expiresAt': "2020-10-15T06:38:00.000+00:00", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.createOperations( - transactionId: '', + transactionId: "", ); expect(response, isA()); }); @@ -167,36 +175,36 @@ void main() { 'rows': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.listRows( - databaseId: '', - tableId: '', + databaseId: "", + tableId: "", ); expect(response, isA()); }); test('test method createRow()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.createRow( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", data: {}, ); expect(response, isA()); @@ -204,69 +212,69 @@ void main() { test('test method getRow()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.getRow( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", ); expect(response, isA()); }); test('test method upsertRow()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.upsertRow( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", ); expect(response, isA()); }); test('test method updateRow()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.updateRow( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", ); expect(response, isA()); }); @@ -274,36 +282,36 @@ void main() { test('test method deleteRow()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.deleteRow( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", ); }); test('test method decrementRowColumn()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.decrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", column: '', ); expect(response, isA()); @@ -311,23 +319,23 @@ void main() { test('test method incrementRowColumn()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$sequence': '1', - '\$tableId': '5e5ea5c15117e', - '\$databaseId': '5e5ea5c15117e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$tableId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", '\$permissions': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await tablesDB.incrementRowColumn( - databaseId: '', - tableId: '', - rowId: '', + databaseId: "", + tableId: "", + rowId: "", column: '', ); expect(response, isA()); diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index d308ebe3..cafe8858 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -10,6 +10,7 @@ import 'package:appwrite/appwrite.dart'; class MockClient extends Mock implements Client { Map config = {'project': 'testproject'}; String endPoint = 'https://localhost/v1'; + @override Future call( HttpMethod? method, { @@ -18,17 +19,18 @@ class MockClient extends Mock implements Client { Map params = const {}, ResponseType? responseType, }) async { - return super.noSuchMethod(Invocation.method(#call, [method]), - returnValue: Response()); + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); } @override - Future webAuth( - Uri? url, { - String? callbackUrlScheme, - }) async { - return super - .noSuchMethod(Invocation.method(#webAuth, [url]), returnValue: 'done'); + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); } @override @@ -41,9 +43,15 @@ class MockClient extends Mock implements Client { Function(UploadProgress)? onProgress, }) async { return super.noSuchMethod( - Invocation.method( - #chunkedUpload, [path, params, paramName, idParamName, headers]), - returnValue: Response(data: {})); + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); } } @@ -63,9 +71,9 @@ void main() { 'teams': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.list(); expect(response, isA()); @@ -73,62 +81,62 @@ void main() { test('test method create()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "VIP", 'total': 7, 'prefs': {}, }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.create( - teamId: '', - name: '', + teamId: "", + name: "", ); expect(response, isA()); }); test('test method get()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "VIP", 'total': 7, 'prefs': {}, }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.get( - teamId: '', + teamId: "", ); expect(response, isA()); }); test('test method updateName()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'name': 'VIP', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "VIP", 'total': 7, 'prefs': {}, }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updateName( - teamId: '', - name: '', + teamId: "", + name: "", ); expect(response, isA()); }); @@ -136,12 +144,12 @@ void main() { test('test method delete()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.delete( - teamId: '', + teamId: "", ); }); @@ -151,84 +159,84 @@ void main() { 'installations': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.listInstallations( - teamId: '', + teamId: "", ); expect(response, isA()); }); test('test method createInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.createInstallation( - teamId: '', - appId: '', + teamId: "", + appId: "", ); expect(response, isA()); }); test('test method getInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.getInstallation( - teamId: '', - installationId: '', + teamId: "", + installationId: "", ); expect(response, isA()); }); test('test method updateInstallation()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updateInstallation( - teamId: '', - installationId: '', + teamId: "", + installationId: "", ); expect(response, isA()); }); @@ -236,13 +244,13 @@ void main() { test('test method deleteInstallation()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.deleteInstallation( - teamId: '', - installationId: '', + teamId: "", + installationId: "", ); }); @@ -252,41 +260,41 @@ void main() { 'memberships': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.listMemberships( - teamId: '', + teamId: "", ); expect(response, isA()); }); test('test method createMembership()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'userName': "John Doe", + 'userEmail': "john@appwrite.io", + 'userPhone': "+1 555 555 5555", + 'teamId': "5e5ea5c16897e", + 'teamName': "VIP", + 'invited': "2020-10-15T06:38:00.000+00:00", + 'joined': "2020-10-15T06:38:00.000+00:00", 'confirm': true, 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'userAccessedAt': "2020-10-15T06:38:00.000+00:00", 'roles': [], }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.createMembership( - teamId: '', + teamId: "", roles: [], ); expect(response, isA()); @@ -294,60 +302,60 @@ void main() { test('test method getMembership()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'userName': "John Doe", + 'userEmail': "john@appwrite.io", + 'userPhone': "+1 555 555 5555", + 'teamId': "5e5ea5c16897e", + 'teamName': "VIP", + 'invited': "2020-10-15T06:38:00.000+00:00", + 'joined': "2020-10-15T06:38:00.000+00:00", 'confirm': true, 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'userAccessedAt': "2020-10-15T06:38:00.000+00:00", 'roles': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.getMembership( - teamId: '', - membershipId: '', + teamId: "", + membershipId: "", ); expect(response, isA()); }); test('test method updateMembership()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'userName': "John Doe", + 'userEmail': "john@appwrite.io", + 'userPhone': "+1 555 555 5555", + 'teamId': "5e5ea5c16897e", + 'teamName': "VIP", + 'invited': "2020-10-15T06:38:00.000+00:00", + 'joined': "2020-10-15T06:38:00.000+00:00", 'confirm': true, 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'userAccessedAt': "2020-10-15T06:38:00.000+00:00", 'roles': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updateMembership( - teamId: '', - membershipId: '', + teamId: "", + membershipId: "", roles: [], ); expect(response, isA()); @@ -356,44 +364,44 @@ void main() { test('test method deleteMembership()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.deleteMembership( - teamId: '', - membershipId: '', + teamId: "", + membershipId: "", ); }); test('test method updateMembershipStatus()', () async { final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'userId': '5e5ea5c16897e', - 'userName': 'John Doe', - 'userEmail': 'john@appwrite.io', - 'userPhone': '+1 555 555 5555', - 'teamId': '5e5ea5c16897e', - 'teamName': 'VIP', - 'invited': '2020-10-15T06:38:00.000+00:00', - 'joined': '2020-10-15T06:38:00.000+00:00', + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'userName': "John Doe", + 'userEmail': "john@appwrite.io", + 'userPhone': "+1 555 555 5555", + 'teamId': "5e5ea5c16897e", + 'teamName': "VIP", + 'invited': "2020-10-15T06:38:00.000+00:00", + 'joined': "2020-10-15T06:38:00.000+00:00", 'confirm': true, 'mfa': true, - 'userAccessedAt': '2020-10-15T06:38:00.000+00:00', + 'userAccessedAt': "2020-10-15T06:38:00.000+00:00", 'roles': [], }; - when(client.call( - HttpMethod.patch, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updateMembershipStatus( - teamId: '', - membershipId: '', - userId: '', - secret: '', + teamId: "", + membershipId: "", + userId: "", + secret: "", ); expect(response, isA()); }); @@ -401,12 +409,12 @@ void main() { test('test method getPrefs()', () async { final Map data = {}; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.getPrefs( - teamId: '', + teamId: "", ); expect(response, isA()); }); @@ -414,12 +422,12 @@ void main() { test('test method updatePrefs()', () async { final Map data = {}; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updatePrefs( - teamId: '', + teamId: "", prefs: {}, ); expect(response, isA()); diff --git a/test/src/models/algo_argon2_test.dart b/test/src/models/algo_argon2_test.dart index 261daa46..81f535b4 100644 --- a/test/src/models/algo_argon2_test.dart +++ b/test/src/models/algo_argon2_test.dart @@ -5,7 +5,7 @@ void main() { group('AlgoArgon2', () { test('model', () { final model = AlgoArgon2( - type: 'argon2', + type: "argon2", memoryCost: 65536, timeCost: 4, threads: 3, @@ -14,7 +14,7 @@ void main() { final map = model.toMap(); final result = AlgoArgon2.fromMap(map); - expect(result.type, 'argon2'); + expect(result.type, "argon2"); expect(result.memoryCost, 65536); expect(result.timeCost, 4); expect(result.threads, 3); diff --git a/test/src/models/algo_bcrypt_test.dart b/test/src/models/algo_bcrypt_test.dart index 3da36624..4cb547df 100644 --- a/test/src/models/algo_bcrypt_test.dart +++ b/test/src/models/algo_bcrypt_test.dart @@ -5,13 +5,13 @@ void main() { group('AlgoBcrypt', () { test('model', () { final model = AlgoBcrypt( - type: 'bcrypt', + type: "bcrypt", ); final map = model.toMap(); final result = AlgoBcrypt.fromMap(map); - expect(result.type, 'bcrypt'); + expect(result.type, "bcrypt"); }); }); } diff --git a/test/src/models/algo_md5_test.dart b/test/src/models/algo_md5_test.dart index e58fa5b5..32269c90 100644 --- a/test/src/models/algo_md5_test.dart +++ b/test/src/models/algo_md5_test.dart @@ -5,13 +5,13 @@ void main() { group('AlgoMd5', () { test('model', () { final model = AlgoMd5( - type: 'md5', + type: "md5", ); final map = model.toMap(); final result = AlgoMd5.fromMap(map); - expect(result.type, 'md5'); + expect(result.type, "md5"); }); }); } diff --git a/test/src/models/algo_phpass_test.dart b/test/src/models/algo_phpass_test.dart index 3bcbb488..91f96ed6 100644 --- a/test/src/models/algo_phpass_test.dart +++ b/test/src/models/algo_phpass_test.dart @@ -5,13 +5,13 @@ void main() { group('AlgoPhpass', () { test('model', () { final model = AlgoPhpass( - type: 'phpass', + type: "phpass", ); final map = model.toMap(); final result = AlgoPhpass.fromMap(map); - expect(result.type, 'phpass'); + expect(result.type, "phpass"); }); }); } diff --git a/test/src/models/algo_scrypt_modified_test.dart b/test/src/models/algo_scrypt_modified_test.dart index b2084927..2e705994 100644 --- a/test/src/models/algo_scrypt_modified_test.dart +++ b/test/src/models/algo_scrypt_modified_test.dart @@ -5,21 +5,23 @@ void main() { group('AlgoScryptModified', () { test('model', () { final model = AlgoScryptModified( - type: 'scryptMod', - salt: 'UxLMreBr6tYyjQ==', - saltSeparator: 'Bw==', + type: "scryptMod", + salt: "UxLMreBr6tYyjQ==", + saltSeparator: "Bw==", signerKey: - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', + "XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==", ); final map = model.toMap(); final result = AlgoScryptModified.fromMap(map); - expect(result.type, 'scryptMod'); - expect(result.salt, 'UxLMreBr6tYyjQ=='); - expect(result.saltSeparator, 'Bw=='); - expect(result.signerKey, - 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='); + expect(result.type, "scryptMod"); + expect(result.salt, "UxLMreBr6tYyjQ=="); + expect(result.saltSeparator, "Bw=="); + expect( + result.signerKey, + "XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==", + ); }); }); } diff --git a/test/src/models/algo_scrypt_test.dart b/test/src/models/algo_scrypt_test.dart index 8c131568..bb3d38b7 100644 --- a/test/src/models/algo_scrypt_test.dart +++ b/test/src/models/algo_scrypt_test.dart @@ -5,7 +5,7 @@ void main() { group('AlgoScrypt', () { test('model', () { final model = AlgoScrypt( - type: 'scrypt', + type: "scrypt", costCpu: 8, costMemory: 14, costParallel: 1, @@ -15,7 +15,7 @@ void main() { final map = model.toMap(); final result = AlgoScrypt.fromMap(map); - expect(result.type, 'scrypt'); + expect(result.type, "scrypt"); expect(result.costCpu, 8); expect(result.costMemory, 14); expect(result.costParallel, 1); diff --git a/test/src/models/algo_sha_test.dart b/test/src/models/algo_sha_test.dart index d080569c..bb795319 100644 --- a/test/src/models/algo_sha_test.dart +++ b/test/src/models/algo_sha_test.dart @@ -5,13 +5,13 @@ void main() { group('AlgoSha', () { test('model', () { final model = AlgoSha( - type: 'sha', + type: "sha", ); final map = model.toMap(); final result = AlgoSha.fromMap(map); - expect(result.type, 'sha'); + expect(result.type, "sha"); }); }); } diff --git a/test/src/models/app_installation_test.dart b/test/src/models/app_installation_test.dart index dc0ec63c..25cf249e 100644 --- a/test/src/models/app_installation_test.dart +++ b/test/src/models/app_installation_test.dart @@ -5,29 +5,29 @@ void main() { group('AppInstallation', () { test('model', () { final model = AppInstallation( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - appId: '5e5ea5c16897e', - teamId: '5e5ea5c16897e', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + teamId: "5e5ea5c16897e", scopes: [], - authorizationDetails: {}, - createdById: '5e5ea5c16897e', - createdByName: 'Walter White', + authorizationDetails: [], + createdById: "5e5ea5c16897e", + createdByName: "Walter White", ); final map = model.toMap(); final result = AppInstallation.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.teamId, '5e5ea5c16897e'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.teamId, "5e5ea5c16897e"); expect(result.scopes, []); - expect(result.authorizationDetails, {}); - expect(result.createdById, '5e5ea5c16897e'); - expect(result.createdByName, 'Walter White'); + expect(result.authorizationDetails, []); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); }); }); } diff --git a/test/src/models/continent_test.dart b/test/src/models/continent_test.dart index 85e559f5..8aa95758 100644 --- a/test/src/models/continent_test.dart +++ b/test/src/models/continent_test.dart @@ -5,15 +5,15 @@ void main() { group('Continent', () { test('model', () { final model = Continent( - name: 'Europe', - code: 'EU', + name: "Europe", + code: "EU", ); final map = model.toMap(); final result = Continent.fromMap(map); - expect(result.name, 'Europe'); - expect(result.code, 'EU'); + expect(result.name, "Europe"); + expect(result.code, "EU"); }); }); } diff --git a/test/src/models/country_test.dart b/test/src/models/country_test.dart index d5404a7f..73617834 100644 --- a/test/src/models/country_test.dart +++ b/test/src/models/country_test.dart @@ -5,15 +5,15 @@ void main() { group('Country', () { test('model', () { final model = Country( - name: 'United States', - code: 'US', + name: "United States", + code: "US", ); final map = model.toMap(); final result = Country.fromMap(map); - expect(result.name, 'United States'); - expect(result.code, 'US'); + expect(result.name, "United States"); + expect(result.code, "US"); }); }); } diff --git a/test/src/models/currency_test.dart b/test/src/models/currency_test.dart index 00e046c7..b7761a5c 100644 --- a/test/src/models/currency_test.dart +++ b/test/src/models/currency_test.dart @@ -5,25 +5,25 @@ void main() { group('Currency', () { test('model', () { final model = Currency( - symbol: '\$', - name: 'US dollar', - symbolNative: '\$', + symbol: "\$", + name: "US dollar", + symbolNative: "\$", decimalDigits: 2, rounding: 0, - code: 'USD', - namePlural: 'US dollars', + code: "USD", + namePlural: "US dollars", ); final map = model.toMap(); final result = Currency.fromMap(map); - expect(result.symbol, '\$'); - expect(result.name, 'US dollar'); - expect(result.symbolNative, '\$'); + expect(result.symbol, "\$"); + expect(result.name, "US dollar"); + expect(result.symbolNative, "\$"); expect(result.decimalDigits, 2); expect(result.rounding, 0); - expect(result.code, 'USD'); - expect(result.namePlural, 'US dollars'); + expect(result.code, "USD"); + expect(result.namePlural, "US dollars"); }); }); } diff --git a/test/src/models/document_test.dart b/test/src/models/document_test.dart index 397b5fab..158af251 100644 --- a/test/src/models/document_test.dart +++ b/test/src/models/document_test.dart @@ -5,12 +5,12 @@ void main() { group('Document', () { test('model', () { final model = Document( - $id: '5e5ea5c16897e', - $sequence: '1', - $collectionId: '5e5ea5c15117e', - $databaseId: '5e5ea5c15117e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $sequence: "1", + $collectionId: "5e5ea5c15117e", + $databaseId: "5e5ea5c15117e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", $permissions: [], data: {}, ); @@ -18,12 +18,12 @@ void main() { final map = model.toMap(); final result = Document.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$collectionId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$sequence, "1"); + expect(result.$collectionId, "5e5ea5c15117e"); + expect(result.$databaseId, "5e5ea5c15117e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.$permissions, []); }); }); diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 80ef508a..15955b9a 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -6,44 +6,46 @@ void main() { group('Execution', () { test('model', () { final model = Execution( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", $permissions: [], - functionId: '5e5ea6g16897e', - deploymentId: '5e5ea5c16897e', + resourceId: "5e5ea6g16897e", + resourceType: ExecutionResourceType.functions, + deploymentId: "5e5ea5c16897e", trigger: ExecutionTrigger.http, status: ExecutionStatus.waiting, - requestMethod: 'GET', - requestPath: '/articles?id=5', + requestMethod: "GET", + requestPath: "/articles?id=5", requestHeaders: [], responseStatusCode: 200, - responseBody: '', + responseBody: "", responseHeaders: [], - logs: '', - errors: '', + logs: "", + errors: "", duration: 0.4, ); final map = model.toMap(); final result = Execution.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.$permissions, []); - expect(result.functionId, '5e5ea6g16897e'); - expect(result.deploymentId, '5e5ea5c16897e'); + expect(result.resourceId, "5e5ea6g16897e"); + expect(result.resourceType, ExecutionResourceType.functions); + expect(result.deploymentId, "5e5ea5c16897e"); expect(result.trigger, ExecutionTrigger.http); expect(result.status, ExecutionStatus.waiting); - expect(result.requestMethod, 'GET'); - expect(result.requestPath, '/articles?id=5'); + expect(result.requestMethod, "GET"); + expect(result.requestPath, "/articles?id=5"); expect(result.requestHeaders, []); expect(result.responseStatusCode, 200); - expect(result.responseBody, ''); + expect(result.responseBody, ""); expect(result.responseHeaders, []); - expect(result.logs, ''); - expect(result.errors, ''); + expect(result.logs, ""); + expect(result.errors, ""); expect(result.duration, 0.4); }); }); diff --git a/test/src/models/file_test.dart b/test/src/models/file_test.dart index 7bf20fce..8aec10e5 100644 --- a/test/src/models/file_test.dart +++ b/test/src/models/file_test.dart @@ -5,43 +5,43 @@ void main() { group('File', () { test('model', () { final model = File( - $id: '5e5ea5c16897e', - bucketId: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + bucketId: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", $permissions: [], - name: 'Pink.png', - folder: 'photos/2026/', - key: 'photos/2026/Pink.png', - signature: '5d529fd02b544198ae075bd57c1762bb', - mimeType: 'image/png', + name: "Pink.png", + folder: "photos/2026/", + key: "photos/2026/Pink.png", + signature: "5d529fd02b544198ae075bd57c1762bb", + mimeType: "image/png", sizeOriginal: 17890, sizeActual: 12345, chunksTotal: 17890, chunksUploaded: 17890, encryption: true, - compression: 'gzip', + compression: "gzip", ); final map = model.toMap(); final result = File.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.bucketId, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.bucketId, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.$permissions, []); - expect(result.name, 'Pink.png'); - expect(result.folder, 'photos/2026/'); - expect(result.key, 'photos/2026/Pink.png'); - expect(result.signature, '5d529fd02b544198ae075bd57c1762bb'); - expect(result.mimeType, 'image/png'); + expect(result.name, "Pink.png"); + expect(result.folder, "photos/2026/"); + expect(result.key, "photos/2026/Pink.png"); + expect(result.signature, "5d529fd02b544198ae075bd57c1762bb"); + expect(result.mimeType, "image/png"); expect(result.sizeOriginal, 17890); expect(result.sizeActual, 12345); expect(result.chunksTotal, 17890); expect(result.chunksUploaded, 17890); expect(result.encryption, true); - expect(result.compression, 'gzip'); + expect(result.compression, "gzip"); }); }); } diff --git a/test/src/models/headers_test.dart b/test/src/models/headers_test.dart index 9252b469..6be7a356 100644 --- a/test/src/models/headers_test.dart +++ b/test/src/models/headers_test.dart @@ -5,15 +5,15 @@ void main() { group('Headers', () { test('model', () { final model = Headers( - name: 'Content-Type', - value: 'application/json', + name: "Content-Type", + value: "application/json", ); final map = model.toMap(); final result = Headers.fromMap(map); - expect(result.name, 'Content-Type'); - expect(result.value, 'application/json'); + expect(result.name, "Content-Type"); + expect(result.value, "application/json"); }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index 525af4ea..a88b2dbe 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -5,31 +5,31 @@ void main() { group('Identity', () { test('model', () { final model = Identity( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5bb8c16897e', - provider: 'email', - providerUid: '5e5bb8c16897e', - providerEmail: 'user@example.com', - providerAccessToken: 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - providerAccessTokenExpiry: '2020-10-15T06:38:00.000+00:00', - providerRefreshToken: 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5bb8c16897e", + provider: "email", + providerUid: "5e5bb8c16897e", + providerEmail: "user@example.com", + providerAccessToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + providerAccessTokenExpiry: "2020-10-15T06:38:00.000+00:00", + providerRefreshToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", ); final map = model.toMap(); final result = Identity.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.provider, 'email'); - expect(result.providerUid, '5e5bb8c16897e'); - expect(result.providerEmail, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5bb8c16897e"); + expect(result.provider, "email"); + expect(result.providerUid, "5e5bb8c16897e"); + expect(result.providerEmail, "user@example.com"); + expect(result.providerAccessToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); + expect(result.providerAccessTokenExpiry, "2020-10-15T06:38:00.000+00:00"); + expect(result.providerRefreshToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); }); }); } diff --git a/test/src/models/jwt_test.dart b/test/src/models/jwt_test.dart index 93376af1..f5229e3c 100644 --- a/test/src/models/jwt_test.dart +++ b/test/src/models/jwt_test.dart @@ -6,14 +6,16 @@ void main() { test('model', () { final model = Jwt( jwt: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", ); final map = model.toMap(); final result = Jwt.fromMap(map); - expect(result.jwt, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); + expect( + result.jwt, + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", + ); }); }); } diff --git a/test/src/models/language_test.dart b/test/src/models/language_test.dart index 4a6c96c1..cbf95302 100644 --- a/test/src/models/language_test.dart +++ b/test/src/models/language_test.dart @@ -5,17 +5,17 @@ void main() { group('Language', () { test('model', () { final model = Language( - name: 'Italian', - code: 'it', - nativeName: 'Italiano', + name: "Italian", + code: "it", + nativeName: "Italiano", ); final map = model.toMap(); final result = Language.fromMap(map); - expect(result.name, 'Italian'); - expect(result.code, 'it'); - expect(result.nativeName, 'Italiano'); + expect(result.name, "Italian"); + expect(result.code, "it"); + expect(result.nativeName, "Italiano"); }); }); } diff --git a/test/src/models/locale_code_test.dart b/test/src/models/locale_code_test.dart index 88cf157b..3c238923 100644 --- a/test/src/models/locale_code_test.dart +++ b/test/src/models/locale_code_test.dart @@ -5,15 +5,15 @@ void main() { group('LocaleCode', () { test('model', () { final model = LocaleCode( - code: 'en-us', - name: 'US', + code: "en-us", + name: "US", ); final map = model.toMap(); final result = LocaleCode.fromMap(map); - expect(result.code, 'en-us'); - expect(result.name, 'US'); + expect(result.code, "en-us"); + expect(result.name, "US"); }); }); } diff --git a/test/src/models/locale_test.dart b/test/src/models/locale_test.dart index 49cb1fc9..38557034 100644 --- a/test/src/models/locale_test.dart +++ b/test/src/models/locale_test.dart @@ -5,25 +5,25 @@ void main() { group('Locale', () { test('model', () { final model = Locale( - ip: '127.0.0.1', - countryCode: 'US', - country: 'United States', - continentCode: 'NA', - continent: 'North America', + ip: "127.0.0.1", + countryCode: "US", + country: "United States", + continentCode: "NA", + continent: "North America", eu: true, - currency: 'USD', + currency: "USD", ); final map = model.toMap(); final result = Locale.fromMap(map); - expect(result.ip, '127.0.0.1'); - expect(result.countryCode, 'US'); - expect(result.country, 'United States'); - expect(result.continentCode, 'NA'); - expect(result.continent, 'North America'); + expect(result.ip, "127.0.0.1"); + expect(result.countryCode, "US"); + expect(result.country, "United States"); + expect(result.continentCode, "NA"); + expect(result.continent, "North America"); expect(result.eu, true); - expect(result.currency, 'USD'); + expect(result.currency, "USD"); }); }); } diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart index c8211d3b..3b4d95af 100644 --- a/test/src/models/log_test.dart +++ b/test/src/models/log_test.dart @@ -5,55 +5,55 @@ void main() { group('Log', () { test('model', () { final model = Log( - event: 'account.sessions.create', - userId: '610fc2f985ee0', - userEmail: 'john@appwrite.io', - userName: 'John Doe', - mode: 'admin', - userType: 'user', - ip: '127.0.0.1', - time: '2020-10-15T06:38:00.000+00:00', - osCode: 'Mac', - osName: 'Mac', - osVersion: 'Mac', - clientType: 'browser', - clientCode: 'CM', - clientName: 'Chrome Mobile iOS', - clientVersion: '84.0', - clientEngine: 'WebKit', - clientEngineVersion: '605.1.15', - deviceName: 'smartphone', - deviceBrand: 'Google', - deviceModel: 'Nexus 5', - countryCode: 'US', - countryName: 'United States', + event: "account.sessions.create", + userId: "610fc2f985ee0", + userEmail: "john@appwrite.io", + userName: "John Doe", + mode: "admin", + userType: "user", + ip: "127.0.0.1", + time: "2020-10-15T06:38:00.000+00:00", + osCode: "Mac", + osName: "Mac", + osVersion: "Mac", + clientType: "browser", + clientCode: "CM", + clientName: "Chrome Mobile iOS", + clientVersion: "84.0", + clientEngine: "WebKit", + clientEngineVersion: "605.1.15", + deviceName: "smartphone", + deviceBrand: "Google", + deviceModel: "Nexus 5", + countryCode: "US", + countryName: "United States", ); final map = model.toMap(); final result = Log.fromMap(map); - expect(result.event, 'account.sessions.create'); - expect(result.userId, '610fc2f985ee0'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userName, 'John Doe'); - expect(result.mode, 'admin'); - expect(result.userType, 'user'); - expect(result.ip, '127.0.0.1'); - expect(result.time, '2020-10-15T06:38:00.000+00:00'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); + expect(result.event, "account.sessions.create"); + expect(result.userId, "610fc2f985ee0"); + expect(result.userEmail, "john@appwrite.io"); + expect(result.userName, "John Doe"); + expect(result.mode, "admin"); + expect(result.userType, "user"); + expect(result.ip, "127.0.0.1"); + expect(result.time, "2020-10-15T06:38:00.000+00:00"); + expect(result.osCode, "Mac"); + expect(result.osName, "Mac"); + expect(result.osVersion, "Mac"); + expect(result.clientType, "browser"); + expect(result.clientCode, "CM"); + expect(result.clientName, "Chrome Mobile iOS"); + expect(result.clientVersion, "84.0"); + expect(result.clientEngine, "WebKit"); + expect(result.clientEngineVersion, "605.1.15"); + expect(result.deviceName, "smartphone"); + expect(result.deviceBrand, "Google"); + expect(result.deviceModel, "Nexus 5"); + expect(result.countryCode, "US"); + expect(result.countryName, "United States"); }); }); } diff --git a/test/src/models/membership_test.dart b/test/src/models/membership_test.dart index b2b8bd3d..2b157ac6 100644 --- a/test/src/models/membership_test.dart +++ b/test/src/models/membership_test.dart @@ -5,40 +5,40 @@ void main() { group('Membership', () { test('model', () { final model = Membership( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5ea5c16897e', - userName: 'John Doe', - userEmail: 'john@appwrite.io', - userPhone: '+1 555 555 5555', - teamId: '5e5ea5c16897e', - teamName: 'VIP', - invited: '2020-10-15T06:38:00.000+00:00', - joined: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c16897e", + userName: "John Doe", + userEmail: "john@appwrite.io", + userPhone: "+1 555 555 5555", + teamId: "5e5ea5c16897e", + teamName: "VIP", + invited: "2020-10-15T06:38:00.000+00:00", + joined: "2020-10-15T06:38:00.000+00:00", confirm: true, mfa: true, - userAccessedAt: '2020-10-15T06:38:00.000+00:00', + userAccessedAt: "2020-10-15T06:38:00.000+00:00", roles: [], ); final map = model.toMap(); final result = Membership.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'John Doe'); - expect(result.userEmail, 'john@appwrite.io'); - expect(result.userPhone, '+1 555 555 5555'); - expect(result.teamId, '5e5ea5c16897e'); - expect(result.teamName, 'VIP'); - expect(result.invited, '2020-10-15T06:38:00.000+00:00'); - expect(result.joined, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.userName, "John Doe"); + expect(result.userEmail, "john@appwrite.io"); + expect(result.userPhone, "+1 555 555 5555"); + expect(result.teamId, "5e5ea5c16897e"); + expect(result.teamName, "VIP"); + expect(result.invited, "2020-10-15T06:38:00.000+00:00"); + expect(result.joined, "2020-10-15T06:38:00.000+00:00"); expect(result.confirm, true); expect(result.mfa, true); - expect(result.userAccessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.userAccessedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.roles, []); }); }); diff --git a/test/src/models/mfa_challenge_test.dart b/test/src/models/mfa_challenge_test.dart index 5d3febca..227ed694 100644 --- a/test/src/models/mfa_challenge_test.dart +++ b/test/src/models/mfa_challenge_test.dart @@ -5,19 +5,19 @@ void main() { group('MfaChallenge', () { test('model', () { final model = MfaChallenge( - $id: 'bb8ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5ea5c168bb8', - expire: '2020-10-15T06:38:00.000+00:00', + $id: "bb8ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c168bb8", + expire: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = MfaChallenge.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "bb8ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c168bb8"); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); }); }); } diff --git a/test/src/models/mfa_factors_test.dart b/test/src/models/mfa_factors_test.dart index 64cc55e4..03c86145 100644 --- a/test/src/models/mfa_factors_test.dart +++ b/test/src/models/mfa_factors_test.dart @@ -9,6 +9,7 @@ void main() { phone: true, email: true, recoveryCode: true, + custom: true, ); final map = model.toMap(); @@ -18,6 +19,7 @@ void main() { expect(result.phone, true); expect(result.email, true); expect(result.recoveryCode, true); + expect(result.custom, true); }); }); } diff --git a/test/src/models/mfa_type_test.dart b/test/src/models/mfa_type_test.dart index 81657394..8ca0e284 100644 --- a/test/src/models/mfa_type_test.dart +++ b/test/src/models/mfa_type_test.dart @@ -5,17 +5,19 @@ void main() { group('MfaType', () { test('model', () { final model = MfaType( - secret: '[SHARED_SECRET]', + secret: "[SHARED_SECRET]", uri: - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite', + "otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite", ); final map = model.toMap(); final result = MfaType.fromMap(map); - expect(result.secret, '[SHARED_SECRET]'); - expect(result.uri, - 'otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite'); + expect(result.secret, "[SHARED_SECRET]"); + expect( + result.uri, + "otpauth://totp/appwrite:user@example.com?secret=[SHARED_SECRET]&issuer=appwrite", + ); }); }); } diff --git a/test/src/models/oauth2_consent_test.dart b/test/src/models/oauth2_consent_test.dart index 32456d3c..c80f1d64 100644 --- a/test/src/models/oauth2_consent_test.dart +++ b/test/src/models/oauth2_consent_test.dart @@ -5,34 +5,38 @@ void main() { group('Oauth2Consent', () { test('model', () { final model = Oauth2Consent( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5ea5c16897e', - appId: '5e5ea5c16897e', - cimdUrl: 'https://example.com/.well-known/client-metadata.json', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c16897e", + appId: "5e5ea5c16897e", + cimdUrl: "https://example.com/.well-known/client-metadata.json", scopes: [], resources: [], authorizationDetails: - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - expire: '2020-10-15T06:38:00.000+00:00', + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + expire: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = Oauth2Consent.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.cimdUrl, - 'https://example.com/.well-known/client-metadata.json'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.cimdUrl, + "https://example.com/.well-known/client-metadata.json", + ); expect(result.scopes, []); expect(result.resources, []); - expect(result.authorizationDetails, - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect( + result.authorizationDetails, + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + ); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); }); }); } diff --git a/test/src/models/oauth2_consent_token_test.dart b/test/src/models/oauth2_consent_token_test.dart index e8a7b94b..08fc9557 100644 --- a/test/src/models/oauth2_consent_token_test.dart +++ b/test/src/models/oauth2_consent_token_test.dart @@ -5,36 +5,40 @@ void main() { group('Oauth2ConsentToken', () { test('model', () { final model = Oauth2ConsentToken( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - consentId: '5e5ea5c16897e', - userId: '5e5ea5c16897e', - appId: '5e5ea5c16897e', - cimdUrl: 'https://example.com/.well-known/client-metadata.json', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + consentId: "5e5ea5c16897e", + userId: "5e5ea5c16897e", + appId: "5e5ea5c16897e", + cimdUrl: "https://example.com/.well-known/client-metadata.json", scopes: [], resources: [], authorizationDetails: - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]', - expire: '2020-10-15T06:38:00.000+00:00', + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + expire: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = Oauth2ConsentToken.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.consentId, '5e5ea5c16897e'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.appId, '5e5ea5c16897e'); - expect(result.cimdUrl, - 'https://example.com/.well-known/client-metadata.json'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.consentId, "5e5ea5c16897e"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.cimdUrl, + "https://example.com/.well-known/client-metadata.json", + ); expect(result.scopes, []); expect(result.resources, []); - expect(result.authorizationDetails, - '[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); + expect( + result.authorizationDetails, + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + ); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); }); }); } diff --git a/test/src/models/phone_test.dart b/test/src/models/phone_test.dart index f70db0e3..3f9c2646 100644 --- a/test/src/models/phone_test.dart +++ b/test/src/models/phone_test.dart @@ -5,17 +5,17 @@ void main() { group('Phone', () { test('model', () { final model = Phone( - code: '+1', - countryCode: 'US', - countryName: 'United States', + code: "+1", + countryCode: "US", + countryName: "United States", ); final map = model.toMap(); final result = Phone.fromMap(map); - expect(result.code, '+1'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); + expect(result.code, "+1"); + expect(result.countryCode, "US"); + expect(result.countryName, "United States"); }); }); } diff --git a/test/src/models/presence_test.dart b/test/src/models/presence_test.dart index ef2ebe31..854a9695 100644 --- a/test/src/models/presence_test.dart +++ b/test/src/models/presence_test.dart @@ -5,23 +5,23 @@ void main() { group('Presence', () { test('model', () { final model = Presence( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", $permissions: [], - userId: '674af8f3e12a5f9ac0be', - source: 'HTTP', + userId: "674af8f3e12a5f9ac0be", + source: "HTTP", ); final map = model.toMap(); final result = Presence.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.$permissions, []); - expect(result.userId, '674af8f3e12a5f9ac0be'); - expect(result.source, 'HTTP'); + expect(result.userId, "674af8f3e12a5f9ac0be"); + expect(result.source, "HTTP"); }); }); } diff --git a/test/src/models/row_test.dart b/test/src/models/row_test.dart index 564bf303..903776c2 100644 --- a/test/src/models/row_test.dart +++ b/test/src/models/row_test.dart @@ -5,12 +5,12 @@ void main() { group('Row', () { test('model', () { final model = Row( - $id: '5e5ea5c16897e', - $sequence: '1', - $tableId: '5e5ea5c15117e', - $databaseId: '5e5ea5c15117e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $sequence: "1", + $tableId: "5e5ea5c15117e", + $databaseId: "5e5ea5c15117e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", $permissions: [], data: {}, ); @@ -18,12 +18,12 @@ void main() { final map = model.toMap(); final result = Row.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$sequence, '1'); - expect(result.$tableId, '5e5ea5c15117e'); - expect(result.$databaseId, '5e5ea5c15117e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$sequence, "1"); + expect(result.$tableId, "5e5ea5c15117e"); + expect(result.$databaseId, "5e5ea5c15117e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); expect(result.$permissions, []); }); }); diff --git a/test/src/models/session_test.dart b/test/src/models/session_test.dart index 689e6048..45dd3471 100644 --- a/test/src/models/session_test.dart +++ b/test/src/models/session_test.dart @@ -5,69 +5,69 @@ void main() { group('Session', () { test('model', () { final model = Session( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5bb8c16897e', - expire: '2020-10-15T06:38:00.000+00:00', - provider: 'email', - providerUid: 'user@example.com', - providerAccessToken: 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - providerAccessTokenExpiry: '2020-10-15T06:38:00.000+00:00', - providerRefreshToken: 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3', - ip: '127.0.0.1', - osCode: 'Mac', - osName: 'Mac', - osVersion: 'Mac', - clientType: 'browser', - clientCode: 'CM', - clientName: 'Chrome Mobile iOS', - clientVersion: '84.0', - clientEngine: 'WebKit', - clientEngineVersion: '605.1.15', - deviceName: 'smartphone', - deviceBrand: 'Google', - deviceModel: 'Nexus 5', - countryCode: 'US', - countryName: 'United States', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5bb8c16897e", + expire: "2020-10-15T06:38:00.000+00:00", + provider: "email", + providerUid: "user@example.com", + providerAccessToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + providerAccessTokenExpiry: "2020-10-15T06:38:00.000+00:00", + providerRefreshToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + ip: "127.0.0.1", + osCode: "Mac", + osName: "Mac", + osVersion: "Mac", + clientType: "browser", + clientCode: "CM", + clientName: "Chrome Mobile iOS", + clientVersion: "84.0", + clientEngine: "WebKit", + clientEngineVersion: "605.1.15", + deviceName: "smartphone", + deviceBrand: "Google", + deviceModel: "Nexus 5", + countryCode: "US", + countryName: "United States", current: true, factors: [], - secret: '5e5bb8c16897e', - mfaUpdatedAt: '2020-10-15T06:38:00.000+00:00', + secret: "5e5bb8c16897e", + mfaUpdatedAt: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = Session.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5bb8c16897e'); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.provider, 'email'); - expect(result.providerUid, 'user@example.com'); - expect(result.providerAccessToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.providerAccessTokenExpiry, '2020-10-15T06:38:00.000+00:00'); - expect(result.providerRefreshToken, 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3'); - expect(result.ip, '127.0.0.1'); - expect(result.osCode, 'Mac'); - expect(result.osName, 'Mac'); - expect(result.osVersion, 'Mac'); - expect(result.clientType, 'browser'); - expect(result.clientCode, 'CM'); - expect(result.clientName, 'Chrome Mobile iOS'); - expect(result.clientVersion, '84.0'); - expect(result.clientEngine, 'WebKit'); - expect(result.clientEngineVersion, '605.1.15'); - expect(result.deviceName, 'smartphone'); - expect(result.deviceBrand, 'Google'); - expect(result.deviceModel, 'Nexus 5'); - expect(result.countryCode, 'US'); - expect(result.countryName, 'United States'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5bb8c16897e"); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); + expect(result.provider, "email"); + expect(result.providerUid, "user@example.com"); + expect(result.providerAccessToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); + expect(result.providerAccessTokenExpiry, "2020-10-15T06:38:00.000+00:00"); + expect(result.providerRefreshToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); + expect(result.ip, "127.0.0.1"); + expect(result.osCode, "Mac"); + expect(result.osName, "Mac"); + expect(result.osVersion, "Mac"); + expect(result.clientType, "browser"); + expect(result.clientCode, "CM"); + expect(result.clientName, "Chrome Mobile iOS"); + expect(result.clientVersion, "84.0"); + expect(result.clientEngine, "WebKit"); + expect(result.clientEngineVersion, "605.1.15"); + expect(result.deviceName, "smartphone"); + expect(result.deviceBrand, "Google"); + expect(result.deviceModel, "Nexus 5"); + expect(result.countryCode, "US"); + expect(result.countryName, "United States"); expect(result.current, true); expect(result.factors, []); - expect(result.secret, '5e5bb8c16897e'); - expect(result.mfaUpdatedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.secret, "5e5bb8c16897e"); + expect(result.mfaUpdatedAt, "2020-10-15T06:38:00.000+00:00"); }); }); } diff --git a/test/src/models/subscriber_test.dart b/test/src/models/subscriber_test.dart index 7445514c..6ac27400 100644 --- a/test/src/models/subscriber_test.dart +++ b/test/src/models/subscriber_test.dart @@ -5,37 +5,37 @@ void main() { group('Subscriber', () { test('model', () { final model = Subscriber( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - targetId: '259125845563242502', + $id: "259125845563242502", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + targetId: "259125845563242502", target: Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', + $id: "259125845563242502", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "Apple iPhone 12", + userId: "259125845563242502", + providerType: "email", + identifier: "token", expired: true, ), - userId: '5e5ea5c16897e', - userName: 'Aegon Targaryen', - topicId: '259125845563242502', - providerType: 'email', + userId: "5e5ea5c16897e", + userName: "Aegon Targaryen", + topicId: "259125845563242502", + providerType: "email", ); final map = model.toMap(); final result = Subscriber.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.targetId, '259125845563242502'); - expect(result.userId, '5e5ea5c16897e'); - expect(result.userName, 'Aegon Targaryen'); - expect(result.topicId, '259125845563242502'); - expect(result.providerType, 'email'); + expect(result.$id, "259125845563242502"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.targetId, "259125845563242502"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.userName, "Aegon Targaryen"); + expect(result.topicId, "259125845563242502"); + expect(result.providerType, "email"); }); }); } diff --git a/test/src/models/target_test.dart b/test/src/models/target_test.dart index 49f1e75e..67a7dfd1 100644 --- a/test/src/models/target_test.dart +++ b/test/src/models/target_test.dart @@ -5,26 +5,26 @@ void main() { group('Target', () { test('model', () { final model = Target( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'Apple iPhone 12', - userId: '259125845563242502', - providerType: 'email', - identifier: 'token', + $id: "259125845563242502", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "Apple iPhone 12", + userId: "259125845563242502", + providerType: "email", + identifier: "token", expired: true, ); final map = model.toMap(); final result = Target.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'Apple iPhone 12'); - expect(result.userId, '259125845563242502'); - expect(result.providerType, 'email'); - expect(result.identifier, 'token'); + expect(result.$id, "259125845563242502"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "Apple iPhone 12"); + expect(result.userId, "259125845563242502"); + expect(result.providerType, "email"); + expect(result.identifier, "token"); expect(result.expired, true); }); }); diff --git a/test/src/models/team_test.dart b/test/src/models/team_test.dart index f652f2c1..8244762c 100644 --- a/test/src/models/team_test.dart +++ b/test/src/models/team_test.dart @@ -5,10 +5,10 @@ void main() { group('Team', () { test('model', () { final model = Team( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'VIP', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "VIP", total: 7, prefs: Preferences(data: {}), ); @@ -16,10 +16,10 @@ void main() { final map = model.toMap(); final result = Team.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'VIP'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "VIP"); expect(result.total, 7); }); }); diff --git a/test/src/models/token_test.dart b/test/src/models/token_test.dart index 8f0957c9..b747dfb8 100644 --- a/test/src/models/token_test.dart +++ b/test/src/models/token_test.dart @@ -5,23 +5,23 @@ void main() { group('Token', () { test('model', () { final model = Token( - $id: 'bb8ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - userId: '5e5ea5c168bb8', - secret: '', - expire: '2020-10-15T06:38:00.000+00:00', - phrase: 'Golden Fox', + $id: "bb8ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c168bb8", + secret: "", + expire: "2020-10-15T06:38:00.000+00:00", + phrase: "Golden Fox", ); final map = model.toMap(); final result = Token.fromMap(map); - expect(result.$id, 'bb8ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.userId, '5e5ea5c168bb8'); - expect(result.secret, ''); - expect(result.expire, '2020-10-15T06:38:00.000+00:00'); - expect(result.phrase, 'Golden Fox'); + expect(result.$id, "bb8ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c168bb8"); + expect(result.secret, ""); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); + expect(result.phrase, "Golden Fox"); }); }); } diff --git a/test/src/models/transaction_test.dart b/test/src/models/transaction_test.dart index 0169427f..98f0c882 100644 --- a/test/src/models/transaction_test.dart +++ b/test/src/models/transaction_test.dart @@ -5,23 +5,23 @@ void main() { group('Transaction', () { test('model', () { final model = Transaction( - $id: '259125845563242502', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - status: 'pending', + $id: "259125845563242502", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + status: "pending", operations: 5, - expiresAt: '2020-10-15T06:38:00.000+00:00', + expiresAt: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = Transaction.fromMap(map); - expect(result.$id, '259125845563242502'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.status, 'pending'); + expect(result.$id, "259125845563242502"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.status, "pending"); expect(result.operations, 5); - expect(result.expiresAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.expiresAt, "2020-10-15T06:38:00.000+00:00"); }); }); } diff --git a/test/src/models/user_test.dart b/test/src/models/user_test.dart index 77c7dd97..37ca37f7 100644 --- a/test/src/models/user_test.dart +++ b/test/src/models/user_test.dart @@ -5,42 +5,42 @@ void main() { group('User', () { test('model', () { final model = User( - $id: '5e5ea5c16897e', - $createdAt: '2020-10-15T06:38:00.000+00:00', - $updatedAt: '2020-10-15T06:38:00.000+00:00', - name: 'John Doe', - registration: '2020-10-15T06:38:00.000+00:00', + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "John Doe", + registration: "2020-10-15T06:38:00.000+00:00", status: true, labels: [], - passwordUpdate: '2020-10-15T06:38:00.000+00:00', - email: 'john@appwrite.io', - phone: '+4930901820', + passwordUpdate: "2020-10-15T06:38:00.000+00:00", + email: "john@appwrite.io", + phone: "+4930901820", emailVerification: true, phoneVerification: true, mfa: true, prefs: Preferences(data: {}), targets: [], - accessedAt: '2020-10-15T06:38:00.000+00:00', + accessedAt: "2020-10-15T06:38:00.000+00:00", ); final map = model.toMap(); final result = User.fromMap(map); - expect(result.$id, '5e5ea5c16897e'); - expect(result.$createdAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.$updatedAt, '2020-10-15T06:38:00.000+00:00'); - expect(result.name, 'John Doe'); - expect(result.registration, '2020-10-15T06:38:00.000+00:00'); + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "John Doe"); + expect(result.registration, "2020-10-15T06:38:00.000+00:00"); expect(result.status, true); expect(result.labels, []); - expect(result.passwordUpdate, '2020-10-15T06:38:00.000+00:00'); - expect(result.email, 'john@appwrite.io'); - expect(result.phone, '+4930901820'); + expect(result.passwordUpdate, "2020-10-15T06:38:00.000+00:00"); + expect(result.email, "john@appwrite.io"); + expect(result.phone, "+4930901820"); expect(result.emailVerification, true); expect(result.phoneVerification, true); expect(result.mfa, true); expect(result.targets, []); - expect(result.accessedAt, '2020-10-15T06:38:00.000+00:00'); + expect(result.accessedAt, "2020-10-15T06:38:00.000+00:00"); }); }); } From 292f2c072f49ac3518b87ade38d035310de277cf Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Mon, 24 Aug 2026 08:20:39 +0000 Subject: [PATCH 08/17] Commit from GitHub Actions (Format and push) --- lib/query.dart | 9 +- lib/services/databases.dart | 10 +- lib/services/organization.dart | 30 ++-- lib/services/tables_db.dart | 10 +- lib/services/teams.dart | 89 +++++++---- lib/src/client.dart | 3 +- lib/src/client_io.dart | 30 ++-- lib/src/client_mixin.dart | 15 +- lib/src/cookie_manager.dart | 22 +-- lib/src/enums.dart | 2 +- lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 ++- lib/src/realtime_mixin.dart | 181 ++++++++++++----------- lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- test/channel_test.dart | 89 ++++++----- test/services/teams_test.dart | 40 +++-- test/src/input_file_test.dart | 24 +-- test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 ++- test/src/upload_progress_test.dart | 2 +- 21 files changed, 360 insertions(+), 253 deletions(-) diff --git a/lib/query.dart b/lib/query.dart index 1ad97bdc..2e809e22 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,13 +159,15 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => Query._( + static String or(List queries) => + Query._( 'or', null, queries.map((query) => jsonDecode(query)).toList(), ).toString(); - static String and(List queries) => Query._( + static String and(List queries) => + Query._( 'and', null, queries.map((query) => jsonDecode(query)).toList(), @@ -175,7 +177,8 @@ class Query { /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => Query._( + static String elemMatch(String attribute, List queries) => + Query._( 'elemMatch', attribute, queries.map((query) => jsonDecode(query)).toList(), diff --git a/lib/services/databases.dart b/lib/services/databases.dart index aaa74ff5..adbd28cc 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -164,11 +164,11 @@ class Databases extends Service { required String transactionId, List? operations, }) async { - final String apiPath = - '/databases/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 1dd88dac..70e4576a 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -69,11 +69,11 @@ class Organization extends Service { Future getInstallation({ required String installationId, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -100,11 +100,11 @@ class Organization extends Service { required String installationId, String? authorizationDetails, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -133,11 +133,11 @@ class Organization extends Service { Future deleteInstallation({ required String installationId, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index d7f23f39..246ab939 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -146,11 +146,11 @@ class TablesDB extends Service { required String transactionId, List? operations, }) async { - final String apiPath = - '/tablesdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 201d111e..7304d3b9 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -327,10 +327,15 @@ class Teams extends Service { } /// List app installations on a team. Any team member can read installations. - Future listInstallations( - {required String teamId, List? queries, bool? total}) async { - final String apiPath = - '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + Future listInstallations({ + required String teamId, + List? queries, + bool? total, + }) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { if (queries != null) 'queries': queries, @@ -342,8 +347,12 @@ class Teams extends Service { 'accept': '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.AppInstallationList.fromMap(res.data); } @@ -352,12 +361,15 @@ class Teams extends Service { /// with the owner role can install apps. Requests using an API key or in admin /// mode can install apps on any team. The installation is granted the scopes /// the app currently requests. - Future createInstallation( - {required String teamId, - required String appId, - String? authorizationDetails}) async { - final String apiPath = - '/teams/{teamId}/installations'.replaceAll('{teamId}', teamId); + Future createInstallation({ + required String teamId, + required String appId, + String? authorizationDetails, + }) async { + final String apiPath = '/teams/{teamId}/installations'.replaceAll( + '{teamId}', + teamId, + ); final Map apiParams = { 'appId': appId, @@ -371,16 +383,22 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } /// Get an app installation on a team by its unique ID. Any team member can /// read installations. - Future getInstallation( - {required String teamId, required String installationId}) async { + Future getInstallation({ + required String teamId, + required String installationId, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll('{teamId}', teamId) .replaceAll('{installationId}', installationId); @@ -392,8 +410,12 @@ class Teams extends Service { 'accept': '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.AppInstallation.fromMap(res.data); } @@ -402,10 +424,11 @@ class Teams extends Service { /// can update installations. The installation's granted scopes are refreshed /// to the scopes the app currently requests; previously issued installation /// access tokens are revoked. - Future updateInstallation( - {required String teamId, - required String installationId, - String? authorizationDetails}) async { + Future updateInstallation({ + required String teamId, + required String installationId, + String? authorizationDetails, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll('{teamId}', teamId) .replaceAll('{installationId}', installationId); @@ -421,8 +444,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return models.AppInstallation.fromMap(res.data); } @@ -430,8 +457,10 @@ class Teams extends Service { /// Uninstall an app from a team by its installation ID. Only team members with /// the owner role can remove installations. Previously issued installation /// access tokens are revoked. - Future deleteInstallation( - {required String teamId, required String installationId}) async { + Future deleteInstallation({ + required String teamId, + required String installationId, + }) async { final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll('{teamId}', teamId) .replaceAll('{installationId}', installationId); @@ -444,8 +473,12 @@ class Teams extends Service { 'accept': 'application/json', }; - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); return res.data; } diff --git a/lib/src/client.dart b/lib/src/client.dart index dbfe4bdf..6fe9425c 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 9566820e..603c04a8 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,9 +47,10 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = + HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -357,8 +358,13 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id, - [RandomAccessFile? raf]) async { + Future uploadChunk( + int index, + int start, + int end, + String? id, [ + RandomAccessFile? raf, + ]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -482,9 +488,10 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: + callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -499,9 +506,10 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = + codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 952d7114..3ca20708 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -92,8 +92,9 @@ mixin ClientMixin { } if (res.statusCode >= 400) { - final isJson = - (res.headers['content-type'] ?? '').contains('application/json'); + final isJson = (res.headers['content-type'] ?? '').contains( + 'application/json', + ); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -141,10 +142,12 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 6b1e67cd..05253273 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,14 +17,15 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }).catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }) + .catchError((e, stackTrace) { + return request; + }); return request; } @@ -43,8 +44,9 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host), + scheme: response.request!.url.scheme, + host: response.request!.url.host, + ), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 595afdc2..0f250ea3 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes + bytes, } diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index a0f4193a..e56b7ddd 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,10 +25,12 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace(queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }); + uri = uri.replace( + queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }, + ); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..ab1c3b42 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,9 +37,11 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel((client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers)); + final websok = IOWebSocketChannel( + (client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers), + ); return websok; } @@ -73,13 +75,18 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, Map headers) async { + Uri uri, + Map headers, + ) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = - (X509Certificate cert, String host, int port) { + client.badCertificateCallback = ( + X509Certificate cert, + String host, + int port, + ) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 72edf5ee..639f2795 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,74 +100,80 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen((response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add(jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - })); + _websocketSubscription = _websok?.stream.listen( + (response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add( + jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + }), + ); + } + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; - } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': - break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': break; - } + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { + break; + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); + } } - } - break; - } - }, onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }); + break; + } + }, + onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, + onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }, + ); } catch (e) { if (e is AppwriteException) { rethrow; @@ -197,27 +203,30 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server"); + "Please set endPointRealtime to connect to realtime server", + ); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = + (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", + ); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -227,10 +236,12 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add(jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + }), + ); } String _generateUniqueSubscriptionId() { @@ -292,10 +303,12 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add(jsonEncode({ - 'type': 'subscribe', - 'data': rows, - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'subscribe', + 'data': rows, + }), + ); } void _flushPendingPresence() { @@ -312,8 +325,10 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo( + List channels, [ + List queries = const [], + ]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..631afe31 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,6 +2,7 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => throw UnsupportedError( +RealtimeBase createRealtime(Client client) => + throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index e572b519..6461e344 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..5ed52b81 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect(Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents'); + expect( + Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents', + ); }); test('returns database channel with action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), - 'databases.db1.collections.col1.documents.doc1.create'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').create().toString(), + 'databases.db1.collections.col1.documents.doc1.create', + ); }); test('returns database channel with upsert action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), - 'databases.db1.collections.col1.documents.doc1.upsert'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').upsert().toString(), + 'databases.db1.collections.col1.documents.doc1.upsert', + ); }); }); @@ -39,18 +39,17 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect(Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows'); + expect( + Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows', + ); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), - 'tablesdb.db1.tables.table1.rows.row1.update'); + Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + 'tablesdb.db1.tables.table1.rows.row1.update', + ); }); }); @@ -67,12 +66,16 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files', + ); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete'); + expect( + Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete', + ); }); }); @@ -116,13 +119,17 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect( + Channel.membership('membership1').toString(), + 'memberships.membership1', + ); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), - 'memberships.membership1.update'); + expect( + Channel.membership('membership1').update().toString(), + 'memberships.membership1.update', + ); }); }); @@ -140,23 +147,31 @@ void main() { }); test('returns presence channel with create action', () { - expect(Channel.presence('presence1').create().toString(), - 'presences.presence1.create'); + expect( + Channel.presence('presence1').create().toString(), + 'presences.presence1.create', + ); }); test('returns presence channel with upsert action', () { - expect(Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert'); + expect( + Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert', + ); }); test('returns presence channel with update action', () { - expect(Channel.presence('presence1').update().toString(), - 'presences.presence1.update'); + expect( + Channel.presence('presence1').update().toString(), + 'presences.presence1.update', + ); }); test('returns presence channel with delete action', () { - expect(Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete'); + expect( + Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete', + ); }); }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index eecb7cb6..4bab0c94 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -260,9 +260,11 @@ void main() { 'installations': [], }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call( + HttpMethod.get, + ), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.listInstallations( teamId: '', @@ -283,9 +285,11 @@ void main() { 'createdByName': 'Walter White', }; - when(client.call( - HttpMethod.post, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call( + HttpMethod.post, + ), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.createInstallation( teamId: '', @@ -307,9 +311,11 @@ void main() { 'createdByName': 'Walter White', }; - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call( + HttpMethod.get, + ), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.getInstallation( teamId: '', @@ -331,9 +337,11 @@ void main() { 'createdByName': 'Walter White', }; - when(client.call( - HttpMethod.put, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call( + HttpMethod.put, + ), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.updateInstallation( teamId: '', @@ -345,9 +353,11 @@ void main() { test('test method deleteInstallation()', () async { final data = ''; - when(client.call( - HttpMethod.delete, - )).thenAnswer((_) async => Response(data: data)); + when( + client.call( + HttpMethod.delete, + ), + ).thenAnswer((_) async => Response(data: data)); final response = await teams.deleteInstallation( teamId: '', diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 3d301a85..046fa07b 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,22 +7,26 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 4435280a..029c35bf 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,7 +48,9 @@ void main() { final responseString = response1.toString(); expect( - responseString, equals('RealtimeResponse(type: $type, data: $data)')); + responseString, + equals('RealtimeResponse(type: $type, data: $data)'), + ); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index 1515f1a3..d19e6eac 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,15 +8,18 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction( - {List? channels, List? queries}) async {} + Future mockUpdateFunction({ + List? channels, + List? queries, + }) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const []); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const [], + ); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index d21607ec..3dce66c9 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded + "chunksUploaded": chunksUploaded, }; final uploadProgress = UploadProgress( $id: id, From d7f9f6d47b7f491be136687aa67babe382ac3e5d Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 24 Aug 2026 13:58:16 +0530 Subject: [PATCH 09/17] chore: update Flutter SDK to 26.0.0 --- CHANGELOG.md | 3 +- README.md | 2 +- lib/query.dart | 9 +- lib/services/databases.dart | 10 +- lib/services/organization.dart | 30 ++-- lib/services/tables_db.dart | 10 +- lib/services/teams.dart | 157 -------------------- lib/src/client.dart | 3 +- lib/src/client_browser.dart | 2 +- lib/src/client_io.dart | 32 ++-- lib/src/client_mixin.dart | 15 +- lib/src/cookie_manager.dart | 22 ++- lib/src/enums.dart | 2 +- lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 +-- lib/src/realtime_mixin.dart | 181 +++++++++++------------ lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- pubspec.yaml | 2 +- test/channel_test.dart | 89 +++++------ test/services/teams_test.dart | 111 -------------- test/src/input_file_test.dart | 24 ++- test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 +-- test/src/upload_progress_test.dart | 2 +- 25 files changed, 216 insertions(+), 547 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e34f7506..ce971fde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,8 @@ # Change Log -## 25.5.0 +## 26.0.0 +* Breaking: `Execution.functionId` replaced by `resourceId` and `resourceType`, now that executions cover both functions and sites * Added: `avatars.getPhoto` returning the user's best available profile photo * Added: `huggingface` OAuth provider * Added: `custom` authentication factor diff --git a/README.md b/README.md index 5705a6cf..74165e5c 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^25.5.0 + appwrite: ^26.0.0 ``` You can install packages from the command line: diff --git a/lib/query.dart b/lib/query.dart index 2e809e22..1ad97bdc 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,15 +159,13 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => - Query._( + static String or(List queries) => Query._( 'or', null, queries.map((query) => jsonDecode(query)).toList(), ).toString(); - static String and(List queries) => - Query._( + static String and(List queries) => Query._( 'and', null, queries.map((query) => jsonDecode(query)).toList(), @@ -177,8 +175,7 @@ class Query { /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => - Query._( + static String elemMatch(String attribute, List queries) => Query._( 'elemMatch', attribute, queries.map((query) => jsonDecode(query)).toList(), diff --git a/lib/services/databases.dart b/lib/services/databases.dart index adbd28cc..aaa74ff5 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -164,11 +164,11 @@ class Databases extends Service { required String transactionId, List? operations, }) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = + '/databases/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 70e4576a..1dd88dac 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -69,11 +69,11 @@ class Organization extends Service { Future getInstallation({ required String installationId, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -100,11 +100,11 @@ class Organization extends Service { required String installationId, String? authorizationDetails, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -133,11 +133,11 @@ class Organization extends Service { Future deleteInstallation({ required String installationId, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 246ab939..d7f23f39 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -146,11 +146,11 @@ class TablesDB extends Service { required String transactionId, List? operations, }) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = + '/tablesdb/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 7304d3b9..99190fc1 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -326,163 +326,6 @@ class Teams extends Service { return res.data; } - /// List app installations on a team. Any team member can read installations. - Future listInstallations({ - required String teamId, - List? queries, - bool? total, - }) async { - final String apiPath = '/teams/{teamId}/installations'.replaceAll( - '{teamId}', - teamId, - ); - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return models.AppInstallationList.fromMap(res.data); - } - - /// Install an app on a team. When authenticated as a user, only team members - /// with the owner role can install apps. Requests using an API key or in admin - /// mode can install apps on any team. The installation is granted the scopes - /// the app currently requests. - Future createInstallation({ - required String teamId, - required String appId, - String? authorizationDetails, - }) async { - final String apiPath = '/teams/{teamId}/installations'.replaceAll( - '{teamId}', - teamId, - ); - - final Map apiParams = { - 'appId': appId, - if (authorizationDetails != null) - 'authorizationDetails': authorizationDetails, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.post, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return models.AppInstallation.fromMap(res.data); - } - - /// Get an app installation on a team by its unique ID. Any team member can - /// read installations. - Future getInstallation({ - required String teamId, - required String installationId, - }) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return models.AppInstallation.fromMap(res.data); - } - - /// Update an app installation on a team. Only team members with the owner role - /// can update installations. The installation's granted scopes are refreshed - /// to the scopes the app currently requests; previously issued installation - /// access tokens are revoked. - Future updateInstallation({ - required String teamId, - required String installationId, - String? authorizationDetails, - }) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); - - final Map apiParams = { - if (authorizationDetails != null) - 'authorizationDetails': authorizationDetails, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.put, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return models.AppInstallation.fromMap(res.data); - } - - /// Uninstall an app from a team by its installation ID. Only team members with - /// the owner role can remove installations. Previously issued installation - /// access tokens are revoked. - Future deleteInstallation({ - required String teamId, - required String installationId, - }) async { - final String apiPath = '/teams/{teamId}/installations/{installationId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{installationId}', installationId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'content-type': 'application/json', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.delete, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return res.data; - } - /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from /// the response by toggling membership privacy in the Console. diff --git a/lib/src/client.dart b/lib/src/client.dart index 6fe9425c..dbfe4bdf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,7 +27,8 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => + createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 279868ed..63a87c51 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.5.0', + 'x-sdk-version': '26.0.0', 'X-Appwrite-Response-Format': '1.9.6', }; diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 603c04a8..88f6c8d9 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,10 +47,9 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = - HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -60,7 +59,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '25.5.0', + 'x-sdk-version': '26.0.0', 'X-Appwrite-Response-Format': '1.9.6', }; @@ -358,13 +357,8 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk( - int index, - int start, - int end, - String? id, [ - RandomAccessFile? raf, - ]) async { + Future uploadChunk(int index, int start, int end, String? id, + [RandomAccessFile? raf]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -488,10 +482,9 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: - callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -506,10 +499,9 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = - codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 3ca20708..952d7114 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -92,9 +92,8 @@ mixin ClientMixin { } if (res.statusCode >= 400) { - final isJson = (res.headers['content-type'] ?? '').contains( - 'application/json', - ); + final isJson = + (res.headers['content-type'] ?? '').contains('application/json'); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -142,12 +141,10 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map( - (k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v), - ), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 05253273..6b1e67cd 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,15 +17,14 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }) - .catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }).catchError((e, stackTrace) { + return request; + }); return request; } @@ -44,9 +43,8 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host, - ), + scheme: response.request!.url.scheme, + host: response.request!.url.host), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 0f250ea3..595afdc2 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes, + bytes } diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index e56b7ddd..a0f4193a 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,12 +25,10 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace( - queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }, - ); + uri = uri.replace(queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index ab1c3b42..0ed367a6 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,11 +37,9 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel( - (client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers), - ); + final websok = IOWebSocketChannel((client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers)); return websok; } @@ -75,18 +73,13 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, - Map headers, - ) async { + Uri uri, Map headers) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = ( - X509Certificate cert, - String host, - int port, - ) { + client.badCertificateCallback = + (X509Certificate cert, String host, int port) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 639f2795..72edf5ee 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,80 +100,74 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen( - (response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add( - jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - }), - ); - } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; + _websocketSubscription = _websok?.stream.listen((response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add(jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + })); } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; + } + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': + break; + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { - break; - } + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); - } + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); } - break; - } - }, - onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, - onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }, - ); + } + break; + } + }, onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }); } catch (e) { if (e is AppwriteException) { rethrow; @@ -203,30 +197,27 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server", - ); + "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = - (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", - ); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -236,12 +227,10 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add( - jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - }), - ); + _websok!.sink.add(jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + })); } String _generateUniqueSubscriptionId() { @@ -303,12 +292,10 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add( - jsonEncode({ - 'type': 'subscribe', - 'data': rows, - }), - ); + _websok!.sink.add(jsonEncode({ + 'type': 'subscribe', + 'data': rows, + })); } void _flushPendingPresence() { @@ -325,10 +312,8 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo( - List channels, [ - List queries = const [], - ]) { + RealtimeSubscription subscribeTo(List channels, + [List queries = const []]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 631afe31..3aab4e03 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,7 +2,6 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => - throw UnsupportedError( +RealtimeBase createRealtime(Client client) => throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index 6461e344..e572b519 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/pubspec.yaml b/pubspec.yaml index ee810a5f..ee9ee40c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 25.5.0 +version: 26.0.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies 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/channel_test.dart b/test/channel_test.dart index 5ed52b81..9e0e11d3 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect( - Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents', - ); + expect(Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents'); }); test('returns database channel with action', () { expect( - Channel.database( - 'db1', - ).collection('col1').document('doc1').create().toString(), - 'databases.db1.collections.col1.documents.doc1.create', - ); + Channel.database('db1') + .collection('col1') + .document('doc1') + .create() + .toString(), + 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { expect( - Channel.database( - 'db1', - ).collection('col1').document('doc1').upsert().toString(), - 'databases.db1.collections.col1.documents.doc1.upsert', - ); + Channel.database('db1') + .collection('col1') + .document('doc1') + .upsert() + .toString(), + 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -39,17 +39,18 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect( - Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows', - ); + expect(Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows'); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1').table('table1').row('row1').update().toString(), - 'tablesdb.db1.tables.table1.rows.row1.update', - ); + Channel.tablesdb('db1') + .table('table1') + .row('row1') + .update() + .toString(), + 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -66,16 +67,12 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), - 'buckets.bucket1.files', - ); + Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect( - Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete', - ); + expect(Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete'); }); }); @@ -119,17 +116,13 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect( - Channel.membership('membership1').toString(), - 'memberships.membership1', - ); + expect(Channel.membership('membership1').toString(), + 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect( - Channel.membership('membership1').update().toString(), - 'memberships.membership1.update', - ); + expect(Channel.membership('membership1').update().toString(), + 'memberships.membership1.update'); }); }); @@ -147,31 +140,23 @@ void main() { }); test('returns presence channel with create action', () { - expect( - Channel.presence('presence1').create().toString(), - 'presences.presence1.create', - ); + expect(Channel.presence('presence1').create().toString(), + 'presences.presence1.create'); }); test('returns presence channel with upsert action', () { - expect( - Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert', - ); + expect(Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert'); }); test('returns presence channel with update action', () { - expect( - Channel.presence('presence1').update().toString(), - 'presences.presence1.update', - ); + expect(Channel.presence('presence1').update().toString(), + 'presences.presence1.update'); }); test('returns presence channel with delete action', () { - expect( - Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete', - ); + expect(Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete'); }); }); } diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index 4bab0c94..cafe8858 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -254,117 +254,6 @@ void main() { ); }); - test('test method listInstallations()', () async { - final Map data = { - 'total': 5, - 'installations': [], - }; - - when( - client.call( - HttpMethod.get, - ), - ).thenAnswer((_) async => Response(data: data)); - - final response = await teams.listInstallations( - teamId: '', - ); - expect(response, isA()); - }); - - test('test method createInstallation()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - }; - - when( - client.call( - HttpMethod.post, - ), - ).thenAnswer((_) async => Response(data: data)); - - final response = await teams.createInstallation( - teamId: '', - appId: '', - ); - expect(response, isA()); - }); - - test('test method getInstallation()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - }; - - when( - client.call( - HttpMethod.get, - ), - ).thenAnswer((_) async => Response(data: data)); - - final response = await teams.getInstallation( - teamId: '', - installationId: '', - ); - expect(response, isA()); - }); - - test('test method updateInstallation()', () async { - final Map data = { - '\$id': '5e5ea5c16897e', - '\$createdAt': '2020-10-15T06:38:00.000+00:00', - '\$updatedAt': '2020-10-15T06:38:00.000+00:00', - 'appId': '5e5ea5c16897e', - 'teamId': '5e5ea5c16897e', - 'scopes': [], - 'authorizationDetails': {}, - 'createdById': '5e5ea5c16897e', - 'createdByName': 'Walter White', - }; - - when( - client.call( - HttpMethod.put, - ), - ).thenAnswer((_) async => Response(data: data)); - - final response = await teams.updateInstallation( - teamId: '', - installationId: '', - ); - expect(response, isA()); - }); - - test('test method deleteInstallation()', () async { - final data = ''; - - when( - client.call( - HttpMethod.delete, - ), - ).thenAnswer((_) async => Response(data: data)); - - final response = await teams.deleteInstallation( - teamId: '', - installationId: '', - ); - }); - test('test method listMemberships()', () async { final Map data = { 'total': 5, diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 046fa07b..3d301a85 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,26 +7,22 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - ), - ), + throwsA(isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + )), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - ), - ), + throwsA(isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + )), ); }); diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 029c35bf..4435280a 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,9 +48,7 @@ void main() { final responseString = response1.toString(); expect( - responseString, - equals('RealtimeResponse(type: $type, data: $data)'), - ); + responseString, equals('RealtimeResponse(type: $type, data: $data)')); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index d19e6eac..1515f1a3 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,18 +8,15 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction({ - List? channels, - List? queries, - }) async {} + Future mockUpdateFunction( + {List? channels, List? queries}) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const [], - ); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const []); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index 3dce66c9..d21607ec 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, + "chunksUploaded": chunksUploaded }; final uploadProgress = UploadProgress( $id: id, From 9c107fb077ce3659f83dc31f90f20d7ccdc6dfd7 Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Mon, 24 Aug 2026 08:29:41 +0000 Subject: [PATCH 10/17] Commit from GitHub Actions (Format and push) --- lib/query.dart | 9 +- lib/services/databases.dart | 10 +- lib/services/organization.dart | 30 ++-- lib/services/tables_db.dart | 10 +- lib/src/client.dart | 3 +- lib/src/client_io.dart | 30 ++-- lib/src/client_mixin.dart | 15 +- lib/src/cookie_manager.dart | 22 +-- lib/src/enums.dart | 2 +- lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 ++- lib/src/realtime_mixin.dart | 181 ++++++++++++----------- lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- test/channel_test.dart | 89 ++++++----- test/src/input_file_test.dart | 24 +-- test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 ++- test/src/upload_progress_test.dart | 2 +- 19 files changed, 274 insertions(+), 210 deletions(-) diff --git a/lib/query.dart b/lib/query.dart index 1ad97bdc..2e809e22 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,13 +159,15 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => Query._( + static String or(List queries) => + Query._( 'or', null, queries.map((query) => jsonDecode(query)).toList(), ).toString(); - static String and(List queries) => Query._( + static String and(List queries) => + Query._( 'and', null, queries.map((query) => jsonDecode(query)).toList(), @@ -175,7 +177,8 @@ class Query { /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => Query._( + static String elemMatch(String attribute, List queries) => + Query._( 'elemMatch', attribute, queries.map((query) => jsonDecode(query)).toList(), diff --git a/lib/services/databases.dart b/lib/services/databases.dart index aaa74ff5..adbd28cc 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -164,11 +164,11 @@ class Databases extends Service { required String transactionId, List? operations, }) async { - final String apiPath = - '/databases/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 1dd88dac..70e4576a 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -69,11 +69,11 @@ class Organization extends Service { Future getInstallation({ required String installationId, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -100,11 +100,11 @@ class Organization extends Service { required String installationId, String? authorizationDetails, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -133,11 +133,11 @@ class Organization extends Service { Future deleteInstallation({ required String installationId, }) async { - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index d7f23f39..246ab939 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -146,11 +146,11 @@ class TablesDB extends Service { required String transactionId, List? operations, }) async { - final String apiPath = - '/tablesdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/src/client.dart b/lib/src/client.dart index dbfe4bdf..6fe9425c 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 88f6c8d9..ee52e2ea 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,9 +47,10 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = + HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -357,8 +358,13 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id, - [RandomAccessFile? raf]) async { + Future uploadChunk( + int index, + int start, + int end, + String? id, [ + RandomAccessFile? raf, + ]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -482,9 +488,10 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: + callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -499,9 +506,10 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = + codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 952d7114..3ca20708 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -92,8 +92,9 @@ mixin ClientMixin { } if (res.statusCode >= 400) { - final isJson = - (res.headers['content-type'] ?? '').contains('application/json'); + final isJson = (res.headers['content-type'] ?? '').contains( + 'application/json', + ); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -141,10 +142,12 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 6b1e67cd..05253273 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,14 +17,15 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }).catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }) + .catchError((e, stackTrace) { + return request; + }); return request; } @@ -43,8 +44,9 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host), + scheme: response.request!.url.scheme, + host: response.request!.url.host, + ), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 595afdc2..0f250ea3 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes + bytes, } diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index a0f4193a..e56b7ddd 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,10 +25,12 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace(queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }); + uri = uri.replace( + queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }, + ); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..ab1c3b42 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,9 +37,11 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel((client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers)); + final websok = IOWebSocketChannel( + (client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers), + ); return websok; } @@ -73,13 +75,18 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, Map headers) async { + Uri uri, + Map headers, + ) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = - (X509Certificate cert, String host, int port) { + client.badCertificateCallback = ( + X509Certificate cert, + String host, + int port, + ) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 72edf5ee..639f2795 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,74 +100,80 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen((response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add(jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - })); + _websocketSubscription = _websok?.stream.listen( + (response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add( + jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + }), + ); + } + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; - } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': - break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': break; - } + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { + break; + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); + } } - } - break; - } - }, onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }); + break; + } + }, + onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, + onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }, + ); } catch (e) { if (e is AppwriteException) { rethrow; @@ -197,27 +203,30 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server"); + "Please set endPointRealtime to connect to realtime server", + ); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = + (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", + ); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -227,10 +236,12 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add(jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + }), + ); } String _generateUniqueSubscriptionId() { @@ -292,10 +303,12 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add(jsonEncode({ - 'type': 'subscribe', - 'data': rows, - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'subscribe', + 'data': rows, + }), + ); } void _flushPendingPresence() { @@ -312,8 +325,10 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo( + List channels, [ + List queries = const [], + ]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..631afe31 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,6 +2,7 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => throw UnsupportedError( +RealtimeBase createRealtime(Client client) => + throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index e572b519..6461e344 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..5ed52b81 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect(Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents'); + expect( + Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents', + ); }); test('returns database channel with action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), - 'databases.db1.collections.col1.documents.doc1.create'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').create().toString(), + 'databases.db1.collections.col1.documents.doc1.create', + ); }); test('returns database channel with upsert action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), - 'databases.db1.collections.col1.documents.doc1.upsert'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').upsert().toString(), + 'databases.db1.collections.col1.documents.doc1.upsert', + ); }); }); @@ -39,18 +39,17 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect(Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows'); + expect( + Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows', + ); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), - 'tablesdb.db1.tables.table1.rows.row1.update'); + Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + 'tablesdb.db1.tables.table1.rows.row1.update', + ); }); }); @@ -67,12 +66,16 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files', + ); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete'); + expect( + Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete', + ); }); }); @@ -116,13 +119,17 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect( + Channel.membership('membership1').toString(), + 'memberships.membership1', + ); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), - 'memberships.membership1.update'); + expect( + Channel.membership('membership1').update().toString(), + 'memberships.membership1.update', + ); }); }); @@ -140,23 +147,31 @@ void main() { }); test('returns presence channel with create action', () { - expect(Channel.presence('presence1').create().toString(), - 'presences.presence1.create'); + expect( + Channel.presence('presence1').create().toString(), + 'presences.presence1.create', + ); }); test('returns presence channel with upsert action', () { - expect(Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert'); + expect( + Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert', + ); }); test('returns presence channel with update action', () { - expect(Channel.presence('presence1').update().toString(), - 'presences.presence1.update'); + expect( + Channel.presence('presence1').update().toString(), + 'presences.presence1.update', + ); }); test('returns presence channel with delete action', () { - expect(Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete'); + expect( + Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete', + ); }); }); } diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 3d301a85..046fa07b 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,22 +7,26 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 4435280a..029c35bf 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,7 +48,9 @@ void main() { final responseString = response1.toString(); expect( - responseString, equals('RealtimeResponse(type: $type, data: $data)')); + responseString, + equals('RealtimeResponse(type: $type, data: $data)'), + ); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index 1515f1a3..d19e6eac 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,15 +8,18 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction( - {List? channels, List? queries}) async {} + Future mockUpdateFunction({ + List? channels, + List? queries, + }) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const []); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const [], + ); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index d21607ec..3dce66c9 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded + "chunksUploaded": chunksUploaded, }; final uploadProgress = UploadProgress( $id: id, From 11e368fdcc6e72ea57dd0b0765ce35f877e8830d Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 24 Aug 2026 14:06:05 +0530 Subject: [PATCH 11/17] chore: remove auto-formatting workflow, the generator now emits formatted code --- .github/workflows/format.yml | 39 ------------------------------------ 1 file changed, 39 deletions(-) delete mode 100644 .github/workflows/format.yml diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml deleted file mode 100644 index 0e4bf293..00000000 --- a/.github/workflows/format.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Format and push - -# Github action will require permission to write to repo -on: - pull_request: - branches: - - main - workflow_dispatch: - -jobs: - format: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: true - ref: ${{ github.event.pull_request.head.ref }} - - - name: Install Flutter - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 - with: - channel: stable - - - name: Install dependencies - run: flutter pub get - - - name: Format Dart code - run: dart format . - - - name: git config - run: git config --global --add safe.directory /__w/sdk-for-flutter/sdk-for-flutter # required to fix dubious ownership - - - name: Add & Commit - uses: EndBug/add-and-commit@290ea2c423ad77ca9c62ae0f5b224379612c0321 # v10.0.0 - with: - add: '["lib", "test"]' - From 8bab69b4a9c7c80e9d07d30166b8ab722717c8d2 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 7 Sep 2026 15:58:04 +0100 Subject: [PATCH 12/17] chore: update Flutter SDK to 26.2.0 --- CHANGELOG.md | 11 + README.md | 6 +- docs/examples/avatars/get-initials.md | 4 +- docs/examples/avatars/get-photo.md | 6 + .../databases/decrement-document-attribute.md | 4 +- .../databases/increment-document-attribute.md | 6 +- docs/examples/documentsdb/create-document.md | 26 + docs/examples/documentsdb/create-documents.md | 16 + .../examples/documentsdb/create-operations.md | 24 + .../documentsdb/create-transaction.md | 13 + .../decrement-document-attribute.md | 19 + docs/examples/documentsdb/delete-document.md | 16 + .../documentsdb/delete-transaction.md | 13 + docs/examples/documentsdb/get-document.md | 17 + docs/examples/documentsdb/get-transaction.md | 13 + .../increment-document-attribute.md | 19 + docs/examples/documentsdb/list-documents.md | 18 + .../examples/documentsdb/list-transactions.md | 13 + docs/examples/documentsdb/update-document.md | 20 + .../documentsdb/update-transaction.md | 15 + docs/examples/documentsdb/upsert-document.md | 20 + docs/examples/storage/create-file.md | 2 +- docs/examples/storage/get-file-preview.md | 8 +- .../examples/tablesdb/decrement-row-column.md | 4 +- .../examples/tablesdb/increment-row-column.md | 6 +- docs/examples/vectorsdb/create-document.md | 30 + docs/examples/vectorsdb/create-operations.md | 24 + docs/examples/vectorsdb/create-query.md | 18 + docs/examples/vectorsdb/create-transaction.md | 13 + docs/examples/vectorsdb/delete-document.md | 16 + docs/examples/vectorsdb/delete-transaction.md | 13 + docs/examples/vectorsdb/get-document.md | 17 + docs/examples/vectorsdb/get-transaction.md | 13 + docs/examples/vectorsdb/list-documents.md | 18 + docs/examples/vectorsdb/list-transactions.md | 13 + docs/examples/vectorsdb/update-document.md | 20 + docs/examples/vectorsdb/update-transaction.md | 15 + docs/examples/vectorsdb/upsert-document.md | 20 + lib/appwrite.dart | 10 +- lib/query.dart | 9 +- lib/services/avatars.dart | 25 +- lib/services/databases.dart | 10 +- lib/services/documents_db.dart | 589 ++++++++++++++++++ lib/services/organization.dart | 30 +- lib/services/tables_db.dart | 10 +- lib/services/vectors_db.dart | 488 +++++++++++++++ lib/src/client.dart | 3 +- lib/src/client_browser.dart | 4 +- lib/src/client_io.dart | 34 +- lib/src/client_mixin.dart | 15 +- lib/src/cookie_manager.dart | 22 +- lib/src/enums.dart | 2 +- lib/src/enums/o_auth_provider.dart | 2 + lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 +- lib/src/realtime_mixin.dart | 187 +++--- lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- pubspec.yaml | 2 +- test/channel_test.dart | 89 ++- test/services/databases_test.dart | 4 +- test/services/documents_db_test.dart | 362 +++++++++++ test/services/tables_db_test.dart | 4 +- test/services/vectors_db_test.dart | 313 ++++++++++ test/src/input_file_test.dart | 24 +- test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 +- test/src/upload_progress_test.dart | 2 +- 68 files changed, 2535 insertions(+), 311 deletions(-) create mode 100644 docs/examples/documentsdb/create-document.md create mode 100644 docs/examples/documentsdb/create-documents.md create mode 100644 docs/examples/documentsdb/create-operations.md create mode 100644 docs/examples/documentsdb/create-transaction.md create mode 100644 docs/examples/documentsdb/decrement-document-attribute.md create mode 100644 docs/examples/documentsdb/delete-document.md create mode 100644 docs/examples/documentsdb/delete-transaction.md create mode 100644 docs/examples/documentsdb/get-document.md create mode 100644 docs/examples/documentsdb/get-transaction.md create mode 100644 docs/examples/documentsdb/increment-document-attribute.md create mode 100644 docs/examples/documentsdb/list-documents.md create mode 100644 docs/examples/documentsdb/list-transactions.md create mode 100644 docs/examples/documentsdb/update-document.md create mode 100644 docs/examples/documentsdb/update-transaction.md create mode 100644 docs/examples/documentsdb/upsert-document.md create mode 100644 docs/examples/vectorsdb/create-document.md create mode 100644 docs/examples/vectorsdb/create-operations.md create mode 100644 docs/examples/vectorsdb/create-query.md create mode 100644 docs/examples/vectorsdb/create-transaction.md create mode 100644 docs/examples/vectorsdb/delete-document.md create mode 100644 docs/examples/vectorsdb/delete-transaction.md create mode 100644 docs/examples/vectorsdb/get-document.md create mode 100644 docs/examples/vectorsdb/get-transaction.md create mode 100644 docs/examples/vectorsdb/list-documents.md create mode 100644 docs/examples/vectorsdb/list-transactions.md create mode 100644 docs/examples/vectorsdb/update-document.md create mode 100644 docs/examples/vectorsdb/update-transaction.md create mode 100644 docs/examples/vectorsdb/upsert-document.md create mode 100644 lib/services/documents_db.dart create mode 100644 lib/services/vectors_db.dart create mode 100644 test/services/documents_db_test.dart create mode 100644 test/services/vectors_db_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index ce971fde..a1ecf988 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change Log +## 26.2.0 + +* Added: `DocumentsDB` and `VectorsDB` services for document and vector database access +* Added: `userId`, `emailHash` and `name` parameters to `Avatars.getPhoto()` +* Added: `cloudflare` and `resend` values to `OAuthProvider` enum +* Updated: `X-Appwrite-Response-Format` header to `2.0.0` + +## 26.1.0 + +* Fixed: realtime policy-violation errors are now delivered to active subscription streams instead of thrown from the message handler + ## 26.0.0 * Breaking: `Execution.functionId` replaced by `resourceId` and `resourceType`, now that executions cover both functions and sites diff --git a/README.md b/README.md index 74165e5c..9220945b 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ [![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.9.x-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-2.0.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) -**This SDK is compatible with Appwrite server version 1.9.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-flutter/releases).** +**This SDK targets Appwrite server version 1.9.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) when APIs differ. Appwrite is an open-source backend as a service server that abstracts and simplifies 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) @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^26.0.0 + appwrite: ^26.2.0 ``` You can install packages from the command line: diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index c832a1c8..89e20e7c 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -15,7 +15,7 @@ Uint8List bytes = await avatars.getInitials( name: '', // optional width: 0, // optional height: 0, // optional - background: '', // optional + background: 'FFFFFF', // optional ); final file = File('path_to_file/filename.ext'); @@ -27,7 +27,7 @@ FutureBuilder( name: '', // optional width: 0, // optional height: 0, // optional - background: '', // optional + background: 'FFFFFF', // optional ), // 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 diff --git a/docs/examples/avatars/get-photo.md b/docs/examples/avatars/get-photo.md index d9baf564..371b19d9 100644 --- a/docs/examples/avatars/get-photo.md +++ b/docs/examples/avatars/get-photo.md @@ -17,6 +17,9 @@ Uint8List bytes = await avatars.getPhoto( quality: 0, // optional output: 'png', // optional rating: 'g', // optional + userId: 'current()', // optional + emailHash: '', // optional + name: '', // optional ); final file = File('path_to_file/filename.ext'); @@ -30,6 +33,9 @@ FutureBuilder( quality: 0, // optional output: 'png', // optional rating: 'g', // optional + userId: 'current()', // optional + emailHash: '', // optional + name: '', // optional ), // 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 diff --git a/docs/examples/databases/decrement-document-attribute.md b/docs/examples/databases/decrement-document-attribute.md index 83eaf379..0d178cff 100644 --- a/docs/examples/databases/decrement-document-attribute.md +++ b/docs/examples/databases/decrement-document-attribute.md @@ -11,8 +11,8 @@ Document result = await databases.decrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', - attribute: '', - value: 0, // optional + attribute: '', + value: 1, // optional min: 0, // optional transactionId: '', // optional ); diff --git a/docs/examples/databases/increment-document-attribute.md b/docs/examples/databases/increment-document-attribute.md index 22ec3431..05b3690e 100644 --- a/docs/examples/databases/increment-document-attribute.md +++ b/docs/examples/databases/increment-document-attribute.md @@ -11,9 +11,9 @@ Document result = await databases.incrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', - attribute: '', - value: 0, // optional - max: 0, // optional + attribute: '', + value: 1, // optional + max: 100, // optional transactionId: '', // optional ); ``` diff --git a/docs/examples/documentsdb/create-document.md b/docs/examples/documentsdb/create-document.md new file mode 100644 index 00000000..d4b564e2 --- /dev/null +++ b/docs/examples/documentsdb/create-document.md @@ -0,0 +1,26 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: { + "username": "walter.obrien", + "email": "walter.obrien@example.com", + "fullName": "Walter O'Brien", + "age": 30, + "isAdmin": false + }, + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/create-documents.md b/docs/examples/documentsdb/create-documents.md new file mode 100644 index 00000000..6a508373 --- /dev/null +++ b/docs/examples/documentsdb/create-documents.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +DocumentList result = await documentsDB.createDocuments( + databaseId: '', + collectionId: '', + documents: [], + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/create-operations.md b/docs/examples/documentsdb/create-operations.md new file mode 100644 index 00000000..a4d1ecdd --- /dev/null +++ b/docs/examples/documentsdb/create-operations.md @@ -0,0 +1,24 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Transaction result = await documentsDB.createOperations( + transactionId: '', + operations: [ + { + "action": "create", + "databaseId": "", + "collectionId": "", + "documentId": "", + "data": { + "name": "Walter O'Brien" + } + } + ], // optional +); +``` diff --git a/docs/examples/documentsdb/create-transaction.md b/docs/examples/documentsdb/create-transaction.md new file mode 100644 index 00000000..2d9cb9f7 --- /dev/null +++ b/docs/examples/documentsdb/create-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Transaction result = await documentsDB.createTransaction( + ttl: 60, // optional +); +``` diff --git a/docs/examples/documentsdb/decrement-document-attribute.md b/docs/examples/documentsdb/decrement-document-attribute.md new file mode 100644 index 00000000..dcdac3aa --- /dev/null +++ b/docs/examples/documentsdb/decrement-document-attribute.md @@ -0,0 +1,19 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.decrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + value: 1, // optional + min: 0, // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/delete-document.md b/docs/examples/documentsdb/delete-document.md new file mode 100644 index 00000000..8d59422e --- /dev/null +++ b/docs/examples/documentsdb/delete-document.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +await documentsDB.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/delete-transaction.md b/docs/examples/documentsdb/delete-transaction.md new file mode 100644 index 00000000..9b95d948 --- /dev/null +++ b/docs/examples/documentsdb/delete-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +await documentsDB.deleteTransaction( + transactionId: '', +); +``` diff --git a/docs/examples/documentsdb/get-document.md b/docs/examples/documentsdb/get-document.md new file mode 100644 index 00000000..45db46e6 --- /dev/null +++ b/docs/examples/documentsdb/get-document.md @@ -0,0 +1,17 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + queries: [], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/get-transaction.md b/docs/examples/documentsdb/get-transaction.md new file mode 100644 index 00000000..4b1a5f1f --- /dev/null +++ b/docs/examples/documentsdb/get-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Transaction result = await documentsDB.getTransaction( + transactionId: '', +); +``` diff --git a/docs/examples/documentsdb/increment-document-attribute.md b/docs/examples/documentsdb/increment-document-attribute.md new file mode 100644 index 00000000..c2c6e95c --- /dev/null +++ b/docs/examples/documentsdb/increment-document-attribute.md @@ -0,0 +1,19 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.incrementDocumentAttribute( + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + value: 1, // optional + max: 100, // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/list-documents.md b/docs/examples/documentsdb/list-documents.md new file mode 100644 index 00000000..92d2651c --- /dev/null +++ b/docs/examples/documentsdb/list-documents.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +DocumentList result = await documentsDB.listDocuments( + databaseId: '', + collectionId: '', + queries: [], // optional + transactionId: '', // optional + total: false, // optional + ttl: 0, // optional +); +``` diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md new file mode 100644 index 00000000..d2c09525 --- /dev/null +++ b/docs/examples/documentsdb/list-transactions.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +TransactionList result = await documentsDB.listTransactions( + queries: [], // optional +); +``` diff --git a/docs/examples/documentsdb/update-document.md b/docs/examples/documentsdb/update-document.md new file mode 100644 index 00000000..1b9fba9a --- /dev/null +++ b/docs/examples/documentsdb/update-document.md @@ -0,0 +1,20 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/documentsdb/update-transaction.md b/docs/examples/documentsdb/update-transaction.md new file mode 100644 index 00000000..ebcf17be --- /dev/null +++ b/docs/examples/documentsdb/update-transaction.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Transaction result = await documentsDB.updateTransaction( + transactionId: '', + commit: false, // optional + rollback: false, // optional +); +``` diff --git a/docs/examples/documentsdb/upsert-document.md b/docs/examples/documentsdb/upsert-document.md new file mode 100644 index 00000000..bdf3844b --- /dev/null +++ b/docs/examples/documentsdb/upsert-document.md @@ -0,0 +1,20 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +DocumentsDB documentsDB = DocumentsDB(client); + +Document result = await documentsDB.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 007abee4..7d8fbd13 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -15,6 +15,6 @@ File result = await storage.createFile( fileId: '', file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), permissions: [Permission.read(Role.any())], // optional - folder: '', // optional + folder: 'photos/2026', // optional ); ``` diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index bfb15b91..274b4224 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -20,11 +20,11 @@ Uint8List bytes = await storage.getFilePreview( gravity: enums.ImageGravity.center, // optional quality: -1, // optional borderWidth: 0, // optional - borderColor: '', // optional + borderColor: 'FFFFFF', // optional borderRadius: 0, // optional opacity: 0, // optional rotation: -360, // optional - background: '', // optional + background: 'FFFFFF', // optional output: enums.ImageFormat.jpg, // optional token: '', // optional ); @@ -42,11 +42,11 @@ FutureBuilder( gravity: enums.ImageGravity.center, // optional quality: -1, // optional borderWidth: 0, // optional - borderColor: '', // optional + borderColor: 'FFFFFF', // optional borderRadius: 0, // optional opacity: 0, // optional rotation: -360, // optional - background: '', // optional + background: 'FFFFFF', // optional output: enums.ImageFormat.jpg, // optional token: '', // optional ), // Works for both public file and private file, for private files you need to be logged in diff --git a/docs/examples/tablesdb/decrement-row-column.md b/docs/examples/tablesdb/decrement-row-column.md index 699badfc..bee4987f 100644 --- a/docs/examples/tablesdb/decrement-row-column.md +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -11,8 +11,8 @@ Row result = await tablesDB.decrementRowColumn( databaseId: '', tableId: '', rowId: '', - column: '', - value: 0, // optional + column: '', + value: 1, // optional min: 0, // optional transactionId: '', // optional ); diff --git a/docs/examples/tablesdb/increment-row-column.md b/docs/examples/tablesdb/increment-row-column.md index 1837125e..9b0e4769 100644 --- a/docs/examples/tablesdb/increment-row-column.md +++ b/docs/examples/tablesdb/increment-row-column.md @@ -11,9 +11,9 @@ Row result = await tablesDB.incrementRowColumn( databaseId: '', tableId: '', rowId: '', - column: '', - value: 0, // optional - max: 0, // optional + column: '', + value: 1, // optional + max: 100, // optional transactionId: '', // optional ); ``` diff --git a/docs/examples/vectorsdb/create-document.md b/docs/examples/vectorsdb/create-document.md new file mode 100644 index 00000000..fc39a7c1 --- /dev/null +++ b/docs/examples/vectorsdb/create-document.md @@ -0,0 +1,30 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Document result = await vectorsDB.createDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: { + "embeddings": [ + 0.12, + -0.55, + 0.88, + 1.02 + ], + "metadata": { + "key": "value" + } + }, + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/vectorsdb/create-operations.md b/docs/examples/vectorsdb/create-operations.md new file mode 100644 index 00000000..a994693e --- /dev/null +++ b/docs/examples/vectorsdb/create-operations.md @@ -0,0 +1,24 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Transaction result = await vectorsDB.createOperations( + transactionId: '', + operations: [ + { + "action": "create", + "databaseId": "", + "collectionId": "", + "documentId": "", + "data": { + "name": "Walter O'Brien" + } + } + ], // optional +); +``` diff --git a/docs/examples/vectorsdb/create-query.md b/docs/examples/vectorsdb/create-query.md new file mode 100644 index 00000000..fa41ee5c --- /dev/null +++ b/docs/examples/vectorsdb/create-query.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +DocumentList result = await vectorsDB.createQuery( + databaseId: '', + collectionId: '', + queries: [], // optional + transactionId: '', // optional + total: false, // optional + ttl: 0, // optional +); +``` diff --git a/docs/examples/vectorsdb/create-transaction.md b/docs/examples/vectorsdb/create-transaction.md new file mode 100644 index 00000000..9c8c96d3 --- /dev/null +++ b/docs/examples/vectorsdb/create-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Transaction result = await vectorsDB.createTransaction( + ttl: 60, // optional +); +``` diff --git a/docs/examples/vectorsdb/delete-document.md b/docs/examples/vectorsdb/delete-document.md new file mode 100644 index 00000000..7827d9c3 --- /dev/null +++ b/docs/examples/vectorsdb/delete-document.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +await vectorsDB.deleteDocument( + databaseId: '', + collectionId: '', + documentId: '', + transactionId: '', // optional +); +``` diff --git a/docs/examples/vectorsdb/delete-transaction.md b/docs/examples/vectorsdb/delete-transaction.md new file mode 100644 index 00000000..e4b82888 --- /dev/null +++ b/docs/examples/vectorsdb/delete-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +await vectorsDB.deleteTransaction( + transactionId: '', +); +``` diff --git a/docs/examples/vectorsdb/get-document.md b/docs/examples/vectorsdb/get-document.md new file mode 100644 index 00000000..28e544b3 --- /dev/null +++ b/docs/examples/vectorsdb/get-document.md @@ -0,0 +1,17 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Document result = await vectorsDB.getDocument( + databaseId: '', + collectionId: '', + documentId: '', + queries: [], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/vectorsdb/get-transaction.md b/docs/examples/vectorsdb/get-transaction.md new file mode 100644 index 00000000..1d191d09 --- /dev/null +++ b/docs/examples/vectorsdb/get-transaction.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Transaction result = await vectorsDB.getTransaction( + transactionId: '', +); +``` diff --git a/docs/examples/vectorsdb/list-documents.md b/docs/examples/vectorsdb/list-documents.md new file mode 100644 index 00000000..03b4931d --- /dev/null +++ b/docs/examples/vectorsdb/list-documents.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +DocumentList result = await vectorsDB.listDocuments( + databaseId: '', + collectionId: '', + queries: [], // optional + transactionId: '', // optional + total: false, // optional + ttl: 0, // optional +); +``` diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md new file mode 100644 index 00000000..fb7f83db --- /dev/null +++ b/docs/examples/vectorsdb/list-transactions.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +TransactionList result = await vectorsDB.listTransactions( + queries: [], // optional +); +``` diff --git a/docs/examples/vectorsdb/update-document.md b/docs/examples/vectorsdb/update-document.md new file mode 100644 index 00000000..8c2a9091 --- /dev/null +++ b/docs/examples/vectorsdb/update-document.md @@ -0,0 +1,20 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Document result = await vectorsDB.updateDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/docs/examples/vectorsdb/update-transaction.md b/docs/examples/vectorsdb/update-transaction.md new file mode 100644 index 00000000..1abd8b02 --- /dev/null +++ b/docs/examples/vectorsdb/update-transaction.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Transaction result = await vectorsDB.updateTransaction( + transactionId: '', + commit: false, // optional + rollback: false, // optional +); +``` diff --git a/docs/examples/vectorsdb/upsert-document.md b/docs/examples/vectorsdb/upsert-document.md new file mode 100644 index 00000000..1367bba4 --- /dev/null +++ b/docs/examples/vectorsdb/upsert-document.md @@ -0,0 +1,20 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/permission.dart'; +import 'package:appwrite/role.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +VectorsDB vectorsDB = VectorsDB(client); + +Document result = await vectorsDB.upsertDocument( + databaseId: '', + collectionId: '', + documentId: '', + data: {}, // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: '', // optional +); +``` diff --git a/lib/appwrite.dart b/lib/appwrite.dart index f55bd86a..e2826d9f 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,8 +1,10 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.9.x. -/// For older versions, please check -/// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). +/// This SDK targets Appwrite server version 2.0.x as shipped on Appwrite Cloud. +/// Self-hosted releases can lag behind Cloud — if you run an older self-hosted +/// build, use a matching older SDK from +/// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) +/// when APIs differ. library appwrite; import 'dart:async'; @@ -35,6 +37,7 @@ part 'operator.dart'; part 'services/account.dart'; part 'services/avatars.dart'; part 'services/databases.dart'; +part 'services/documents_db.dart'; part 'services/functions.dart'; part 'services/graphql.dart'; part 'services/locale.dart'; @@ -44,3 +47,4 @@ part 'services/presences.dart'; part 'services/storage.dart'; part 'services/tables_db.dart'; part 'services/teams.dart'; +part 'services/vectors_db.dart'; diff --git a/lib/query.dart b/lib/query.dart index 2e809e22..1ad97bdc 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,15 +159,13 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => - Query._( + static String or(List queries) => Query._( 'or', null, queries.map((query) => jsonDecode(query)).toList(), ).toString(); - static String and(List queries) => - Query._( + static String and(List queries) => Query._( 'and', null, queries.map((query) => jsonDecode(query)).toList(), @@ -177,8 +175,7 @@ class Query { /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => - Query._( + static String elemMatch(String attribute, List queries) => Query._( 'elemMatch', attribute, queries.map((query) => jsonDecode(query)).toList(), diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index ba09d21e..c57fb66e 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -241,16 +241,30 @@ class Avatars extends Service { return res.data; } - /// Returns the best available profile photo for the currently authenticated - /// user. The endpoint tries each source in priority order and returns the - /// first successful result: Gravatar, Libavatar, Appwrite Initials, built-in - /// static fallback file. + /// Returns the best available profile photo for a user. The endpoint tries + /// each source in priority order and returns the first successful result: + /// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in + /// static fallback. + /// + /// Passing `userId` — `current()` for the authenticated user — resolves + /// the photo from everything known about that user: identity photos, email, + /// and name. An explicit `emailHash` or `name` then overrides just that value, + /// and the user's remaining sources stay in the chain. Without `userId`, + /// passing `emailHash` and/or `name` resolves the avatar from those values + /// alone: the hash is looked up on Gravatar and Libravatar, the name is + /// rendered as initials, and the session user stays out of the chain so their + /// own photo never shadows the avatar being asked for. When nothing is passed, + /// the photo resolves for the currently authenticated user. Emails are only + /// ever accepted pre-hashed, so no address ends up in a URL. Future getPhoto({ int? width, int? height, int? quality, String? output, String? rating, + String? userId, + String? emailHash, + String? name, }) async { final String apiPath = '/avatars/photo'; @@ -260,6 +274,9 @@ class Avatars extends Service { if (quality != null) 'quality': quality, if (output != null) 'output': output, if (rating != null) 'rating': rating, + if (userId != null) 'userId': userId, + if (emailHash != null) 'emailHash': emailHash, + if (name != null) 'name': name, }; final Map apiHeaders = { diff --git a/lib/services/databases.dart b/lib/services/databases.dart index adbd28cc..aaa74ff5 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -164,11 +164,11 @@ class Databases extends Service { required String transactionId, List? operations, }) async { - final String apiPath = '/databases/transactions/{transactionId}/operations' - .replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = + '/databases/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/documents_db.dart b/lib/services/documents_db.dart new file mode 100644 index 00000000..0756f7d1 --- /dev/null +++ b/lib/services/documents_db.dart @@ -0,0 +1,589 @@ +part of '../appwrite.dart'; + +class DocumentsDB extends Service { + /// Initializes a [DocumentsDB] service + DocumentsDB(super.client); + + /// List transactions across all databases. + Future listTransactions({ + List? queries, + }) async { + final String apiPath = '/documentsdb/transactions'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.TransactionList.fromMap(res.data); + } + + /// Create a new transaction. + Future createTransaction({ + int? ttl, + }) async { + final String apiPath = '/documentsdb/transactions'; + + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Get a transaction by its unique ID. + Future getTransaction({ + required String transactionId, + }) async { + final String apiPath = + '/documentsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Update a transaction, to either commit or roll back its operations. + Future updateTransaction({ + required String transactionId, + bool? commit, + bool? rollback, + }) async { + final String apiPath = + '/documentsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Delete a transaction by its unique ID. + Future deleteTransaction({ + required String transactionId, + }) async { + final String apiPath = + '/documentsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Create multiple operations in a single transaction. + Future createOperations({ + required String transactionId, + List? operations, + }) async { + final String apiPath = + '/documentsdb/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = { + if (operations != null) 'operations': operations, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// 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, + String? transactionId, + bool? total, + int? ttl, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.DocumentList.fromMap(res.data); + } + + /// 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#documentsDBCreateCollection) + /// API or directly from your database console. + Future createDocument({ + required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Create new Documents. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + Future createDocuments({ + required String databaseId, + required String collectionId, + required List documents, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + 'documents': documents, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.DocumentList.fromMap(res.data); + } + + /// 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, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + Future upsertDocument({ + required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// 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, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Delete a document by its unique ID. + Future deleteDocument({ + required String databaseId, + required String collectionId, + required String documentId, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Decrement a specific column of a row by a given value. + Future decrementDocumentAttribute({ + required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? min, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ) + .replaceAll( + '{attribute}', + attribute, + ); + + final Map apiParams = { + if (value != null) 'value': value, + if (min != null) 'min': min, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Increment a specific column of a row by a given value. + Future incrementDocumentAttribute({ + required String databaseId, + required String collectionId, + required String documentId, + required String attribute, + double? value, + double? max, + String? transactionId, + }) async { + final String apiPath = + '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ) + .replaceAll( + '{attribute}', + attribute, + ); + + final Map apiParams = { + if (value != null) 'value': value, + if (max != null) 'max': max, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } +} diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 70e4576a..1dd88dac 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -69,11 +69,11 @@ class Organization extends Service { Future getInstallation({ required String installationId, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -100,11 +100,11 @@ class Organization extends Service { required String installationId, String? authorizationDetails, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -133,11 +133,11 @@ class Organization extends Service { Future deleteInstallation({ required String installationId, }) async { - final String apiPath = '/organization/installations/{installationId}' - .replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = + '/organization/installations/{installationId}'.replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 246ab939..d7f23f39 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -146,11 +146,11 @@ class TablesDB extends Service { required String transactionId, List? operations, }) async { - final String apiPath = '/tablesdb/transactions/{transactionId}/operations' - .replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = + '/tablesdb/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/vectors_db.dart b/lib/services/vectors_db.dart new file mode 100644 index 00000000..08ba3e81 --- /dev/null +++ b/lib/services/vectors_db.dart @@ -0,0 +1,488 @@ +part of '../appwrite.dart'; + +class VectorsDB extends Service { + /// Initializes a [VectorsDB] service + VectorsDB(super.client); + + /// List transactions across all databases. + Future listTransactions({ + List? queries, + }) async { + final String apiPath = '/vectorsdb/transactions'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.TransactionList.fromMap(res.data); + } + + /// Create a new transaction. + Future createTransaction({ + int? ttl, + }) async { + final String apiPath = '/vectorsdb/transactions'; + + final Map apiParams = { + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Get a transaction by its unique ID. + Future getTransaction({ + required String transactionId, + }) async { + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Update a transaction, to either commit or roll back its operations. + Future updateTransaction({ + required String transactionId, + bool? commit, + bool? rollback, + }) async { + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = { + if (commit != null) 'commit': commit, + if (rollback != null) 'rollback': rollback, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// Delete a transaction by its unique ID. + Future deleteTransaction({ + required String transactionId, + }) async { + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Create multiple operations in a single transaction. + Future createOperations({ + required String transactionId, + List? operations, + }) async { + final String apiPath = + '/vectorsdb/transactions/{transactionId}/operations'.replaceAll( + '{transactionId}', + transactionId, + ); + + final Map apiParams = { + if (operations != null) 'operations': operations, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Transaction.fromMap(res.data); + } + + /// 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, + String? transactionId, + bool? total, + int? ttl, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.DocumentList.fromMap(res.data); + } + + /// 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#documentsDBCreateCollection) + /// API or directly from your database console. + Future createDocument({ + required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions, + String? transactionId, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Get a list of all the user's documents in a given collection using a POST + /// request. This behaves identically to the list documents endpoint but + /// accepts the queries in the request body, allowing much larger `queries` + /// arrays than can fit in a URL query string. + Future createQuery({ + required String databaseId, + required String collectionId, + List? queries, + String? transactionId, + bool? total, + int? ttl, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents/query' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + if (total != null) 'total': total, + if (ttl != null) 'ttl': ttl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.DocumentList.fromMap(res.data); + } + + /// 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, + String? transactionId, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + Future upsertDocument({ + required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions, + String? transactionId, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// 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, + String? transactionId, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (data != null) 'data': data, + if (permissions != null) 'permissions': permissions, + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Document.fromMap(res.data); + } + + /// Delete a document by its unique ID. + Future deleteDocument({ + required String databaseId, + required String collectionId, + required String documentId, + String? transactionId, + }) async { + final String apiPath = + '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll( + '{databaseId}', + databaseId, + ) + .replaceAll( + '{collectionId}', + collectionId, + ) + .replaceAll( + '{documentId}', + documentId, + ); + + final Map apiParams = { + if (transactionId != null) 'transactionId': transactionId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 6fe9425c..dbfe4bdf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,7 +27,8 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => + createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 63a87c51..fdf011c8 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,8 +40,8 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '26.0.0', - 'X-Appwrite-Response-Format': '1.9.6', + 'x-sdk-version': '26.2.0', + 'X-Appwrite-Response-Format': '2.0.0', }; config = {}; diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index ee52e2ea..3ccefd87 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,10 +47,9 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = - HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -60,8 +59,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '26.0.0', - 'X-Appwrite-Response-Format': '1.9.6', + 'x-sdk-version': '26.2.0', + 'X-Appwrite-Response-Format': '2.0.0', }; config = {}; @@ -358,13 +357,8 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk( - int index, - int start, - int end, - String? id, [ - RandomAccessFile? raf, - ]) async { + Future uploadChunk(int index, int start, int end, String? id, + [RandomAccessFile? raf]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -488,10 +482,9 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: - callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -506,10 +499,9 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = - codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 3ca20708..952d7114 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -92,9 +92,8 @@ mixin ClientMixin { } if (res.statusCode >= 400) { - final isJson = (res.headers['content-type'] ?? '').contains( - 'application/json', - ); + final isJson = + (res.headers['content-type'] ?? '').contains('application/json'); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -142,12 +141,10 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map( - (k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v), - ), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 05253273..6b1e67cd 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,15 +17,14 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }) - .catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }).catchError((e, stackTrace) { + return request; + }); return request; } @@ -44,9 +43,8 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host, - ), + scheme: response.request!.url.scheme, + host: response.request!.url.host), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 0f250ea3..595afdc2 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes, + bytes } diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 1bd23697..6626f3a0 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -10,6 +10,7 @@ enum OAuthProvider { bitbucket(value: "bitbucket"), bitly(value: "bitly"), box(value: "box"), + cloudflare(value: "cloudflare"), dailymotion(value: "dailymotion"), discord(value: "discord"), disqus(value: "disqus"), @@ -32,6 +33,7 @@ enum OAuthProvider { paypal(value: "paypal"), paypalSandbox(value: "paypalSandbox"), podio(value: "podio"), + resend(value: "resend"), salesforce(value: "salesforce"), slack(value: "slack"), spotify(value: "spotify"), diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index e56b7ddd..a0f4193a 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,12 +25,10 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace( - queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }, - ); + uri = uri.replace(queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index ab1c3b42..0ed367a6 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,11 +37,9 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel( - (client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers), - ); + final websok = IOWebSocketChannel((client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers)); return websok; } @@ -75,18 +73,13 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, - Map headers, - ) async { + Uri uri, Map headers) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = ( - X509Certificate cert, - String host, - int port, - ) { + client.badCertificateCallback = + (X509Certificate cert, String host, int port) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 639f2795..ee4c4c30 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,80 +100,74 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen( - (response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add( - jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - }), - ); - } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; + _websocketSubscription = _websok?.stream.listen((response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add(jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + })); } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; + } + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': + break; + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { - break; - } + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); - } + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); } - break; - } - }, - onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, - onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }, - ); + } + break; + } + }, onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }); } catch (e) { if (e is AppwriteException) { rethrow; @@ -203,30 +197,27 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server", - ); + "Please set endPointRealtime to connect to realtime server"); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = - (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", - ); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -236,12 +227,10 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add( - jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - }), - ); + _websok!.sink.add(jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + })); } String _generateUniqueSubscriptionId() { @@ -303,12 +292,10 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add( - jsonEncode({ - 'type': 'subscribe', - 'data': rows, - }), - ); + _websok!.sink.add(jsonEncode({ + 'type': 'subscribe', + 'data': rows, + })); } void _flushPendingPresence() { @@ -325,10 +312,8 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo( - List channels, [ - List queries = const [], - ]) { + RealtimeSubscription subscribeTo(List channels, + [List queries = const []]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); @@ -397,7 +382,11 @@ mixin RealtimeMixin { void handleError(RealtimeResponse response) { if (response.data['code'] == status.policyViolation) { - throw AppwriteException(response.data["message"], response.data["code"]); + final error = AppwriteException( + response.data["message"], response.data["code"]); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(error); + } } else { _retry(); } diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 631afe31..3aab4e03 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,7 +2,6 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => - throw UnsupportedError( +RealtimeBase createRealtime(Client client) => throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index 6461e344..e572b519 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/pubspec.yaml b/pubspec.yaml index ee9ee40c..a08b4cdb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 26.0.0 +version: 26.2.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies 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/channel_test.dart b/test/channel_test.dart index 5ed52b81..9e0e11d3 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect( - Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents', - ); + expect(Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents'); }); test('returns database channel with action', () { expect( - Channel.database( - 'db1', - ).collection('col1').document('doc1').create().toString(), - 'databases.db1.collections.col1.documents.doc1.create', - ); + Channel.database('db1') + .collection('col1') + .document('doc1') + .create() + .toString(), + 'databases.db1.collections.col1.documents.doc1.create'); }); test('returns database channel with upsert action', () { expect( - Channel.database( - 'db1', - ).collection('col1').document('doc1').upsert().toString(), - 'databases.db1.collections.col1.documents.doc1.upsert', - ); + Channel.database('db1') + .collection('col1') + .document('doc1') + .upsert() + .toString(), + 'databases.db1.collections.col1.documents.doc1.upsert'); }); }); @@ -39,17 +39,18 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect( - Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows', - ); + expect(Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows'); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1').table('table1').row('row1').update().toString(), - 'tablesdb.db1.tables.table1.rows.row1.update', - ); + Channel.tablesdb('db1') + .table('table1') + .row('row1') + .update() + .toString(), + 'tablesdb.db1.tables.table1.rows.row1.update'); }); }); @@ -66,16 +67,12 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), - 'buckets.bucket1.files', - ); + Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); }); test('returns buckets channel with action', () { - expect( - Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete', - ); + expect(Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete'); }); }); @@ -119,17 +116,13 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect( - Channel.membership('membership1').toString(), - 'memberships.membership1', - ); + expect(Channel.membership('membership1').toString(), + 'memberships.membership1'); }); test('returns memberships channel with action', () { - expect( - Channel.membership('membership1').update().toString(), - 'memberships.membership1.update', - ); + expect(Channel.membership('membership1').update().toString(), + 'memberships.membership1.update'); }); }); @@ -147,31 +140,23 @@ void main() { }); test('returns presence channel with create action', () { - expect( - Channel.presence('presence1').create().toString(), - 'presences.presence1.create', - ); + expect(Channel.presence('presence1').create().toString(), + 'presences.presence1.create'); }); test('returns presence channel with upsert action', () { - expect( - Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert', - ); + expect(Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert'); }); test('returns presence channel with update action', () { - expect( - Channel.presence('presence1').update().toString(), - 'presences.presence1.update', - ); + expect(Channel.presence('presence1').update().toString(), + 'presences.presence1.update'); }); test('returns presence channel with delete action', () { - expect( - Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete', - ); + expect(Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete'); }); }); } diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index d55be0c4..d92a7381 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -312,7 +312,7 @@ void main() { databaseId: "", collectionId: "", documentId: "", - attribute: '', + attribute: "", ); expect(response, isA()); }); @@ -336,7 +336,7 @@ void main() { databaseId: "", collectionId: "", documentId: "", - attribute: '', + attribute: "", ); expect(response, isA()); }); diff --git a/test/services/documents_db_test.dart b/test/services/documents_db_test.dart new file mode 100644 index 00000000..6e7d3a62 --- /dev/null +++ b/test/services/documents_db_test.dart @@ -0,0 +1,362 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('DocumentsDB test', () { + late MockClient client; + late DocumentsDB documentsDB; + + setUp(() { + client = MockClient(); + documentsDB = DocumentsDB(client); + }); + + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.listTransactions(); + expect(response, isA()); + }); + + test('test method createTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.createTransaction(); + expect(response, isA()); + }); + + test('test method getTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.getTransaction( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method updateTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.updateTransaction( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method deleteTransaction()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.deleteTransaction( + transactionId: "", + ); + }); + + test('test method createOperations()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.createOperations( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method listDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.listDocuments( + databaseId: "", + collectionId: "", + ); + expect(response, isA()); + }); + + test('test method createDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.createDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: {}, + ); + expect(response, isA()); + }); + + test('test method createDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.createDocuments( + databaseId: "", + collectionId: "", + documents: [], + ); + expect(response, isA()); + }); + + test('test method getDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.getDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method upsertDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.upsertDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method updateDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.updateDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method deleteDocument()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.deleteDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + }); + + test('test method decrementDocumentAttribute()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.decrementDocumentAttribute( + databaseId: "", + collectionId: "", + documentId: "", + attribute: "", + ); + expect(response, isA()); + }); + + test('test method incrementDocumentAttribute()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await documentsDB.incrementDocumentAttribute( + databaseId: "", + collectionId: "", + documentId: "", + attribute: "", + ); + expect(response, isA()); + }); + }); +} diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 9cf7d024..47f0eee8 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -312,7 +312,7 @@ void main() { databaseId: "", tableId: "", rowId: "", - column: '', + column: "", ); expect(response, isA()); }); @@ -336,7 +336,7 @@ void main() { databaseId: "", tableId: "", rowId: "", - column: '', + column: "", ); expect(response, isA()); }); diff --git a/test/services/vectors_db_test.dart b/test/services/vectors_db_test.dart new file mode 100644 index 00000000..14660ed0 --- /dev/null +++ b/test/services/vectors_db_test.dart @@ -0,0 +1,313 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('VectorsDB test', () { + late MockClient client; + late VectorsDB vectorsDB; + + setUp(() { + client = MockClient(); + vectorsDB = VectorsDB(client); + }); + + test('test method listTransactions()', () async { + final Map data = { + 'total': 5, + 'transactions': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.listTransactions(); + expect(response, isA()); + }); + + test('test method createTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.createTransaction(); + expect(response, isA()); + }); + + test('test method getTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.getTransaction( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method updateTransaction()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.updateTransaction( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method deleteTransaction()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.deleteTransaction( + transactionId: "", + ); + }); + + test('test method createOperations()', () async { + final Map data = { + '\$id': "259125845563242502", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'status': "pending", + 'operations': 5, + 'expiresAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.createOperations( + transactionId: "", + ); + expect(response, isA()); + }); + + test('test method listDocuments()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.listDocuments( + databaseId: "", + collectionId: "", + ); + expect(response, isA()); + }); + + test('test method createDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.createDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: {}, + ); + expect(response, isA()); + }); + + test('test method createQuery()', () async { + final Map data = { + 'total': 5, + 'documents': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.createQuery( + databaseId: "", + collectionId: "", + ); + expect(response, isA()); + }); + + test('test method getDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.getDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method upsertDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.upsertDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method updateDocument()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$sequence': "1", + '\$collectionId': "5e5ea5c15117e", + '\$databaseId': "5e5ea5c15117e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + '\$permissions': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.updateDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + expect(response, isA()); + }); + + test('test method deleteDocument()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await vectorsDB.deleteDocument( + databaseId: "", + collectionId: "", + documentId: "", + ); + }); + }); +} diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 046fa07b..3d301a85 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,26 +7,22 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - ), - ), + throwsA(isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + )), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - ), - ), + throwsA(isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + )), ); }); diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 029c35bf..4435280a 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,9 +48,7 @@ void main() { final responseString = response1.toString(); expect( - responseString, - equals('RealtimeResponse(type: $type, data: $data)'), - ); + responseString, equals('RealtimeResponse(type: $type, data: $data)')); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index d19e6eac..1515f1a3 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,18 +8,15 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction({ - List? channels, - List? queries, - }) async {} + Future mockUpdateFunction( + {List? channels, List? queries}) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const [], - ); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const []); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index 3dce66c9..d21607ec 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, + "chunksUploaded": chunksUploaded }; final uploadProgress = UploadProgress( $id: id, From 26583918a019c133a578666f19e6774aaf654b4b Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 7 Sep 2026 17:15:17 +0100 Subject: [PATCH 13/17] docs: state the SDK targets Appwrite server version 2.0.x --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9220945b..584d890c 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 targets Appwrite server version 1.9.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) when APIs differ. +**This SDK targets Appwrite server version 2.0.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) when APIs differ. Appwrite is an open-source backend as a service server that abstracts and simplifies 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) From dc3489f0a5855ebf704343a90dfedcf1ab6476ed Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 7 Sep 2026 18:21:12 +0100 Subject: [PATCH 14/17] fix: regenerate with the latest sdk-generator and add auto image gravity --- CHANGELOG.md | 1 + docs/examples/storage/get-file-preview.md | 4 ++-- lib/src/enums/image_gravity.dart | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1ecf988..cdb46c5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * Added: `DocumentsDB` and `VectorsDB` services for document and vector database access * Added: `userId`, `emailHash` and `name` parameters to `Avatars.getPhoto()` * Added: `cloudflare` and `resend` values to `OAuthProvider` enum +* Added: `auto` value to `ImageGravity` enum * Updated: `X-Appwrite-Response-Format` header to `2.0.0` ## 26.1.0 diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 274b4224..bc811343 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -17,7 +17,7 @@ Uint8List bytes = await storage.getFilePreview( fileId: '', width: 0, // optional height: 0, // optional - gravity: enums.ImageGravity.center, // optional + gravity: enums.ImageGravity.auto, // optional quality: -1, // optional borderWidth: 0, // optional borderColor: 'FFFFFF', // optional @@ -39,7 +39,7 @@ FutureBuilder( fileId: '', width: 0, // optional height: 0, // optional - gravity: enums.ImageGravity.center, // optional + gravity: enums.ImageGravity.auto, // optional quality: -1, // optional borderWidth: 0, // optional borderColor: 'FFFFFF', // optional diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index dbcef202..1a0de57b 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,6 +1,7 @@ part of '../../enums.dart'; enum ImageGravity { + auto(value: "auto"), center(value: "center"), topLeft(value: "top-left"), top(value: "top"), From 0b5d55862133231d535cdebe005e649b8d5d746a Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Thu, 24 Sep 2026 15:39:06 +0100 Subject: [PATCH 15/17] chore: update Flutter SDK to 27.0.0 --- CHANGELOG.md | 12 + README.md | 6 +- ...gs.md => create-email-verification-otp.md} | 5 +- .../account/create-id-token-session.md | 19 + docs/examples/account/create-recovery-otp.md | 14 + .../account/update-email-verification-otp.md | 14 + docs/examples/account/update-recovery-otp.md | 15 + lib/appwrite.dart | 3 +- lib/enums.dart | 1 + lib/models.dart | 2 - lib/services/account.dart | 343 ++++++++++++++++-- lib/services/databases.dart | 170 +++++++++ lib/services/documents_db.dart | 182 ++++++++++ lib/services/functions.dart | 24 ++ lib/services/messaging.dart | 19 + lib/services/organization.dart | 18 + lib/services/presences.dart | 25 ++ lib/services/storage.dart | 85 +++++ lib/services/tables_db.dart | 170 +++++++++ lib/services/teams.dart | 140 +++++++ lib/services/vectors_db.dart | 134 +++++++ lib/src/client.dart | 5 - lib/src/client_base.dart | 4 - lib/src/client_browser.dart | 24 +- lib/src/client_io.dart | 12 +- lib/src/enums/id_token_provider.dart | 12 + lib/src/enums/o_auth_provider.dart | 2 + lib/src/models/execution.dart | 2 +- lib/src/models/identity.dart | 6 + lib/src/models/log.dart | 151 -------- lib/src/models/log_list.dart | 33 -- lib/src/models/user.dart | 6 + pubspec.yaml | 2 +- test/services/account_test.dart | 139 ++++++- test/services/functions_test.dart | 4 +- test/src/models/execution_test.dart | 4 +- test/src/models/identity_test.dart | 6 + test/src/models/log_list_test.dart | 19 - test/src/models/log_test.dart | 59 --- 39 files changed, 1532 insertions(+), 359 deletions(-) rename docs/examples/account/{list-logs.md => create-email-verification-otp.md} (71%) create mode 100644 docs/examples/account/create-id-token-session.md create mode 100644 docs/examples/account/create-recovery-otp.md create mode 100644 docs/examples/account/update-email-verification-otp.md create mode 100644 docs/examples/account/update-recovery-otp.md create mode 100644 lib/src/enums/id_token_provider.dart delete mode 100644 lib/src/models/log.dart delete mode 100644 lib/src/models/log_list.dart delete mode 100644 test/src/models/log_list_test.dart delete mode 100644 test/src/models/log_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index cdb46c5a..1344896b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Change Log +## 27.0.0 + +* Breaking: removed `Account.listLogs` and the `Log`, `LogList` models +* Breaking: removed `Client.setDevKey` +* Breaking: SDK now targets Appwrite 2.3 (`X-Appwrite-Response-Format: 2.3.0`) +* Added: `Account.createIdTokenSession` for native Apple and Google sign-in with `IdTokenProvider` enum +* Added: `Account.createRecoveryOTP` and `Account.updateRecoveryOTP` for code-based password recovery +* Added: `Account.createEmailVerificationOTP` and `Account.updateEmailVerificationOTP` +* Added: `kakao` and `tiktok` values to `OAuthProvider` +* Added: `passwordPwned` field on `User` and `providerIdToken` field on `Identity` +* Fixed: empty-string required path parameters are rejected instead of sent to the API + ## 26.2.0 * Added: `DocumentsDB` and `VectorsDB` services for document and vector database access diff --git a/README.md b/README.md index 584d890c..bbc066a7 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ [![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-2.0.x-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-2.3.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) -**This SDK targets Appwrite server version 2.0.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) when APIs differ. +**This SDK targets Appwrite server version 2.3.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) when APIs differ. Appwrite is an open-source backend as a service server that abstracts and simplifies 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) @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^26.2.0 + appwrite: ^27.0.0 ``` You can install packages from the command line: diff --git a/docs/examples/account/list-logs.md b/docs/examples/account/create-email-verification-otp.md similarity index 71% rename from docs/examples/account/list-logs.md rename to docs/examples/account/create-email-verification-otp.md index 924470de..941db965 100644 --- a/docs/examples/account/list-logs.md +++ b/docs/examples/account/create-email-verification-otp.md @@ -7,8 +7,7 @@ Client client = Client() Account account = Account(client); -LogList result = await account.listLogs( - queries: [], // optional - total: false, // optional +Token result = await account.createEmailVerificationOTP( + phrase: false, // optional ); ``` diff --git a/docs/examples/account/create-id-token-session.md b/docs/examples/account/create-id-token-session.md new file mode 100644 index 00000000..61f84065 --- /dev/null +++ b/docs/examples/account/create-id-token-session.md @@ -0,0 +1,19 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/enums.dart' as enums; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Session result = await account.createIdTokenSession( + provider: enums.IdTokenProvider.apple, + idToken: '', + nonce: '', // optional + accessToken: '', // optional + accessTokenExpiry: 0, // optional + name: '', // optional +); +``` diff --git a/docs/examples/account/create-recovery-otp.md b/docs/examples/account/create-recovery-otp.md new file mode 100644 index 00000000..366469f3 --- /dev/null +++ b/docs/examples/account/create-recovery-otp.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Token result = await account.createRecoveryOTP( + email: 'email@example.com', + phrase: false, // optional +); +``` diff --git a/docs/examples/account/update-email-verification-otp.md b/docs/examples/account/update-email-verification-otp.md new file mode 100644 index 00000000..52ff4c11 --- /dev/null +++ b/docs/examples/account/update-email-verification-otp.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Token result = await account.updateEmailVerificationOTP( + userId: '', + secret: '', +); +``` diff --git a/docs/examples/account/update-recovery-otp.md b/docs/examples/account/update-recovery-otp.md new file mode 100644 index 00000000..f7b4a2ef --- /dev/null +++ b/docs/examples/account/update-recovery-otp.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Account account = Account(client); + +Token result = await account.updateRecoveryOTP( + userId: '', + secret: '', + password: 'password', +); +``` diff --git a/lib/appwrite.dart b/lib/appwrite.dart index e2826d9f..c80609e3 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK targets Appwrite server version 2.0.x as shipped on Appwrite Cloud. +/// This SDK targets Appwrite server version 2.3.x as shipped on Appwrite Cloud. /// Self-hosted releases can lag behind Cloud — if you run an older self-hosted /// build, use a matching older SDK from /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases) @@ -13,6 +13,7 @@ import 'dart:typed_data'; import 'dart:convert'; import 'src/enums.dart'; +import 'src/exception.dart'; import 'src/service.dart'; import 'src/input_file.dart'; import 'models.dart' as models; diff --git a/lib/enums.dart b/lib/enums.dart index a9677f03..c73a7c43 100644 --- a/lib/enums.dart +++ b/lib/enums.dart @@ -3,6 +3,7 @@ library appwrite.enums; part 'src/enums/authenticator_type.dart'; part 'src/enums/authentication_factor.dart'; +part 'src/enums/id_token_provider.dart'; part 'src/enums/o_auth_provider.dart'; part 'src/enums/browser.dart'; part 'src/enums/credit_card.dart'; diff --git a/lib/models.dart b/lib/models.dart index d6ee0466..f1fca69d 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -9,7 +9,6 @@ part 'src/models/document_list.dart'; part 'src/models/presence_list.dart'; part 'src/models/session_list.dart'; part 'src/models/identity_list.dart'; -part 'src/models/log_list.dart'; part 'src/models/file_list.dart'; part 'src/models/team_list.dart'; part 'src/models/membership_list.dart'; @@ -24,7 +23,6 @@ part 'src/models/transaction_list.dart'; part 'src/models/row.dart'; part 'src/models/document.dart'; part 'src/models/presence.dart'; -part 'src/models/log.dart'; part 'src/models/user.dart'; part 'src/models/algo_md5.dart'; part 'src/models/algo_sha.dart'; diff --git a/lib/services/account.dart b/lib/services/account.dart index 41a32f4a..48492bdb 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -97,6 +97,12 @@ class Account extends Service { Future getConsent({ required String consentId, }) async { + if (consentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "consentId"', + ); + } + final String apiPath = '/account/consents/{consentId}'.replaceAll( '{consentId}', consentId, @@ -125,6 +131,12 @@ class Account extends Service { Future deleteConsent({ required String consentId, }) async { + if (consentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "consentId"', + ); + } + final String apiPath = '/account/consents/{consentId}'.replaceAll( '{consentId}', consentId, @@ -156,6 +168,12 @@ class Account extends Service { List? queries, bool? total, }) async { + if (consentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "consentId"', + ); + } + final String apiPath = '/account/consents/{consentId}/tokens'.replaceAll( '{consentId}', consentId, @@ -187,6 +205,18 @@ class Account extends Service { required String consentId, required String tokenId, }) async { + if (consentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "consentId"', + ); + } + + if (tokenId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tokenId"', + ); + } + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' .replaceAll( '{consentId}', @@ -221,6 +251,18 @@ class Account extends Service { required String consentId, required String tokenId, }) async { + if (consentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "consentId"', + ); + } + + if (tokenId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tokenId"', + ); + } + final String apiPath = '/account/consents/{consentId}/tokens/{tokenId}' .replaceAll( '{consentId}', @@ -314,6 +356,12 @@ class Account extends Service { Future deleteIdentity({ required String identityId, }) async { + if (identityId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "identityId"', + ); + } + final String apiPath = '/account/identities/{identityId}'.replaceAll( '{identityId}', identityId, @@ -324,6 +372,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -366,34 +415,6 @@ class Account extends Service { return models.Jwt.fromMap(res.data); } - /// 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, - bool? total, - }) async { - final String apiPath = '/account/logs'; - - final Map apiParams = { - if (queries != null) 'queries': queries, - if (total != null) 'total': total, - }; - - final Map apiHeaders = { - 'X-Appwrite-Project': client.config['project'] ?? '', - 'accept': 'application/json', - }; - - final res = await client.call( - HttpMethod.get, - path: apiPath, - params: apiParams, - headers: apiHeaders, - ); - - return models.LogList.fromMap(res.data); - } - /// Enable or disable MFA on an account. Future updateMFA({ required bool mfa, @@ -567,6 +588,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -593,6 +615,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -1146,6 +1169,81 @@ class Account extends Service { return models.Token.fromMap(res.data); } + /// Use this endpoint to send a 6-digit password recovery code to the user's + /// email address. Unlike + /// [createRecovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery), + /// this method requires no redirect URL, which makes it suitable for mobile + /// and desktop apps that cannot host a recovery page. Learn more about how to + /// [complete the recovery + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateRecoveryOTP). + /// The code sent to the user's email address is valid for 15 minutes. + /// + /// Enable the **phrase** parameter to include a randomly generated security + /// phrase in both the email and the response. Showing that phrase in your app + /// lets the user confirm the email genuinely came from your request, which + /// helps protect against phishing. + Future createRecoveryOTP({ + required String email, + bool? phrase, + }) async { + final String apiPath = '/account/recovery/otp'; + + final Map apiParams = { + 'email': email, + if (phrase != null) 'phrase': phrase, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Token.fromMap(res.data); + } + + /// Use this endpoint to complete the user password recovery process using the + /// 6-digit code that was emailed by + /// [createRecoveryOTP](https://appwrite.io/docs/references/cloud/client-web/account#createRecoveryOTP). + /// Pass the **userId** of the user along with the **secret** code from the + /// email and the new **password** to set. If confirmed, this route will return + /// a 200 status code, the code is consumed and the user's password is updated. + Future updateRecoveryOTP({ + required String userId, + required String secret, + required String password, + }) async { + final String apiPath = '/account/recovery/otp'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Token.fromMap(res.data); + } + /// Get the list of active sessions across different devices for the currently /// logged in user. Future listSessions() async { @@ -1178,6 +1276,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -1251,6 +1350,82 @@ class Account extends Service { return models.Session.fromMap(res.data); } + /// Allow the user to login to their account using an OpenID Connect ID token + /// obtained natively from the OAuth2 provider, for example via Google + /// Credential Manager on Android or Sign in with Apple on iOS. No browser or + /// redirect is involved: the ID token is verified against the provider's + /// published signing keys and a session is created in a single request. + /// + /// Native sign-in is switched on per provider with its nativeEnabled setting. + /// It is independent of the browser-based flow's enabled setting, which has no + /// effect on this endpoint. The token's audience must match the provider's + /// configured client ID or one of its native client IDs; tokens issued for any + /// other client ID are rejected. For Sign in with Apple, register your app's + /// bundle ID as a native client ID. For Google, the web client ID used by + /// Credential Manager is usually the configured client ID; add your Android + /// and iOS client IDs as native client IDs if your app requests tokens for + /// them. + /// + /// Pass the raw nonce used when requesting the ID token so it can be validated + /// against the token's nonce claim. When signing in with Apple, the nonce is + /// required: hash it with SHA-256 before passing it to the Apple SDK, and send + /// the raw value here - Apple tokens requested without a nonce are rejected. + /// For Google the nonce is optional: it is validated whenever the token + /// carries one, and ignored when the provider issued the token without one. + /// Apple only returns the user's name on the first authorization, and never + /// inside the ID token - capture it on the client and pass it via the name + /// parameter. + /// + /// 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 verified + /// email received from the provider and attach the new session to the existing + /// user. If no matching user is found - the server will create a new user. + /// + /// This flow does not return provider refresh tokens. You may pass an access + /// token the provider handed your client, along with its lifetime, to store it + /// on the session - but Appwrite cannot renew it once it expires. If your app + /// needs long-lived access to provider APIs, use the browser-based OAuth2 flow + /// instead. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createIdTokenSession({ + required enums.IdTokenProvider provider, + required String idToken, + String? nonce, + String? accessToken, + int? accessTokenExpiry, + String? name, + }) async { + final String apiPath = '/account/sessions/id-token'; + + final Map apiParams = { + 'provider': provider.value, + 'idToken': idToken, + if (nonce != null) 'nonce': nonce, + if (accessToken != null) 'accessToken': accessToken, + if (accessTokenExpiry != null) 'accessTokenExpiry': accessTokenExpiry, + if (name != null) 'name': name, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Session.fromMap(res.data); + } + /// 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. @@ -1411,6 +1586,12 @@ class Account extends Service { Future getSession({ required String sessionId, }) async { + if (sessionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "sessionId"', + ); + } + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( '{sessionId}', sessionId, @@ -1439,6 +1620,12 @@ class Account extends Service { Future updateSession({ required String sessionId, }) async { + if (sessionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "sessionId"', + ); + } + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( '{sessionId}', sessionId, @@ -1470,6 +1657,12 @@ class Account extends Service { Future deleteSession({ required String sessionId, }) async { + if (sessionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "sessionId"', + ); + } + final String apiPath = '/account/sessions/{sessionId}'.replaceAll( '{sessionId}', sessionId, @@ -1480,6 +1673,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -1520,7 +1714,10 @@ class Account extends Service { /// target ID (custom or generated using ID.unique()), a device identifier /// (usually a device token), and optionally specify which provider should send /// notifications to this target. The target is automatically linked to the - /// current session and includes device information like brand and model. + /// current session and includes device information like brand and model. A + /// session holds one push target per provider, so if one already exists this + /// endpoint updates and returns that target instead of creating a second one, + /// and a device that rotates its token is never notified twice. Future createPushTarget({ required String targetId, required String identifier, @@ -1559,6 +1756,12 @@ class Account extends Service { required String targetId, required String identifier, }) async { + if (targetId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "targetId"', + ); + } + final String apiPath = '/account/targets/{targetId}/push'.replaceAll( '{targetId}', targetId, @@ -1590,6 +1793,12 @@ class Account extends Service { Future deletePushTarget({ required String targetId, }) async { + if (targetId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "targetId"', + ); + } + final String apiPath = '/account/targets/{targetId}/push'.replaceAll( '{targetId}', targetId, @@ -1600,6 +1809,7 @@ class Account extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -1709,6 +1919,10 @@ class Account extends Service { /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) /// endpoint. /// + /// If there is already an active session, the OAuth2 identity is attached to + /// the logged-in account and that session stays active until the token is + /// exchanged for a new one. + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). @@ -1939,6 +2153,77 @@ class Account extends Service { return models.Token.fromMap(res.data); } + /// Use this endpoint to send a 6-digit verification code to the currently + /// logged in user's email address. Unlike + /// [createEmailVerification](https://appwrite.io/docs/references/cloud/client-web/account#createEmailVerification), + /// this method requires no redirect URL, which makes it suitable for mobile + /// and desktop apps that cannot host a verification page. Learn more about how + /// to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateEmailVerificationOTP). + /// The code sent to the user's email address is valid for 15 minutes. + /// + /// Enable the **phrase** parameter to include a randomly generated security + /// phrase in both the email and the response. Showing that phrase in your app + /// lets the user confirm the email genuinely came from your request, which + /// helps protect against phishing. + Future createEmailVerificationOTP({ + bool? phrase, + }) async { + final String apiPath = '/account/verifications/email/otp'; + + final Map apiParams = { + if (phrase != null) 'phrase': phrase, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Token.fromMap(res.data); + } + + /// Use this endpoint to complete the user email verification process using the + /// 6-digit code that was emailed by + /// [createEmailVerificationOTP](https://appwrite.io/docs/references/cloud/client-web/account#createEmailVerificationOTP). + /// Pass the **userId** of the user being verified along with the **secret** + /// code from the email. If confirmed, this route will return a 200 status code + /// and the code is consumed. + Future updateEmailVerificationOTP({ + required String userId, + required String secret, + }) async { + final String apiPath = '/account/verifications/email/otp'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Token.fromMap(res.data); + } + /// 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 diff --git a/lib/services/databases.dart b/lib/services/databases.dart index aaa74ff5..f1bb2510 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -70,6 +70,12 @@ class Databases extends Service { Future getTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -101,6 +107,12 @@ class Databases extends Service { bool? commit, bool? rollback, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -134,6 +146,12 @@ class Databases extends Service { Future deleteTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/databases/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -144,6 +162,7 @@ class Databases extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -164,6 +183,12 @@ class Databases extends Service { required String transactionId, List? operations, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/databases/transactions/{transactionId}/operations'.replaceAll( '{transactionId}', @@ -203,6 +228,18 @@ class Databases extends Service { bool? total, int? ttl, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -251,6 +288,18 @@ class Databases extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -297,6 +346,24 @@ class Databases extends Service { List? queries, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -347,6 +414,24 @@ class Databases extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -397,6 +482,24 @@ class Databases extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -444,6 +547,24 @@ class Databases extends Service { required String documentId, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -466,6 +587,7 @@ class Databases extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -491,6 +613,30 @@ class Databases extends Service { double? min, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + + if (attribute.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "attribute"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' .replaceAll( @@ -545,6 +691,30 @@ class Databases extends Service { double? max, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + + if (attribute.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "attribute"', + ); + } + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' .replaceAll( diff --git a/lib/services/documents_db.dart b/lib/services/documents_db.dart index 0756f7d1..3ca77cdb 100644 --- a/lib/services/documents_db.dart +++ b/lib/services/documents_db.dart @@ -59,6 +59,12 @@ class DocumentsDB extends Service { Future getTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/documentsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', @@ -88,6 +94,12 @@ class DocumentsDB extends Service { bool? commit, bool? rollback, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/documentsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', @@ -119,6 +131,12 @@ class DocumentsDB extends Service { Future deleteTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/documentsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', @@ -130,6 +148,7 @@ class DocumentsDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -147,6 +166,12 @@ class DocumentsDB extends Service { required String transactionId, List? operations, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/documentsdb/transactions/{transactionId}/operations'.replaceAll( '{transactionId}', @@ -183,6 +208,18 @@ class DocumentsDB extends Service { bool? total, int? ttl, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -228,6 +265,18 @@ class DocumentsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -272,6 +321,18 @@ class DocumentsDB extends Service { required List documents, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -313,6 +374,24 @@ class DocumentsDB extends Service { List? queries, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -360,6 +439,24 @@ class DocumentsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -407,6 +504,24 @@ class DocumentsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -451,6 +566,24 @@ class DocumentsDB extends Service { required String documentId, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -473,6 +606,7 @@ class DocumentsDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -495,6 +629,30 @@ class DocumentsDB extends Service { double? min, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + + if (attribute.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "attribute"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement' .replaceAll( @@ -546,6 +704,30 @@ class DocumentsDB extends Service { double? max, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + + if (attribute.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "attribute"', + ); + } + final String apiPath = '/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment' .replaceAll( diff --git a/lib/services/functions.dart b/lib/services/functions.dart index fc5f460e..9d40b1d0 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -13,6 +13,12 @@ class Functions extends Service { List? queries, bool? total, }) async { + if (functionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "functionId"', + ); + } + final String apiPath = '/functions/{functionId}/executions'.replaceAll( '{functionId}', functionId, @@ -51,6 +57,12 @@ class Functions extends Service { Map? headers, String? scheduledAt, }) async { + if (functionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "functionId"', + ); + } + final String apiPath = '/functions/{functionId}/executions'.replaceAll( '{functionId}', functionId, @@ -86,6 +98,18 @@ class Functions extends Service { required String functionId, required String executionId, }) async { + if (functionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "functionId"', + ); + } + + if (executionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "executionId"', + ); + } + final String apiPath = '/functions/{functionId}/executions/{executionId}' .replaceAll( '{functionId}', diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index d213b55f..4afbb010 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -12,6 +12,12 @@ class Messaging extends Service { required String subscriberId, required String targetId, }) async { + if (topicId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "topicId"', + ); + } + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll( '{topicId}', topicId, @@ -43,6 +49,18 @@ class Messaging extends Service { required String topicId, required String subscriberId, }) async { + if (topicId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "topicId"', + ); + } + + if (subscriberId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "subscriberId"', + ); + } + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}' .replaceAll( @@ -59,6 +77,7 @@ class Messaging extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( diff --git a/lib/services/organization.dart b/lib/services/organization.dart index 1dd88dac..bbda874a 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -69,6 +69,12 @@ class Organization extends Service { Future getInstallation({ required String installationId, }) async { + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/organization/installations/{installationId}'.replaceAll( '{installationId}', @@ -100,6 +106,12 @@ class Organization extends Service { required String installationId, String? authorizationDetails, }) async { + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/organization/installations/{installationId}'.replaceAll( '{installationId}', @@ -133,6 +145,12 @@ class Organization extends Service { Future deleteInstallation({ required String installationId, }) async { + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/organization/installations/{installationId}'.replaceAll( '{installationId}', diff --git a/lib/services/presences.dart b/lib/services/presences.dart index f40c07e3..7ce2e633 100644 --- a/lib/services/presences.dart +++ b/lib/services/presences.dart @@ -40,6 +40,12 @@ class Presences extends Service { Future get({ required String presenceId, }) async { + if (presenceId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "presenceId"', + ); + } + final String apiPath = '/presences/{presenceId}'.replaceAll( '{presenceId}', presenceId, @@ -70,6 +76,12 @@ class Presences extends Service { String? expiresAt, Map? metadata, }) async { + if (presenceId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "presenceId"', + ); + } + final String apiPath = '/presences/{presenceId}'.replaceAll( '{presenceId}', presenceId, @@ -108,6 +120,12 @@ class Presences extends Service { List? permissions, bool? purge, }) async { + if (presenceId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "presenceId"', + ); + } + final String apiPath = '/presences/{presenceId}'.replaceAll( '{presenceId}', presenceId, @@ -141,6 +159,12 @@ class Presences extends Service { Future delete({ required String presenceId, }) async { + if (presenceId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "presenceId"', + ); + } + final String apiPath = '/presences/{presenceId}'.replaceAll( '{presenceId}', presenceId, @@ -151,6 +175,7 @@ class Presences extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( diff --git a/lib/services/storage.dart b/lib/services/storage.dart index 77f156dd..52a129a8 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -13,6 +13,12 @@ class Storage extends Service { String? search, bool? total, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll( '{bucketId}', bucketId, @@ -64,6 +70,12 @@ class Storage extends Service { String? folder, Function(UploadProgress)? onProgress, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll( '{bucketId}', bucketId, @@ -103,6 +115,18 @@ class Storage extends Service { required String bucketId, required String fileId, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' .replaceAll( '{bucketId}', @@ -138,6 +162,18 @@ class Storage extends Service { String? name, List? permissions, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' .replaceAll( '{bucketId}', @@ -175,6 +211,18 @@ class Storage extends Service { required String bucketId, required String fileId, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' .replaceAll( '{bucketId}', @@ -190,6 +238,7 @@ class Storage extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -210,6 +259,18 @@ class Storage extends Service { required String fileId, String? token, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' .replaceAll( '{bucketId}', @@ -260,6 +321,18 @@ class Storage extends Service { enums.ImageFormat? output, String? token, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' .replaceAll( '{bucketId}', @@ -308,6 +381,18 @@ class Storage extends Service { required String fileId, String? token, }) async { + if (bucketId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "bucketId"', + ); + } + + if (fileId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "fileId"', + ); + } + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' .replaceAll( '{bucketId}', diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index d7f23f39..4fdbb987 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -61,6 +61,12 @@ class TablesDB extends Service { Future getTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -89,6 +95,12 @@ class TablesDB extends Service { bool? commit, bool? rollback, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -119,6 +131,12 @@ class TablesDB extends Service { Future deleteTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/tablesdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -129,6 +147,7 @@ class TablesDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -146,6 +165,12 @@ class TablesDB extends Service { required String transactionId, List? operations, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/tablesdb/transactions/{transactionId}/operations'.replaceAll( '{transactionId}', @@ -182,6 +207,18 @@ class TablesDB extends Service { bool? total, int? ttl, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' .replaceAll( '{databaseId}', @@ -226,6 +263,18 @@ class TablesDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows' .replaceAll( '{databaseId}', @@ -268,6 +317,24 @@ class TablesDB extends Service { List? queries, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' .replaceAll( @@ -315,6 +382,24 @@ class TablesDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' .replaceAll( @@ -362,6 +447,24 @@ class TablesDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' .replaceAll( @@ -406,6 +509,24 @@ class TablesDB extends Service { required String rowId, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}' .replaceAll( @@ -428,6 +549,7 @@ class TablesDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -450,6 +572,30 @@ class TablesDB extends Service { double? min, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + + if (column.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "column"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement' .replaceAll( @@ -501,6 +647,30 @@ class TablesDB extends Service { double? max, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (tableId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "tableId"', + ); + } + + if (rowId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "rowId"', + ); + } + + if (column.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "column"', + ); + } + final String apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment' .replaceAll( diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 99190fc1..99e9d722 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -72,6 +72,12 @@ class Teams extends Service { Future get({ required String teamId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}'.replaceAll( '{teamId}', teamId, @@ -99,6 +105,12 @@ class Teams extends Service { required String teamId, required String name, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}'.replaceAll( '{teamId}', teamId, @@ -129,6 +141,12 @@ class Teams extends Service { Future delete({ required String teamId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}'.replaceAll( '{teamId}', teamId, @@ -139,6 +157,7 @@ class Teams extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -157,6 +176,12 @@ class Teams extends Service { List? queries, bool? total, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/installations'.replaceAll( '{teamId}', teamId, @@ -191,6 +216,12 @@ class Teams extends Service { required String appId, String? authorizationDetails, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/installations'.replaceAll( '{teamId}', teamId, @@ -224,6 +255,18 @@ class Teams extends Service { required String teamId, required String installationId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll( '{teamId}', @@ -260,6 +303,18 @@ class Teams extends Service { required String installationId, String? authorizationDetails, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll( '{teamId}', @@ -298,6 +353,18 @@ class Teams extends Service { required String teamId, required String installationId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + final String apiPath = '/teams/{teamId}/installations/{installationId}' .replaceAll( '{teamId}', @@ -335,6 +402,12 @@ class Teams extends Service { String? search, bool? total, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships'.replaceAll( '{teamId}', teamId, @@ -390,6 +463,12 @@ class Teams extends Service { String? url, String? name, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships'.replaceAll( '{teamId}', teamId, @@ -427,6 +506,18 @@ class Teams extends Service { required String teamId, required String membershipId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (membershipId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "membershipId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' .replaceAll( '{teamId}', @@ -462,6 +553,18 @@ class Teams extends Service { required String membershipId, required List roles, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (membershipId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "membershipId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' .replaceAll( '{teamId}', @@ -499,6 +602,18 @@ class Teams extends Service { required String teamId, required String membershipId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (membershipId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "membershipId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' .replaceAll( '{teamId}', @@ -514,6 +629,7 @@ class Teams extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -538,6 +654,18 @@ class Teams extends Service { required String userId, required String secret, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + + if (membershipId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "membershipId"', + ); + } + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' .replaceAll( '{teamId}', @@ -575,6 +703,12 @@ class Teams extends Service { Future getPrefs({ required String teamId, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/prefs'.replaceAll( '{teamId}', teamId, @@ -604,6 +738,12 @@ class Teams extends Service { required String teamId, required Map prefs, }) async { + if (teamId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "teamId"', + ); + } + final String apiPath = '/teams/{teamId}/prefs'.replaceAll( '{teamId}', teamId, diff --git a/lib/services/vectors_db.dart b/lib/services/vectors_db.dart index 08ba3e81..e257b38c 100644 --- a/lib/services/vectors_db.dart +++ b/lib/services/vectors_db.dart @@ -59,6 +59,12 @@ class VectorsDB extends Service { Future getTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -87,6 +93,12 @@ class VectorsDB extends Service { bool? commit, bool? rollback, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -117,6 +129,12 @@ class VectorsDB extends Service { Future deleteTransaction({ required String transactionId, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/vectorsdb/transactions/{transactionId}'.replaceAll( '{transactionId}', transactionId, @@ -127,6 +145,7 @@ class VectorsDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( @@ -144,6 +163,12 @@ class VectorsDB extends Service { required String transactionId, List? operations, }) async { + if (transactionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "transactionId"', + ); + } + final String apiPath = '/vectorsdb/transactions/{transactionId}/operations'.replaceAll( '{transactionId}', @@ -180,6 +205,18 @@ class VectorsDB extends Service { bool? total, int? ttl, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -225,6 +262,18 @@ class VectorsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents' .replaceAll( @@ -271,6 +320,18 @@ class VectorsDB extends Service { bool? total, int? ttl, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents/query' .replaceAll( @@ -314,6 +375,24 @@ class VectorsDB extends Service { List? queries, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -361,6 +440,24 @@ class VectorsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -408,6 +505,24 @@ class VectorsDB extends Service { List? permissions, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -452,6 +567,24 @@ class VectorsDB extends Service { required String documentId, String? transactionId, }) async { + if (databaseId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "databaseId"', + ); + } + + if (collectionId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "collectionId"', + ); + } + + if (documentId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "documentId"', + ); + } + final String apiPath = '/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}' .replaceAll( @@ -474,6 +607,7 @@ class VectorsDB extends Service { final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', 'content-type': 'application/json', + 'accept': 'application/json', }; final res = await client.call( diff --git a/lib/src/client.dart b/lib/src/client.dart index dbfe4bdf..fedec03c 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -79,11 +79,6 @@ abstract class Client { /// The user session to authenticate with. Client setSession(String value); - /// Set DevKey. - /// - /// Your secret dev API key. - Client setDevKey(String value); - /// Set Cookie. /// /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes.. diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 9e6cf566..36e4bbc9 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -22,10 +22,6 @@ abstract class ClientBase implements Client { @override ClientBase setSession(value); - /// Your secret dev API key - @override - ClientBase setDevKey(value); - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBase setCookie(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index fdf011c8..d04f9bc6 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,8 +40,8 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '26.2.0', - 'X-Appwrite-Response-Format': '2.0.0', + 'x-sdk-version': '27.0.0', + 'X-Appwrite-Response-Format': '2.3.0', }; config = {}; @@ -94,14 +94,6 @@ class ClientBrowser extends ClientBase with ClientMixin { return this; } - /// Your secret dev API key - @override - ClientBrowser setDevKey(value) { - config['devKey'] = value; - addHeader('X-Appwrite-Dev-Key', value); - return this; - } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientBrowser setCookie(value) { @@ -346,21 +338,13 @@ class ClientBrowser extends ClientBase with ClientMixin { }) async { await init(); - // Combine headers to check for dev key - final combinedHeaders = {..._headers!, ...headers}; - - // Only include credentials when dev key is not set - if (combinedHeaders['X-Appwrite-Dev-Key'] == null) { - _httpClient.withCredentials = true; - } else { - _httpClient.withCredentials = false; - } + _httpClient.withCredentials = true; late http.Response res; http.BaseRequest request = prepareRequest( method, uri: Uri.parse(_endPoint + path), - headers: combinedHeaders, + headers: {..._headers!, ...headers}, params: params, ); try { diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 3ccefd87..f228d17f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -59,8 +59,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '26.2.0', - 'X-Appwrite-Response-Format': '2.0.0', + 'x-sdk-version': '27.0.0', + 'X-Appwrite-Response-Format': '2.3.0', }; config = {}; @@ -121,14 +121,6 @@ class ClientIO extends ClientBase with ClientMixin { return this; } - /// Your secret dev API key - @override - ClientIO setDevKey(value) { - config['devKey'] = value; - addHeader('X-Appwrite-Dev-Key', value); - return this; - } - /// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. @override ClientIO setCookie(value) { diff --git a/lib/src/enums/id_token_provider.dart b/lib/src/enums/id_token_provider.dart new file mode 100644 index 00000000..4863e845 --- /dev/null +++ b/lib/src/enums/id_token_provider.dart @@ -0,0 +1,12 @@ +part of '../../enums.dart'; + +enum IdTokenProvider { + apple(value: "apple"), + google(value: "google"); + + const IdTokenProvider({required this.value}); + + final String value; + + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 6626f3a0..02b85c7f 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -23,6 +23,7 @@ enum OAuthProvider { gitlab(value: "gitlab"), google(value: "google"), huggingface(value: "huggingface"), + kakao(value: "kakao"), keycloak(value: "keycloak"), kick(value: "kick"), linkedin(value: "linkedin"), @@ -38,6 +39,7 @@ enum OAuthProvider { slack(value: "slack"), spotify(value: "spotify"), stripe(value: "stripe"), + tiktok(value: "tiktok"), tradeshift(value: "tradeshift"), tradeshiftBox(value: "tradeshiftBox"), twitch(value: "twitch"), diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 2b07213b..d4fe5134 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -53,7 +53,7 @@ class Execution implements Model { /// Resource 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; - /// Resource(function/site) execution duration in seconds. + /// Total time the resource(function/site) took to respond, in seconds. final double duration; /// The scheduled time for execution. If left empty, execution will be queued immediately. diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 2f32c7f9..7203863d 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -32,6 +32,9 @@ class Identity implements Model { /// Identity Provider Refresh Token. final String providerRefreshToken; + /// Identity Provider ID token (JWT) from the most recent native sign-in. Empty for identities created through the browser OAuth2 flow. + final String providerIdToken; + Identity({ required this.$id, required this.$createdAt, @@ -43,6 +46,7 @@ class Identity implements Model { required this.providerAccessToken, required this.providerAccessTokenExpiry, required this.providerRefreshToken, + required this.providerIdToken, }); factory Identity.fromMap( Map map, @@ -58,6 +62,7 @@ class Identity implements Model { providerAccessToken: map['providerAccessToken'].toString(), providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), providerRefreshToken: map['providerRefreshToken'].toString(), + providerIdToken: map['providerIdToken'].toString(), ); } @@ -74,6 +79,7 @@ class Identity implements Model { "providerAccessToken": providerAccessToken, "providerAccessTokenExpiry": providerAccessTokenExpiry, "providerRefreshToken": providerRefreshToken, + "providerIdToken": providerIdToken, }; } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart deleted file mode 100644 index 296fe5f8..00000000 --- a/lib/src/models/log.dart +++ /dev/null @@ -1,151 +0,0 @@ -part of '../../models.dart'; - -/// Log -class Log implements Model { - /// Event name. - final String event; - - /// User ID of the actor recorded for this log. During impersonation, this is the original impersonator, not the impersonated target user. - final String userId; - - /// User email of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userEmail; - - /// User name of the actor recorded for this log. During impersonation, this is the original impersonator. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization. - final String userType; - - /// 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.userType, - 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(), - userType: map['userType'].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(), - ); - } - - @override - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "userType": userType, - "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 deleted file mode 100644 index 07828c75..00000000 --- a/lib/src/models/log_list.dart +++ /dev/null @@ -1,33 +0,0 @@ -part of '../../models.dart'; - -/// Logs List -class LogList implements Model { - /// Total number of logs that matched your query. - final int total; - - /// List of logs. - final List 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)), - ), - ); - } - - @override - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } -} diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 8650dfd5..7d58b908 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -59,6 +59,9 @@ class User implements Model { /// Whether the user email is in its canonical form. final bool? emailIsCanonical; + /// Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked. + final bool? passwordPwned; + /// Phone verification status. final bool phoneVerification; @@ -100,6 +103,7 @@ class User implements Model { this.emailIsDisposable, this.emailIsCorporate, this.emailIsCanonical, + this.passwordPwned, required this.phoneVerification, required this.mfa, required this.prefs, @@ -131,6 +135,7 @@ class User implements Model { emailIsDisposable: map['emailIsDisposable'], emailIsCorporate: map['emailIsCorporate'], emailIsCanonical: map['emailIsCanonical'], + passwordPwned: map['passwordPwned'], phoneVerification: map['phoneVerification'], mfa: map['mfa'], prefs: Preferences.fromMap( @@ -167,6 +172,7 @@ class User implements Model { "emailIsDisposable": emailIsDisposable, "emailIsCorporate": emailIsCorporate, "emailIsCanonical": emailIsCanonical, + "passwordPwned": passwordPwned, "phoneVerification": phoneVerification, "mfa": mfa, "prefs": prefs.toMap(), diff --git a/pubspec.yaml b/pubspec.yaml index a08b4cdb..b04bee5a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 26.2.0 +version: 27.0.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies 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/account_test.dart b/test/services/account_test.dart index 00c1e68e..ef1bc31b 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -303,20 +303,6 @@ void main() { expect(response, isA()); }); - test('test method listLogs()', () async { - final Map data = { - 'total': 5, - 'logs': [], - }; - - when( - client.call(HttpMethod.get), - ).thenAnswer((_) async => Response(data: data)); - - final response = await account.listLogs(); - expect(response, isA()); - }); - test('test method updateMFA()', () async { final Map data = { '\$id': "5e5ea5c16897e", @@ -878,6 +864,48 @@ void main() { expect(response, isA()); }); + test('test method createRecoveryOTP()', () async { + final Map data = { + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await account.createRecoveryOTP( + email: "email@example.com", + ); + expect(response, isA()); + }); + + test('test method updateRecoveryOTP()', () async { + final Map data = { + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateRecoveryOTP( + userId: "", + secret: "", + password: "password", + ); + expect(response, isA()); + }); + test('test method listSessions()', () async { final Map data = { 'total': 5, @@ -987,6 +1015,50 @@ void main() { expect(response, isA()); }); + test('test method createIdTokenSession()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5bb8c16897e", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'provider': "email", + 'providerUid': "user@example.com", + 'providerAccessToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'providerAccessTokenExpiry': "2020-10-15T06:38:00.000+00:00", + 'providerRefreshToken': "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + 'ip': "127.0.0.1", + 'osCode': "Mac", + 'osName': "Mac", + 'osVersion': "Mac", + 'clientType': "browser", + 'clientCode': "CM", + 'clientName': "Chrome Mobile iOS", + 'clientVersion': "84.0", + 'clientEngine': "WebKit", + 'clientEngineVersion': "605.1.15", + 'deviceName': "smartphone", + 'deviceBrand': "Google", + 'deviceModel': "Nexus 5", + 'countryCode': "US", + 'countryName': "United States", + 'current': true, + 'factors': [], + 'secret': "5e5bb8c16897e", + 'mfaUpdatedAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await account.createIdTokenSession( + provider: enums.IdTokenProvider.apple, + idToken: "", + ); + expect(response, isA()); + }); + test('test method updateMagicURLSession()', () async { final Map data = { '\$id': "5e5ea5c16897e", @@ -1470,6 +1542,45 @@ void main() { expect(response, isA()); }); + test('test method createEmailVerificationOTP()', () async { + final Map data = { + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await account.createEmailVerificationOTP(); + expect(response, isA()); + }); + + test('test method updateEmailVerificationOTP()', () async { + final Map data = { + '\$id': "bb8ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c168bb8", + 'secret': "", + 'expire': "2020-10-15T06:38:00.000+00:00", + 'phrase': "Golden Fox", + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await account.updateEmailVerificationOTP( + userId: "", + secret: "", + ); + expect(response, isA()); + }); + test('test method createPhoneVerification()', () async { final Map data = { '\$id': "bb8ea5c16897e", diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index aae489d9..75d34f13 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -100,7 +100,7 @@ void main() { 'responseHeaders': [], 'logs': "", 'errors': "", - 'duration': 0.4, + 'duration': 1.23, }; when( @@ -132,7 +132,7 @@ void main() { 'responseHeaders': [], 'logs': "", 'errors': "", - 'duration': 0.4, + 'duration': 1.23, }; when( diff --git a/test/src/models/execution_test.dart b/test/src/models/execution_test.dart index 15955b9a..2ead39c0 100644 --- a/test/src/models/execution_test.dart +++ b/test/src/models/execution_test.dart @@ -23,7 +23,7 @@ void main() { responseHeaders: [], logs: "", errors: "", - duration: 0.4, + duration: 1.23, ); final map = model.toMap(); @@ -46,7 +46,7 @@ void main() { expect(result.responseHeaders, []); expect(result.logs, ""); expect(result.errors, ""); - expect(result.duration, 0.4); + expect(result.duration, 1.23); }); }); } diff --git a/test/src/models/identity_test.dart b/test/src/models/identity_test.dart index a88b2dbe..5d8d275c 100644 --- a/test/src/models/identity_test.dart +++ b/test/src/models/identity_test.dart @@ -15,6 +15,8 @@ void main() { providerAccessToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", providerAccessTokenExpiry: "2020-10-15T06:38:00.000+00:00", providerRefreshToken: "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", + providerIdToken: + "eyJhbGciOiJSUzI1NiIsImtpZCI6IjBhYzNmMWQwNWExYjhlN2YifQ.eyJzdWIiOiIxMTAxNjk0ODQ0NzQzODYyNzYzMzQifQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", ); final map = model.toMap(); @@ -30,6 +32,10 @@ void main() { expect(result.providerAccessToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); expect(result.providerAccessTokenExpiry, "2020-10-15T06:38:00.000+00:00"); expect(result.providerRefreshToken, "MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3"); + expect( + result.providerIdToken, + "eyJhbGciOiJSUzI1NiIsImtpZCI6IjBhYzNmMWQwNWExYjhlN2YifQ.eyJzdWIiOiIxMTAxNjk0ODQ0NzQzODYyNzYzMzQifQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", + ); }); }); } diff --git a/test/src/models/log_list_test.dart b/test/src/models/log_list_test.dart deleted file mode 100644 index b07ca8ee..00000000 --- a/test/src/models/log_list_test.dart +++ /dev/null @@ -1,19 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('LogList', () { - test('model', () { - final model = LogList( - total: 5, - logs: [], - ); - - final map = model.toMap(); - final result = LogList.fromMap(map); - - expect(result.total, 5); - expect(result.logs, []); - }); - }); -} diff --git a/test/src/models/log_test.dart b/test/src/models/log_test.dart deleted file mode 100644 index 3b4d95af..00000000 --- a/test/src/models/log_test.dart +++ /dev/null @@ -1,59 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('Log', () { - test('model', () { - final model = Log( - event: "account.sessions.create", - userId: "610fc2f985ee0", - userEmail: "john@appwrite.io", - userName: "John Doe", - mode: "admin", - userType: "user", - ip: "127.0.0.1", - time: "2020-10-15T06:38:00.000+00:00", - osCode: "Mac", - osName: "Mac", - osVersion: "Mac", - clientType: "browser", - clientCode: "CM", - clientName: "Chrome Mobile iOS", - clientVersion: "84.0", - clientEngine: "WebKit", - clientEngineVersion: "605.1.15", - deviceName: "smartphone", - deviceBrand: "Google", - deviceModel: "Nexus 5", - countryCode: "US", - countryName: "United States", - ); - - final map = model.toMap(); - final result = Log.fromMap(map); - - expect(result.event, "account.sessions.create"); - expect(result.userId, "610fc2f985ee0"); - expect(result.userEmail, "john@appwrite.io"); - expect(result.userName, "John Doe"); - expect(result.mode, "admin"); - expect(result.userType, "user"); - expect(result.ip, "127.0.0.1"); - expect(result.time, "2020-10-15T06:38:00.000+00:00"); - expect(result.osCode, "Mac"); - expect(result.osName, "Mac"); - expect(result.osVersion, "Mac"); - expect(result.clientType, "browser"); - expect(result.clientCode, "CM"); - expect(result.clientName, "Chrome Mobile iOS"); - expect(result.clientVersion, "84.0"); - expect(result.clientEngine, "WebKit"); - expect(result.clientEngineVersion, "605.1.15"); - expect(result.deviceName, "smartphone"); - expect(result.deviceBrand, "Google"); - expect(result.deviceModel, "Nexus 5"); - expect(result.countryCode, "US"); - expect(result.countryName, "United States"); - }); - }); -} From fd1381cce363a0cf1a930a60c49c2a1d6ae81123 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Tue, 6 Oct 2026 06:27:59 +0000 Subject: [PATCH 16/17] chore: update Flutter SDK to 27.1.0-rc.0 --- CHANGELOG.md | 11 + README.md | 43 +- android/.editorconfig | 39 + android/build.gradle | 56 + android/consumer-rules.pro | 27 + android/settings.gradle | 1 + android/src/main/AndroidManifest.xml | 41 + .../appwrite/exceptions/AppwriteException.kt | 6 + .../io/appwrite/flutter/AppwritePushPlugin.kt | 108 ++ .../io/appwrite/services/PushBackground.kt | 1009 +++++++++++++ .../kotlin/io/appwrite/services/PushBridge.kt | 135 ++ .../kotlin/io/appwrite/services/PushCore.kt | 374 +++++ .../io/appwrite/services/PushReceiver.kt | 33 + .../io/appwrite/services/PushService.kt | 67 + .../io/appwrite/services/PushWakeups.kt | 46 + .../account/create-email-password-session.md | 1 + docs/examples/account/delete-sessions.md | 4 +- docs/examples/account/list-sessions.md | 4 +- .../apps/create-installation-token.md | 14 + docs/examples/apps/create-key.md | 13 + docs/examples/apps/create-secret.md | 13 + docs/examples/apps/create.md | 31 + docs/examples/apps/delete-installation.md | 14 + docs/examples/apps/delete-key.md | 14 + docs/examples/apps/delete-secret.md | 14 + docs/examples/apps/delete-tokens.md | 13 + docs/examples/apps/delete.md | 13 + docs/examples/apps/get-installation.md | 14 + docs/examples/apps/get-key.md | 14 + docs/examples/apps/get-secret.md | 14 + docs/examples/apps/get.md | 13 + .../examples/apps/list-installation-scopes.md | 11 + docs/examples/apps/list-installations.md | 15 + docs/examples/apps/list-keys.md | 15 + docs/examples/apps/list-o-auth-2-scopes.md | 11 + docs/examples/apps/list-secrets.md | 15 + docs/examples/apps/list.md | 14 + docs/examples/apps/update-team.md | 14 + docs/examples/apps/update.md | 32 + docs/examples/avatars/delete-photo.md | 11 + docs/examples/avatars/get-screenshot.md | 6 +- docs/examples/avatars/update-photo.md | 14 + docs/examples/databases/list-transactions.md | 1 + docs/examples/documentsdb/create-documents.md | 11 +- .../examples/documentsdb/list-transactions.md | 1 + docs/examples/graphql/mutation.md | 4 +- docs/examples/graphql/query.md | 4 +- docs/examples/locale/list-codes.md | 4 +- docs/examples/locale/list-continents.md | 4 +- docs/examples/locale/list-countries-eu.md | 4 +- docs/examples/locale/list-countries-phones.md | 4 +- docs/examples/locale/list-countries.md | 4 +- docs/examples/locale/list-currencies.md | 4 +- docs/examples/locale/list-languages.md | 4 +- docs/examples/oauth2/approve.md | 15 + docs/examples/oauth2/authorize-post.md | 26 + docs/examples/oauth2/authorize.md | 26 + .../oauth2/create-device-authorization.md | 17 + docs/examples/oauth2/create-grant.md | 13 + docs/examples/oauth2/create-par.md | 25 + docs/examples/oauth2/create-token.md | 22 + docs/examples/oauth2/get-grant.md | 13 + docs/examples/oauth2/list-organizations.md | 15 + docs/examples/oauth2/list-projects.md | 15 + docs/examples/oauth2/logout-post.md | 18 + docs/examples/oauth2/logout.md | 18 + docs/examples/oauth2/reject.md | 13 + docs/examples/oauth2/revoke.md | 16 + docs/examples/tablesdb/list-transactions.md | 1 + docs/examples/teams/create-membership.md | 2 +- docs/examples/teams/update-membership.md | 2 +- docs/examples/vectorsdb/create-operations.md | 10 +- docs/examples/vectorsdb/list-transactions.md | 1 + lib/appwrite.dart | 5 + lib/models.dart | 21 + lib/query.dart | 38 +- lib/services/account.dart | 24 +- lib/services/apps.dart | 852 +++++++++++ lib/services/avatars.dart | 68 +- lib/services/databases.dart | 12 +- lib/services/documents_db.dart | 32 +- lib/services/locale.dart | 56 +- lib/services/oauth2.dart | 588 ++++++++ lib/services/organization.dart | 30 +- lib/services/storage.dart | 1 + lib/services/tables_db.dart | 12 +- lib/services/vectors_db.dart | 12 +- lib/src/client.dart | 13 +- lib/src/client_base.dart | 6 + lib/src/client_browser.dart | 33 +- lib/src/client_io.dart | 63 +- lib/src/client_mixin.dart | 41 +- lib/src/cookie_manager.dart | 22 +- lib/src/enums.dart | 2 +- lib/src/enums/o_auth_provider.dart | 1 + lib/src/input_file.dart | 30 +- lib/src/models/account.dart | 167 +++ lib/src/models/app.dart | 177 +++ lib/src/models/app_key.dart | 73 + lib/src/models/app_key_list.dart | 33 + lib/src/models/app_scope.dart | 49 + lib/src/models/app_scope_list.dart | 33 + lib/src/models/app_secret.dart | 73 + lib/src/models/app_secret_list.dart | 33 + lib/src/models/app_secret_plaintext.dart | 73 + lib/src/models/apps_list.dart | 33 + lib/src/models/oauth2_approve.dart | 25 + lib/src/models/oauth2_authorize.dart | 31 + .../models/oauth2_device_authorization.dart | 55 + lib/src/models/oauth2_grant.dart | 91 ++ lib/src/models/oauth2_organization.dart | 25 + lib/src/models/oauth2_organization_list.dart | 33 + lib/src/models/oauth2_par.dart | 31 + lib/src/models/oauth2_project.dart | 37 + lib/src/models/oauth2_project_list.dart | 33 + lib/src/models/oauth2_reject.dart | 25 + lib/src/models/oauth2_token.dart | 61 + lib/src/mqtt.dart | 129 ++ lib/src/mqtt_browser.dart | 904 +++++++++++ lib/src/mqtt_foreground.dart | 322 ++++ lib/src/mqtt_io.dart | 1333 +++++++++++++++++ lib/src/mqtt_message.dart | 24 + lib/src/mqtt_native.dart | 128 ++ lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 +- lib/src/realtime_mixin.dart | 185 +-- lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- lib/topic.dart | 85 ++ pubspec.yaml | 15 +- test/channel_test.dart | 89 +- test/services/account_test.dart | 2 + test/services/apps_test.dart | 524 +++++++ test/services/avatars_test.dart | 48 + test/services/databases_test.dart | 2 + test/services/documents_db_test.dart | 2 + test/services/functions_test.dart | 2 + test/services/graphql_test.dart | 2 + test/services/locale_test.dart | 2 + test/services/messaging_test.dart | 2 + test/services/oauth2_test.dart | 300 ++++ test/services/organization_test.dart | 2 + test/services/presences_test.dart | 2 + test/services/storage_test.dart | 2 + test/services/tables_db_test.dart | 2 + test/services/teams_test.dart | 2 + test/services/vectors_db_test.dart | 2 + test/src/input_file_test.dart | 55 +- test/src/models/account_test.dart | 46 + test/src/models/app_key_list_test.dart | 19 + test/src/models/app_key_test.dart | 35 + test/src/models/app_scope_list_test.dart | 19 + test/src/models/app_scope_test.dart | 25 + test/src/models/app_secret_list_test.dart | 19 + .../src/models/app_secret_plaintext_test.dart | 35 + test/src/models/app_secret_test.dart | 31 + test/src/models/app_test.dart | 67 + test/src/models/apps_list_test.dart | 19 + test/src/models/oauth2_approve_test.dart | 20 + test/src/models/oauth2_authorize_test.dart | 22 + .../oauth2_device_authorization_test.dart | 35 + test/src/models/oauth2_grant_test.dart | 43 + .../models/oauth2_organization_list_test.dart | 19 + test/src/models/oauth2_organization_test.dart | 17 + test/src/models/oauth2_par_test.dart | 19 + test/src/models/oauth2_project_list_test.dart | 19 + test/src/models/oauth2_project_test.dart | 21 + test/src/models/oauth2_reject_test.dart | 21 + test/src/models/oauth2_token_test.dart | 25 + test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 +- test/src/upload_progress_test.dart | 2 +- test/topic_test.dart | 70 + 173 files changed, 10386 insertions(+), 313 deletions(-) create mode 100644 android/.editorconfig create mode 100644 android/build.gradle create mode 100644 android/consumer-rules.pro create mode 100644 android/settings.gradle create mode 100644 android/src/main/AndroidManifest.xml create mode 100644 android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt create mode 100644 android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushBackground.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushBridge.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushCore.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushReceiver.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushService.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushWakeups.kt create mode 100644 docs/examples/apps/create-installation-token.md create mode 100644 docs/examples/apps/create-key.md create mode 100644 docs/examples/apps/create-secret.md create mode 100644 docs/examples/apps/create.md create mode 100644 docs/examples/apps/delete-installation.md create mode 100644 docs/examples/apps/delete-key.md create mode 100644 docs/examples/apps/delete-secret.md create mode 100644 docs/examples/apps/delete-tokens.md create mode 100644 docs/examples/apps/delete.md create mode 100644 docs/examples/apps/get-installation.md create mode 100644 docs/examples/apps/get-key.md create mode 100644 docs/examples/apps/get-secret.md create mode 100644 docs/examples/apps/get.md create mode 100644 docs/examples/apps/list-installation-scopes.md create mode 100644 docs/examples/apps/list-installations.md create mode 100644 docs/examples/apps/list-keys.md create mode 100644 docs/examples/apps/list-o-auth-2-scopes.md create mode 100644 docs/examples/apps/list-secrets.md create mode 100644 docs/examples/apps/list.md create mode 100644 docs/examples/apps/update-team.md create mode 100644 docs/examples/apps/update.md create mode 100644 docs/examples/avatars/delete-photo.md create mode 100644 docs/examples/avatars/update-photo.md create mode 100644 docs/examples/oauth2/approve.md create mode 100644 docs/examples/oauth2/authorize-post.md create mode 100644 docs/examples/oauth2/authorize.md create mode 100644 docs/examples/oauth2/create-device-authorization.md create mode 100644 docs/examples/oauth2/create-grant.md create mode 100644 docs/examples/oauth2/create-par.md create mode 100644 docs/examples/oauth2/create-token.md create mode 100644 docs/examples/oauth2/get-grant.md create mode 100644 docs/examples/oauth2/list-organizations.md create mode 100644 docs/examples/oauth2/list-projects.md create mode 100644 docs/examples/oauth2/logout-post.md create mode 100644 docs/examples/oauth2/logout.md create mode 100644 docs/examples/oauth2/reject.md create mode 100644 docs/examples/oauth2/revoke.md create mode 100644 lib/services/apps.dart create mode 100644 lib/services/oauth2.dart create mode 100644 lib/src/models/account.dart create mode 100644 lib/src/models/app.dart create mode 100644 lib/src/models/app_key.dart create mode 100644 lib/src/models/app_key_list.dart create mode 100644 lib/src/models/app_scope.dart create mode 100644 lib/src/models/app_scope_list.dart create mode 100644 lib/src/models/app_secret.dart create mode 100644 lib/src/models/app_secret_list.dart create mode 100644 lib/src/models/app_secret_plaintext.dart create mode 100644 lib/src/models/apps_list.dart create mode 100644 lib/src/models/oauth2_approve.dart create mode 100644 lib/src/models/oauth2_authorize.dart create mode 100644 lib/src/models/oauth2_device_authorization.dart create mode 100644 lib/src/models/oauth2_grant.dart create mode 100644 lib/src/models/oauth2_organization.dart create mode 100644 lib/src/models/oauth2_organization_list.dart create mode 100644 lib/src/models/oauth2_par.dart create mode 100644 lib/src/models/oauth2_project.dart create mode 100644 lib/src/models/oauth2_project_list.dart create mode 100644 lib/src/models/oauth2_reject.dart create mode 100644 lib/src/models/oauth2_token.dart create mode 100644 lib/src/mqtt.dart create mode 100644 lib/src/mqtt_browser.dart create mode 100644 lib/src/mqtt_foreground.dart create mode 100644 lib/src/mqtt_io.dart create mode 100644 lib/src/mqtt_message.dart create mode 100644 lib/src/mqtt_native.dart create mode 100644 lib/topic.dart create mode 100644 test/services/apps_test.dart create mode 100644 test/services/oauth2_test.dart create mode 100644 test/src/models/account_test.dart create mode 100644 test/src/models/app_key_list_test.dart create mode 100644 test/src/models/app_key_test.dart create mode 100644 test/src/models/app_scope_list_test.dart create mode 100644 test/src/models/app_scope_test.dart create mode 100644 test/src/models/app_secret_list_test.dart create mode 100644 test/src/models/app_secret_plaintext_test.dart create mode 100644 test/src/models/app_secret_test.dart create mode 100644 test/src/models/app_test.dart create mode 100644 test/src/models/apps_list_test.dart create mode 100644 test/src/models/oauth2_approve_test.dart create mode 100644 test/src/models/oauth2_authorize_test.dart create mode 100644 test/src/models/oauth2_device_authorization_test.dart create mode 100644 test/src/models/oauth2_grant_test.dart create mode 100644 test/src/models/oauth2_organization_list_test.dart create mode 100644 test/src/models/oauth2_organization_test.dart create mode 100644 test/src/models/oauth2_par_test.dart create mode 100644 test/src/models/oauth2_project_list_test.dart create mode 100644 test/src/models/oauth2_project_test.dart create mode 100644 test/src/models/oauth2_reject_test.dart create mode 100644 test/src/models/oauth2_token_test.dart create mode 100644 test/topic_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 1344896b..547ce7c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change Log +## 27.1.0-rc.0 + +* Added: `Apps` service to manage OAuth2 apps, keys, secrets, and installations +* Added: `Oauth2` service for authorization, consent, device, PAR, and token flows +* Added: `Push` service for MQTT realtime push with iOS background delivery +* Added: `Topic` builder and a native `android` module for push +* Added: `Client.setPushEndpoint()` and `Client.setPushClientId()` +* Added: `Avatars.updatePhoto()` and `Avatars.deletePhoto()` methods +* Added: `App`, `Oauth2*`, and `Account` models +* Added: `webflow` to the `OAuthProvider` enum + ## 27.0.0 * Breaking: removed `Account.listLogs` and the `Log`, `LogList` models diff --git a/README.md b/README.md index bbc066a7..e8465a41 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^27.0.0 + appwrite: ^27.1.0-rc.0 ``` You can install packages from the command line: @@ -28,6 +28,45 @@ You can install packages from the command line: flutter pub add appwrite ``` +### Push on Android + +`Push` includes a native Android plugin, and `flutter_local_notifications` needs core library +desugaring, so add this to `android/app/build.gradle.kts` (desugaring is configured when the app +is assembled, so a plugin cannot apply it for you): + +```kotlin +android { + compileOptions { + isCoreLibraryDesugaringEnabled = true + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") +} +``` + +A subscription with `background: true` keeps delivering after the app is backgrounded, killed or +the device restarts, until it is unsubscribed or `push.close()` is called (do this on sign-out). +The plugin saves the subscription, and a scheduled job and alarm wake the app every 15 to 60 +seconds to reconnect; the broker replays what was sent in between (`retry: true`). Messages no +in-app callback receives are posted as notifications that open the app. It reconnects with the +credential saved at subscribe time, so use a session rather than a short-lived JWT. + +```dart +final sub = await push.subscribe('news', (message) => print(message.data), + background: true, title: 'News'); + +// Optional: immediate delivery even after a kill and during Doze, with a quiet ongoing +// notification (call while the app is in the foreground). +await push.setForeground(true); +``` + +Foreground mode runs a `remoteMessaging` foreground service, which Google Play asks apps to +declare in the Play Console. Apps that never enable it can remove the service from their merged +manifest with `tools:node="remove"` on `io.appwrite.services.PushService` and +`android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING`. + ## Getting Started @@ -38,6 +77,8 @@ From the options, choose to add a new **Flutter** platform and add your app cred If you are building your Flutter application for multiple devices, you have to follow this process for each different device. +> On Android, iOS and macOS, call `createOAuth2Session` without the `success` and `failure` URLs. The SDK only returns to your app through the `appwrite-callback-[PROJECT_ID]` scheme, and only the default redirect carries the new session with it. A custom URL, such as an https App Link, makes the call fail (for example with `PlatformException(CANCELED)`) even when the login itself succeeded. Await the returned `Future` and navigate from your Dart code instead. + ### Android For **Android** first add your app name and package name, Your package name is generally the **applicationId** in your app-level build.gradle file. By registering your new app platform, you are allowing your app to communicate with the Appwrite API. diff --git a/android/.editorconfig b/android/.editorconfig new file mode 100644 index 00000000..f0895a33 --- /dev/null +++ b/android/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*.{kt,kts}] +ktlint_code_style = ktlint_official +ktlint_standard_annotation = disabled +ktlint_standard_argument-list-wrapping = disabled +ktlint_standard_blank-line-before-declaration = disabled +ktlint_standard_blank-line-between-when-conditions = disabled +ktlint_standard_chain-method-continuation = disabled +ktlint_standard_class-signature = disabled +ktlint_standard_function-expression-body = disabled +ktlint_standard_function-signature = disabled +ktlint_standard_function-start-of-body-spacing = disabled +ktlint_standard_if-else-bracing = disabled +ktlint_standard_if-else-wrapping = disabled +ktlint_standard_max-line-length = disabled +ktlint_standard_multiline-expression-wrapping = disabled +ktlint_standard_multiline-if-else = disabled +ktlint_standard_no-blank-line-before-rbrace = disabled +ktlint_standard_no-blank-line-in-list = disabled +ktlint_standard_no-empty-first-line-in-class-body = disabled +ktlint_standard_no-line-break-before-assignment = disabled +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_parameter-list-wrapping = disabled +ktlint_standard_spacing-between-declarations-with-annotations = disabled +ktlint_standard_spacing-between-declarations-with-comments = disabled +ktlint_standard_string-template = disabled +ktlint_standard_trailing-comma-on-call-site = disabled +ktlint_standard_trailing-comma-on-declaration-site = disabled +ktlint_standard_when-entry-bracing = disabled +ktlint_standard_wrapping = disabled + +[**/Channel.kt] +# Marker types intentionally use leading underscores to distinguish channel states. +ktlint_standard_class-naming = disabled + +[**/models/*.kt] +# Model imports follow schema property order so generated declarations stay deterministic. +ktlint_standard_import-ordering = disabled diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 00000000..47df6fdf --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,56 @@ +// The native half of Push on Android: background delivery that survives the process being +// killed, a reboot and an app update, shared with the Appwrite Android SDK. +group = "io.appwrite.flutter" +version = "27.1.0-rc.0" + +buildscript { + ext.kotlin_version = "2.1.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.7.3") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" +apply plugin: "kotlin-android" + +android { + namespace = "io.appwrite.flutter" + compileSdk = 35 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + sourceSets { + main.java.srcDirs += "src/main/kotlin" + } + + defaultConfig { + minSdk = 24 + // R8 rules for the bundled MQTT client, applied to the app. + consumerProguardFiles("consumer-rules.pro") + } +} + +dependencies { + implementation("com.hivemq:hivemq-mqtt-client-shaded:1.3.6") + implementation("androidx.core:core-ktx:1.13.1") +} diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro new file mode 100644 index 00000000..04d7db2c --- /dev/null +++ b/android/consumer-rules.pro @@ -0,0 +1,27 @@ +# Push: rules applied to apps that shrink with R8. +# +# The shaded HiveMQ MQTT client relocates Netty and JCTools under +# com.hivemq.client.internal.shaded. Netty references optional classes that are never loaded +# on Android: native transports, the HTTP/WebSocket codecs, proxy handlers, alternative TLS +# providers (tcnative, BouncyCastle, Conscrypt, Jetty ALPN) and logging backends. +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.epoll.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.kqueue.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.codec.http.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.proxy.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.internal.tcnative.** +-dontwarn org.bouncycastle.** +-dontwarn org.conscrypt.** +-dontwarn org.eclipse.jetty.** +-dontwarn org.apache.log4j.** +-dontwarn org.apache.logging.log4j.** +-dontwarn org.slf4j.** +-dontwarn reactor.blockhound.** + +# Netty and JCTools reach their own fields by name, through atomic field updaters and Unsafe offsets. +-keepclassmembernames class com.hivemq.client.internal.shaded.io.netty.** { ; } +-keepclassmembers class com.hivemq.client.internal.shaded.org.jctools.** { ; } + +# Netty's leak detector looks these methods up by name when its classes load. +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AbstractByteBufAllocator { *** toLeakAwareBuffer(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AdvancedLeakAwareByteBuf { *** recordLeakNonRefCountingOperation(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.util.ReferenceCountUtil { *** touch(...); } diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 00000000..137b5997 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'appwrite' diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..44f894ed --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt new file mode 100644 index 00000000..81b0d30e --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt @@ -0,0 +1,6 @@ +package io.appwrite.exceptions + +/** A push error. When the broker explained a refusal or a disconnect, that is its message. */ +class AppwriteException( + override val message: String? = null, +) : Exception(message) diff --git a/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt new file mode 100644 index 00000000..c68a60c6 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt @@ -0,0 +1,108 @@ +package io.appwrite.flutter + +import android.os.Handler +import android.os.Looper +import io.appwrite.services.PushBridge +import io.appwrite.services.PushMessage +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +/** + * The Flutter side of [PushBridge]: the SDK's `Push` hosts its background subscriptions here on + * Android over a method channel, and receives their messages and errors over an event channel. + */ +class AppwritePushPlugin : + FlutterPlugin, + MethodChannel.MethodCallHandler, + EventChannel.StreamHandler { + private val main = Handler(Looper.getMainLooper()) + private var methods: MethodChannel? = null + private var events: EventChannel? = null + private var sink: EventChannel.EventSink? = null + private var bridge: PushBridge? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + bridge = PushBridge( + binding.applicationContext, + object : PushBridge.Events { + override fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) = send( + mapOf( + "type" to "message", + "id" to subscriptionId, + "topic" to message.topic, + "payload" to message.payload, + "qos" to message.qos, + "ackToken" to ackToken, + ), + ) + + override fun onError(message: String) = send(mapOf("type" to "error", "message" to message)) + }, + ) + methods = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL).also { it.setMethodCallHandler(this) } + events = EventChannel(binding.binaryMessenger, EVENT_CHANNEL).also { it.setStreamHandler(this) } + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + methods?.setMethodCallHandler(null) + events?.setStreamHandler(null) + methods = null + events = null + sink = null + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + val bridge = bridge ?: return result.error(ERROR_CODE, "Push plugin is not attached", null) + try { + if (call.method == "host") { + // Replies once the connection is up and every filter is subscribed, or with why not. + bridge.host(call.argument("config")!!, call.argument("subscriptions")!!) { error -> + main.post { + if (error == null) { + result.success(null) + } else { + result.error(ERROR_CODE, error, null) + } + } + } + return + } + result.success( + when (call.method) { + "ack" -> bridge.ack(call.argument("token")!!).let { null } + "release" -> bridge.release().let { null } + "stop" -> bridge.stop().let { null } + "setForeground" -> bridge.setForeground(call.argument("enabled") == true).let { null } + "hasSaved" -> bridge.hasSaved() + "resume" -> bridge.resume().let { null } + "setErrorCallback" -> bridge.setErrorCallback(call.argument("registered") == true) + "defaultClientId" -> bridge.defaultClientId(call.argument("authMethod")!!, call.argument("credential")!!) + else -> return result.notImplemented() + }, + ) + } catch (e: Exception) { + result.error(ERROR_CODE, e.message, null) + } + } + + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + sink = events + } + + override fun onCancel(arguments: Any?) { + sink = null + } + + // The bridge calls back on background threads; event sinks must be used on the main thread. + private fun send(event: Map) { + main.post { sink?.success(event) } + } + + private companion object { + const val METHOD_CHANNEL = "appwrite.push" + const val EVENT_CHANNEL = "appwrite.push/events" + const val ERROR_CODE = "appwrite_push" + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBackground.kt b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt new file mode 100644 index 00000000..52517344 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt @@ -0,0 +1,1009 @@ +package io.appwrite.services + +import android.app.AlarmManager +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.job.JobInfo +import android.app.job.JobScheduler +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.Network +import android.os.Build +import android.os.PowerManager +import android.os.SystemClock +import android.util.AtomicFile +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.hivemq.client.mqtt.MqttGlobalPublishFilter +import com.hivemq.client.mqtt.datatypes.MqttQos +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.util.UUID +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger + +private const val LOG_TAG = "AppwritePush" + +/** A background subscription saved across restarts: its filter, QoS choice and notification title. */ +internal data class PushEntry( + val filter: String, + val retry: Boolean, + val title: String?, +) + +/** + * The adaptive heartbeat: its interval, the current streak of failed heartbeats, and when the + * interval last shrank (wall-clock ms, as it must survive reboots). + */ +internal data class PushHeartbeat( + val intervalMs: Long, + val failures: Int = 0, + val shrunkAt: Long = 0L, +) + +/** + * The process-wide host of the background push connection, modelled on how socket push + * services survive on Android without keeping a service alive. + * + * The background subscriptions and their connection config are saved to private storage (see + * [PushStore]), so delivery survives the process being killed, a reboot and an app update. A + * job ([PushJobService]) that reschedules itself on every run, backed by an alarm + * ([PushAlarmReceiver]), wakes the process every 15 seconds (60 when the app may use exact + * alarms or is exempt from battery optimisation). Each run holds a short wakelock and + * reconnects when the connection is gone or the default network changed, sends a heartbeat + * when one is due, and re-arms the job. While the process is alive between runs the socket + * stays open and messages arrive immediately; while it is dead the broker keeps the backlog + * for this client id and replays it when the next run subscribes again. + * + * With foreground mode enabled ([Push.setForeground]) a foreground service ([PushService]) also keeps + * the process at foreground priority, so delivery is immediate after a kill and during Doze. + * + * Messages go to the live in-app callbacks that match them. When none match (the process was + * started in the background), a declared [PushReceiver] gets the message, and a notification + * is posted unless it returns true. + */ +internal object PushBackground { + const val CHANNEL_ID = "appwrite-push" + const val NOTIFICATION_ID = 1911 + const val ACTION_TICK = "io.appwrite.push.TICK" + const val ACTION_MESSAGE = "io.appwrite.push.MESSAGE" + const val NOTIFICATION_ICON = "io.appwrite.push.notification_icon" + const val EXTRA_TOPIC = "io.appwrite.push.TOPIC" + const val EXTRA_PAYLOAD = "io.appwrite.push.PAYLOAD" + + private const val SERVICE_CHANNEL_ID = "appwrite-push-service" + private const val JOB_ID = 0x50555348 + private const val INTERVAL_MS = 15_000L + private const val PRIVILEGED_INTERVAL_MS = 60_000L + private const val RESTART_DELAY_MS = 3_000L + // An upper bound covering a run's connect (20 s) and its requests (10 s each); the wakelock is + // released as soon as the run finishes. + private const val WAKE_LOCK_MS = 60_000L + private const val KEEP_ALIVE_SECONDS = 300 + + // The heartbeat interval: below the broker's 1.5 x keep-alive expiry, measured on a clock that + // counts deep sleep. Networks that drop idle connections sooner (carrier NATs) make heartbeats + // fail; after HEARTBEAT_FAILURES in a row the interval shrinks by a quarter, down to + // MIN_HEARTBEAT_MS, and returns to the default HEARTBEAT_RESET_MS after the last shrink, in + // case the device moved to a better network. + const val HEARTBEAT_MS = 180_000L + private const val MIN_HEARTBEAT_MS = 60_000L + private const val HEARTBEAT_FAILURES = 3 + private const val HEARTBEAT_RESET_MS = 3 * 24 * 60 * 60 * 1_000L + private const val REQUEST_TIMEOUT_SECONDS = 10L + private const val CONNECT_TIMEOUT_SECONDS = 20L + + // How long a message waits for a listener that acknowledges it itself (the React Native and + // Flutter bridges, once their callback has run) before it is acknowledged anyway, so one stuck + // callback cannot hold back the acknowledgements after it. + private const val ACK_TIMEOUT_SECONDS = 10L + + // Unsubscribing a filter nothing subscribes to is a harmless round trip the broker always + // acknowledges, so it proves the connection is alive. The broker ignores client PUBLISHes + // without a PUBACK, so a publish cannot serve as the heartbeat. + private const val HEARTBEAT_FILTER = "\$heartbeat" + + @Volatile + var channelName: String = "Notifications" + + @Volatile + var ongoingTitle: String = "Appwrite" + + // Reports errors to the Push instance that hosts its subscriptions here. Returns whether the + // app's onError received the error (false when it registered none). + @Volatile + var errorHandler: ((Throwable) -> Boolean)? = null + + @Volatile + var serviceRunning = false + + // Whether a refused service start was reported, so a job that retries it every run does not + // report the same failure every 15 seconds. + @Volatile + private var serviceStartReported = false + + // The live in-app subscriptions hosted here, each with its callback. Empty after the process + // was restarted in the background, until the app subscribes again. + val listeners = CopyOnWriteArrayList() + + // Guards the saved state below and its copy on disk. + private val lock = Any() + private var loaded = false + private var config: PushConfig? = null + + // Background subscriptions saved by an earlier run that no live subscription has taken over. + private var saved: List = emptyList() + + // Every MQTT call runs on this thread, in order, so the connection state below needs no lock. + private val worker = Executors.newSingleThreadScheduledExecutor { runnable -> + Thread(runnable, "AppwritePushBackground").apply { isDaemon = true } + } + private var mqtt: Mqtt5AsyncClient? = null + private var connectedConfig: PushConfig? = null + private var connectedNetwork: Network? = null + private var lastHeartbeat = 0L + private var heartbeatState: PushHeartbeat? = null + private val subscribed = mutableMapOf() + private var networkCallback: ConnectivityManager.NetworkCallback? = null + + // Worker thread only. While a caller waits for a converge (host with a completion), its + // failures go to that caller, which reports them, instead of onError. + private var waiting = false + private var failure: Throwable? = null + + /** + * Host [newListeners] (the app's live subscriptions) on the background connection with + * [newConfig], save the background ones, and arm the scheduled wake-ups. Saved subscriptions + * from an earlier run stay unless a live subscription on the same filter takes them over + * (with background on or off), or [newConfig] is for another client id (another user), whose + * saved subscriptions are dropped. + * + * With [done], it is called once the connection is up and every filter is subscribed (SUBACK), + * or with the failure, which is then not reported to onError: the caller reports it. + */ + fun host( + context: Context, + newConfig: PushConfig, + newListeners: List, + done: ((Throwable?) -> Unit)? = null, + ) { + val app = context.applicationContext + synchronized(lock) { + load(app) + if (config != null && config?.clientId != newConfig.clientId) { + saved = emptyList() + } + // A live subscription on a saved filter takes it over, whether or not it wants background: + // one that turned background off, or is later unsubscribed, must not leave the saved + // entry delivering in the background. + saved = saved.filter { entry -> newListeners.none { entry.filter in it.topics } } + config = newConfig + listeners.clear() + listeners.addAll(newListeners) + persist(app) + } + activate(app, done) + } + + /** + * Stop hosting the app's live subscriptions, keeping the saved ones from an earlier run. + * Shuts down when none remain. + */ + fun release(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + listeners.clear() + persist(app) + isActive() + } + if (active) { + worker.execute { converge(app, heartbeat = false) } + } else { + shutdown(app) + } + } + + /** Stop background delivery completely and forget every saved subscription. */ + fun stop(context: Context) { + val app = context.applicationContext + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = true + PushStore.clearState(app) + } + shutdown(app) + } + + /** Whether subscriptions saved by an earlier run are still delivered in the background. */ + fun hasSaved(context: Context): Boolean = synchronized(lock) { + load(context.applicationContext) + saved.isNotEmpty() + } + + /** Persist the foreground-mode choice and start or stop the foreground service to match. */ + fun setForeground(context: Context, enabled: Boolean) { + val app = context.applicationContext + PushStore.setForeground(app, enabled) + serviceStartReported = false + ensureService(app) + } + + /** Whether the foreground service should run: foreground mode is enabled and there is work to do. */ + fun wantsService(context: Context): Boolean { + val app = context.applicationContext + return PushStore.foreground(app) && synchronized(lock) { + load(app) + isActive() + } + } + + /** Resume saved background delivery when the app starts, without waiting for the next run. */ + fun resume(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + tick(app) {} + } + } + + /** + * One scheduled run: under a wakelock, reconnect if needed, send a heartbeat when one is due, + * re-arm the next run, and call [done] once finished. Shuts down when nothing is saved. + */ + fun tick(context: Context, done: () -> Unit) { + val app = context.applicationContext + val wakeLock = acquireWakeLock(app) + worker.execute { + try { + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + // Arm the next run first, so a run cut short (killed, or a slow broker outlasting + // the wakelock) still leaves the chain armed. A refused credential in converge() + // shuts down, cancelling it again. + schedule(app, INTERVAL_MS) + ensureService(app) + registerNetworkCallback(app) + converge(app, heartbeat = true) + } else { + shutdown(app) + } + } catch (e: Exception) { + report(e) + } finally { + releaseWakeLock(wakeLock) + done() + } + } + } + + /** Run once more shortly after the task was removed, so an OEM kill that follows is undone. */ + fun scheduleRestart(context: Context) { + schedule(context.applicationContext, RESTART_DELAY_MS, jobToo = false) + } + + /** + * Forget everything held in memory, as the process dying does, keeping only what is saved. + * For tests of what happens after the app's process was killed. + */ + internal fun dropProcessState(context: Context) { + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = false + } + errorHandler = null + unregisterNetworkCallback(context.applicationContext) + worker.submit { disconnect() }.get() + } + + /** Report an error to the hosting Push instance's onError; logged when there is none. */ + fun report(error: Throwable): Boolean { + val delivered = try { + errorHandler?.invoke(error) ?: false + } catch (callbackError: Exception) { + Log.e(LOG_TAG, "Push onError threw", callbackError) + true + } + if (!delivered) { + Log.e(LOG_TAG, "Push background error", error) + } + return delivered + } + + // Must hold [lock]. + private fun load(context: Context) { + if (loaded) { + return + } + loaded = true + val state = PushStore.loadState(context) ?: return + config = state.first + saved = state.second + } + + // Must hold [lock]. + private fun isActive(): Boolean = config != null && (saved.isNotEmpty() || listeners.isNotEmpty()) + + // Must hold [lock]. Every background subscription, live or saved, one per filter and title. + // Subscriptions sharing a filter and title are saved once, with QoS 1 when any of them wants it. + private fun entries(): List = + (saved + listeners.filter { it.background }.flatMap { listener -> listener.topics.map { PushEntry(it, listener.retry, listener.title) } }) + .groupBy { it.filter to it.title } + .map { (key, group) -> PushEntry(key.first, group.any { it.retry }, key.second) } + + // Must hold [lock]. + private fun persist(context: Context) { + val current = config + val entries = entries() + if (current == null || entries.isEmpty()) { + PushStore.clearState(context) + } else { + PushStore.saveState(context, current, entries) + } + } + + // Must hold [lock]. The broker subscriptions wanted, at the highest QoS any subscription on a + // filter asks for. + private fun wanted(): Map { + val qos = linkedMapOf() + fun want(filter: String, retry: Boolean) { + if (retry) { + qos[filter] = MqttQos.AT_LEAST_ONCE + } else if (filter !in qos) { + qos[filter] = MqttQos.AT_MOST_ONCE + } + } + for (listener in listeners) { + listener.topics.forEach { want(it, listener.retry) } + } + saved.forEach { want(it.filter, it.retry) } + return qos + } + + private fun activate(context: Context, done: ((Throwable?) -> Unit)? = null) { + registerNetworkCallback(context) + schedule(context, INTERVAL_MS) + ensureService(context) + worker.execute { converge(context, heartbeat = false, done) } + } + + private fun shutdown(context: Context) { + cancelSchedule(context) + unregisterNetworkCallback(context) + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + worker.execute { disconnect() } + } + + // Worker thread only. Bring the connection to the wanted state: reconnect when the config or + // the default network changed or a due heartbeat fails, then subscribe and unsubscribe the + // difference. With [done], failures go to it (see [waiting]) instead of onError. + private fun converge(context: Context, heartbeat: Boolean, done: ((Throwable?) -> Unit)? = null) { + waiting = done != null + failure = null + try { + convergeOnce(context, heartbeat) + } catch (e: Exception) { + fail(e) + } finally { + waiting = false + done?.invoke(failure) + } + } + + // Worker thread only. Record a failure for the waiting caller, or report it. + private fun fail(error: Throwable) { + if (failure == null) { + failure = error + } + if (!waiting) { + report(error) + } + } + + private fun convergeOnce(context: Context, heartbeat: Boolean) { + val (current, wanted) = synchronized(lock) { config to wanted() } + if (current == null || wanted.isEmpty()) { + disconnect() + return + } + var client = mqtt + if (client != null && (current != connectedConfig || networkChanged(context))) { + disconnect() + client = null + } + if (client != null && heartbeat && SystemClock.elapsedRealtime() - lastHeartbeat >= heartbeatInterval(context)) { + val alive = sendHeartbeat(client) + recordHeartbeat(context, alive) + if (alive) { + lastHeartbeat = SystemClock.elapsedRealtime() + } else { + disconnect() + client = null + } + } + if (client == null) { + client = connect(context, current) ?: return + } + for (filter in subscribed.keys - wanted.keys) { + request { client.unsubscribeWith().topicFilter(filter).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) } + subscribed.remove(filter) + } + for ((filter, qos) in wanted) { + if (subscribed[filter] != qos && subscribe(client, filter, qos)) { + subscribed[filter] = qos + } + } + } + + // Worker thread only. Connect with [config], or report why not and return null. A refused + // credential stops background delivery: retrying it would only be refused again. + private fun connect(context: Context, config: PushConfig): Mqtt5AsyncClient? { + // A failed first connect of a waited-for converge goes to the waiting caller only. + val quiet = waiting + val connected = AtomicBoolean(false) + val client = buildPushClient( + config.copy(keepAlive = KEEP_ALIVE_SECONDS), + onError = { error -> + if (!quiet || connected.get()) { + report(error) + } + }, + onAuthRefused = { error -> worker.execute { refused(context, error) } }, + ) + // Registered before connecting, so the backlog the broker replays right after each + // SUBSCRIBE reaches the app however the subscription was made (including the ones the + // client restores itself after an automatic reconnect). Acknowledged by hand, once the + // message was delivered (see [deliver]). + client.publishes(MqttGlobalPublishFilter.ALL, { publish -> deliver(context, publish) }, true) + try { + client.sendPushConnect(config.copy(keepAlive = KEEP_ALIVE_SECONDS), CONNECT_TIMEOUT_SECONDS) + } catch (e: Exception) { + val cause = (e as? ExecutionException)?.cause ?: e + client.disconnect() + val error = connectError(cause) + when { + isAuthRefusal(cause) -> refused(context, error) + waiting -> fail(error) + // A network failure already reached onError through the client's disconnect + // listener; a refused CONNECT and a timeout did not. + cause is Mqtt5ConnAckException || cause is TimeoutException -> report(error) + } + return null + } + connected.set(true) + mqtt = client + connectedConfig = config + connectedNetwork = activeNetwork(context) + lastHeartbeat = SystemClock.elapsedRealtime() + subscribed.clear() + return client + } + + // Worker thread only. + private fun subscribe(client: Mqtt5AsyncClient, filter: String, qos: MqttQos): Boolean = request { + val subAck = client.subscribeWith().topicFilter(filter).qos(qos).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + val code = subAck.reasonCodes.firstOrNull { it.isError } + if (code != null) { + throw AppwriteException( + subAck.reasonString.map { it.toString() }.orElse("Subscribing to $filter was refused (reason $code)"), + ) + } + } + + // Worker thread only. The current heartbeat interval, back at the default once a shrink is + // old enough. + private fun heartbeatInterval(context: Context): Long { + val state = heartbeatState ?: PushStore.heartbeat(context).also { heartbeatState = it } + if (state.intervalMs < HEARTBEAT_MS && System.currentTimeMillis() - state.shrunkAt >= HEARTBEAT_RESET_MS) { + saveHeartbeat(context, PushHeartbeat(HEARTBEAT_MS)) + return HEARTBEAT_MS + } + return state.intervalMs + } + + // Worker thread only. Count a failed heartbeat (a connection the network dropped silently), + // shrinking the interval after HEARTBEAT_FAILURES in a row; a delivered one ends the streak. + private fun recordHeartbeat(context: Context, alive: Boolean) { + val state = heartbeatState ?: PushStore.heartbeat(context) + val next = when { + alive -> state.copy(failures = 0) + state.failures + 1 < HEARTBEAT_FAILURES -> state.copy(failures = state.failures + 1) + else -> PushHeartbeat(maxOf(MIN_HEARTBEAT_MS, state.intervalMs * 3 / 4), 0, System.currentTimeMillis()) + } + if (next != state) { + saveHeartbeat(context, next) + } + } + + private fun saveHeartbeat(context: Context, state: PushHeartbeat) { + heartbeatState = state + PushStore.setHeartbeat(context, state) + } + + // Worker thread only. + private fun sendHeartbeat(client: Mqtt5AsyncClient): Boolean = try { + client.unsubscribeWith().topicFilter(HEARTBEAT_FILTER).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + true + } catch (e: Exception) { + false + } + + // Run a broker request, recording or reporting its failure. Returns whether it succeeded. + private fun request(block: () -> Unit): Boolean = try { + block() + true + } catch (e: Exception) { + fail((e as? ExecutionException)?.cause ?: e) + false + } + + // Worker thread only. + private fun disconnect() { + mqtt?.disconnect() + mqtt = null + connectedConfig = null + connectedNetwork = null + subscribed.clear() + } + + // Worker thread only. The broker refused the credential: report it and stop. With no onError + // registered the message is also saved, and the next onError registration receives it. A + // waiting caller receives it instead. + private fun refused(context: Context, error: Throwable) { + if (waiting) { + fail(error) + } else if (!report(error)) { + PushStore.setStoppedError(context, error.message ?: "Push connection refused") + } + stop(context) + } + + // Deliver a message, then acknowledge it: right away, or once every listener that acknowledges + // messages itself has done so (at most ACK_TIMEOUT_SECONDS later). + private fun deliver(context: Context, publish: Mqtt5Publish) { + val acknowledged = AtomicBoolean(false) + val acknowledge = { + if (acknowledged.compareAndSet(false, true)) { + runCatching { publish.acknowledge() } + } + } + val pending = AtomicInteger(1) + val settle = { + if (pending.decrementAndGet() == 0) { + acknowledge() + } + } + try { + deliverMessage(context, publish.toPushMessage()) { + pending.incrementAndGet() + val once = AtomicBoolean(false) + val ack: () -> Unit = { + if (once.compareAndSet(false, true)) { + settle() + } + } + ack + } + } finally { + settle() + } + if (!acknowledged.get()) { + worker.schedule({ acknowledge() }, ACK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + } + } + + // Deliver a message to the matching live callbacks; with none, to the declared PushReceiver + // and/or a notification per saved subscription that matches it. [deferAck] hands a listener + // that acknowledges messages itself its acknowledgement. + private fun deliverMessage(context: Context, message: PushMessage, deferAck: () -> () -> Unit) { + val matching = listeners.filter { listener -> listener.topics.any { matchesTopic(it, message.topic) } } + // Saved background subscriptions no live one has taken over; they deliver even when a live + // foreground-only subscription on an overlapping filter received the message too. + val entries = synchronized(lock) { saved }.filter { matchesTopic(it.filter, message.topic) } + if (matching.isEmpty() && entries.isEmpty()) { + return + } + for (listener in matching) { + try { + val acknowledging = listener.acknowledgingCallback + if (acknowledging != null) { + acknowledging(message, deferAck()) + } else { + listener.callback(message) + } + } catch (e: Exception) { + report(e) + } + } + val wakeLock = acquireWakeLock(context) + try { + // The app's PushReceiver gets only messages no live callback received. + val handled = matching.isEmpty() && deliverToReceivers(context, message) + val titles = matching.filter { it.background }.map { it.title ?: message.topic } + + if (handled) emptyList() else entries.map { it.title ?: message.topic } + titles.distinct().forEach { notify(context, message, it) } + } finally { + releaseWakeLock(wakeLock) + } + } + + // Call every PushReceiver the app declares. Returns whether one handled the message. + private fun deliverToReceivers(context: Context, message: PushMessage): Boolean { + val intent = Intent(ACTION_MESSAGE).setPackage(context.packageName) + val receivers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.queryBroadcastReceivers(intent, PackageManager.ResolveInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + context.packageManager.queryBroadcastReceivers(intent, 0) + } + var handled = false + for (info in receivers) { + val name = info.activityInfo?.name ?: continue + try { + val receiver = Class.forName(name, true, context.classLoader).getDeclaredConstructor().newInstance() + if (receiver is PushReceiver && receiver.onMessage(context, message)) { + handled = true + } + } catch (e: Exception) { + report(e) + } + } + return handled + } + + /** Post a notification for [message] that opens the app, with the message in its extras. */ + fun notify(context: Context, message: PushMessage, title: String) { + val manager = NotificationManagerCompat.from(context) + if (!manager.areNotificationsEnabled()) { + return + } + createChannels(context) + val id = 31 * message.hashCode() + title.hashCode() + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setContentTitle(title) + .setContentText(message.data) + .setSmallIcon(notificationIcon(context)) + .setAutoCancel(true) + context.packageManager.getLaunchIntentForPackage(context.packageName)?.let { launch -> + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(EXTRA_TOPIC, message.topic) + .putExtra(EXTRA_PAYLOAD, message.data) + builder.setContentIntent( + PendingIntent.getActivity(context, id, launch, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE), + ) + } + try { + manager.notify(id, builder.build()) + } catch (e: SecurityException) { + // POST_NOTIFICATIONS not granted; nothing to show. + } + } + + /** The ongoing notification the foreground service shows, on its own quiet channel. */ + fun ongoingNotification(context: Context) = NotificationCompat.Builder(context, SERVICE_CHANNEL_ID) + .also { createChannels(context) } + .setContentTitle(ongoingTitle) + .setContentText("Listening for messages") + .setSmallIcon(notificationIcon(context)) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOngoing(true) + .build() + + private fun createChannels(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return + } + val manager = context.getSystemService(NotificationManager::class.java) ?: return + manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH)) + manager.createNotificationChannel( + NotificationChannel(SERVICE_CHANNEL_ID, "Background connection", NotificationManager.IMPORTANCE_LOW), + ) + } + + // The icon named by the app's ``, else a + // generic one. + private fun notificationIcon(context: Context): Int { + val metaData = runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.getApplicationInfo(context.packageName, PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong())) + } else { + @Suppress("DEPRECATION") + context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) + }.metaData + }.getOrNull() + return metaData?.getInt(NOTIFICATION_ICON, 0)?.takeIf { it != 0 } ?: android.R.drawable.stat_notify_chat + } + + private fun ensureService(context: Context) { + if (!wantsService(context)) { + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + return + } + if (serviceRunning) { + return + } + try { + ContextCompat.startForegroundService(context, Intent(context, PushService::class.java)) + } catch (e: Exception) { + // Android 12+ refuses a foreground-service start from the background; the scheduled + // runs keep delivering, and the next start from the foreground succeeds. + if (!serviceStartReported) { + serviceStartReported = true + report(e) + } + } + } + + // Arm the next run in [delayMs]: the job, and an alarm just after it in case the job is late. + private fun schedule(context: Context, delayMs: Long, jobToo: Boolean = true) { + val interval = if (delayMs == INTERVAL_MS && privileged(context)) PRIVILEGED_INTERVAL_MS else delayMs + if (jobToo) { + try { + val job = JobInfo.Builder(JOB_ID, ComponentName(context, PushJobService::class.java)) + .setMinimumLatency(interval) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) + .setPersisted(true) + .build() + context.getSystemService(JobScheduler::class.java)?.schedule(job) + } catch (e: Exception) { + report(e) + } + } + val alarms = context.getSystemService(AlarmManager::class.java) ?: return + val at = SystemClock.elapsedRealtime() + interval + 1_000L + val intent = tickIntent(context) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarms.canScheduleExactAlarms()) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } else { + alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } catch (e: SecurityException) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } + + private fun cancelSchedule(context: Context) { + context.getSystemService(JobScheduler::class.java)?.cancel(JOB_ID) + context.getSystemService(AlarmManager::class.java)?.cancel(tickIntent(context)) + } + + private fun tickIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( + context, + 0, + Intent(context, PushAlarmReceiver::class.java).setAction(ACTION_TICK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + // Allowed exact alarms or exempt from battery optimisation: the alarm is reliable, so the + // runs can be spaced further apart. + private fun privileged(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.S || + context.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true || + context.getSystemService(PowerManager::class.java)?.isIgnoringBatteryOptimizations(context.packageName) == true + + private fun activeNetwork(context: Context): Network? = + runCatching { context.getSystemService(ConnectivityManager::class.java)?.activeNetwork }.getOrNull() + + private fun networkChanged(context: Context): Boolean { + val now = activeNetwork(context) + return now != null && connectedNetwork != null && now != connectedNetwork + } + + // Reconnect as soon as the default network changes (e.g. from cellular to Wi-Fi) while the + // process is alive, instead of waiting for the next run to notice. + private fun registerNetworkCallback(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + return + } + synchronized(lock) { + if (networkCallback != null) { + return + } + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + worker.execute { + if (mqtt != null && network != connectedNetwork) { + converge(context, heartbeat = false) + } + } + } + } + try { + context.getSystemService(ConnectivityManager::class.java)?.registerDefaultNetworkCallback(callback) + networkCallback = callback + } catch (e: Exception) { + report(e) + } + } + } + + private fun unregisterNetworkCallback(context: Context) { + val callback = synchronized(lock) { networkCallback.also { networkCallback = null } } ?: return + runCatching { context.getSystemService(ConnectivityManager::class.java)?.unregisterNetworkCallback(callback) } + } + + private fun acquireWakeLock(context: Context): PowerManager.WakeLock? = runCatching { + context.getSystemService(PowerManager::class.java) + ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Appwrite:push") + ?.apply { + setReferenceCounted(false) + acquire(WAKE_LOCK_MS) + } + }.getOrNull() + + private fun releaseWakeLock(wakeLock: PowerManager.WakeLock?) { + runCatching { + if (wakeLock?.isHeld == true) { + wakeLock.release() + } + } + } +} + +/** + * Background push state in the app's no-backup directory, so a restored backup on another + * device never carries this install's id or credential: the saved subscriptions with their + * connection config (cleared when background delivery stops), and the settings that outlive + * it (the install id, the foreground-mode choice, a refusal waiting for onError). + */ +internal object PushStore { + private const val STATE_FILE = "appwrite_push_state.json" + private const val SETTINGS_FILE = "appwrite_push_settings.json" + + fun loadState(context: Context): Pair>? = synchronized(this) { + val json = read(context, STATE_FILE) ?: return null + runCatching { + val config = json.getJSONObject("config").let { + PushConfig( + host = it.getString("host"), + port = it.getInt("port"), + tls = it.getBoolean("tls"), + tlsInsecure = it.getBoolean("tlsInsecure"), + clientId = it.getString("clientId"), + keepAlive = it.getInt("keepAlive"), + authMethod = it.getString("authMethod"), + credential = it.getString("credential"), + project = it.getString("project"), + ) + } + val list = json.getJSONArray("entries") + val entries = (0 until list.length()).map { index -> + val entry = list.getJSONObject(index) + PushEntry( + filter = entry.getString("filter"), + retry = entry.getBoolean("retry"), + title = if (entry.isNull("title")) null else entry.getString("title"), + ) + } + config to entries + }.getOrNull() + } + + fun saveState(context: Context, config: PushConfig, entries: List) = synchronized(this) { + val json = JSONObject() + .put( + "config", + JSONObject() + .put("host", config.host) + .put("port", config.port) + .put("tls", config.tls) + .put("tlsInsecure", config.tlsInsecure) + .put("clientId", config.clientId) + .put("keepAlive", config.keepAlive) + .put("authMethod", config.authMethod) + .put("credential", config.credential) + .put("project", config.project), + ) + .put( + "entries", + JSONArray(entries.map { JSONObject().put("filter", it.filter).put("retry", it.retry).put("title", it.title ?: JSONObject.NULL) }), + ) + write(context, STATE_FILE, json) + } + + fun clearState(context: Context) = synchronized(this) { + file(context, STATE_FILE).delete() + } + + /** A random id for this install, created once, which keeps the broker's replay position. */ + fun installId(context: Context): String = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: JSONObject() + settings.optString("installId").ifEmpty { + val id = UUID.randomUUID().toString() + write(context, SETTINGS_FILE, settings.put("installId", id)) + id + } + } + + fun foreground(context: Context): Boolean = synchronized(this) { + read(context, SETTINGS_FILE)?.optBoolean("foreground", false) ?: false + } + + fun setForeground(context: Context, enabled: Boolean) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("foreground", enabled)) + } + + /** The saved adaptive heartbeat; the default interval until one was saved. */ + fun heartbeat(context: Context): PushHeartbeat = synchronized(this) { + val json = read(context, SETTINGS_FILE)?.optJSONObject("heartbeat") ?: return PushHeartbeat(PushBackground.HEARTBEAT_MS) + PushHeartbeat( + intervalMs = json.optLong("intervalMs", PushBackground.HEARTBEAT_MS), + failures = json.optInt("failures", 0), + shrunkAt = json.optLong("shrunkAt", 0L), + ) + } + + fun setHeartbeat(context: Context, state: PushHeartbeat) = synchronized(this) { + val heartbeat = JSONObject() + .put("intervalMs", state.intervalMs) + .put("failures", state.failures) + .put("shrunkAt", state.shrunkAt) + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("heartbeat", heartbeat)) + } + + fun setStoppedError(context: Context, message: String) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("stoppedError", message)) + } + + /** The refusal that stopped background delivery while no onError was registered, once. */ + fun takeStoppedError(context: Context): String? = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: return null + val message = settings.optString("stoppedError").ifEmpty { return null } + settings.remove("stoppedError") + write(context, SETTINGS_FILE, settings) + message + } + + private fun file(context: Context, name: String) = AtomicFile(File(context.noBackupFilesDir, name)) + + private fun read(context: Context, name: String): JSONObject? = + runCatching { JSONObject(String(file(context, name).readFully(), Charsets.UTF_8)) }.getOrNull() + + private fun write(context: Context, name: String, json: JSONObject) { + val file = file(context, name) + val out = try { + file.startWrite() + } catch (e: IOException) { + Log.e(LOG_TAG, "Could not save push state", e) + return + } + try { + out.write(json.toString().toByteArray(Charsets.UTF_8)) + file.finishWrite(out) + } catch (e: IOException) { + file.failWrite(out) + Log.e(LOG_TAG, "Could not save push state", e) + } + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBridge.kt b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt new file mode 100644 index 00000000..d7b79b5d --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt @@ -0,0 +1,135 @@ +package io.appwrite.services + +import android.content.Context +import android.os.SystemClock +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** + * The contract the React Native and Flutter SDKs use to host their background push + * subscriptions on this Android core, so they get the same delivery as the Android SDK: saved + * subscriptions, scheduled wake-ups after the process dies, notifications, and foreground mode. + * + * Both SDKs pass the same JSON: [host] takes the connection config and every live subscription, + * and each message for a live subscription comes back through [Events.onMessage] with its id and + * an acknowledgement token, which the SDK passes to [ack] once its callback has run (the broker's + * PUBACK waits for it, at most ten seconds). One bridge per process; hosting again replaces the + * live subscriptions. + */ +class PushBridge(context: Context, private val events: Events) { + /** Where messages and errors go; called on a background thread. */ + interface Events { + fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) + + fun onError(message: String) + } + + private val appContext = context.applicationContext + // Acknowledgement token -> (when it was handed out, the acknowledgement). A token the SDK never + // acknowledges (its JS or Dart side was gone) is dropped once the core has acknowledged the + // message anyway, so the map stays bounded. + private val acks = ConcurrentHashMap Unit>>() + + // Whether the app registered onError; without one, errors are logged and a refused + // credential is kept for the next registration. + @Volatile + private var errorCallback = false + + /** + * Host the subscriptions in [subscriptionsJson] on the background connection described by + * [configJson]. + * + * Config: `{"host", "port", "tls", "tlsInsecure", "clientId" (optional; per user and install + * when empty), "authMethod", "credential", "project"}`. Subscriptions: an array of + * `{"id", "topic", "background", "title" (optional), "retry"}`. + * + * [done] is called once the connection is up and every filter is subscribed, or with the + * failure's message; the SDK rejects its subscribe with it and reports it itself. + */ + fun host(configJson: String, subscriptionsJson: String, done: (String?) -> Unit) { + val json = JSONObject(configJson) + val authMethod = json.getString("authMethod") + val credential = json.getString("credential") + val config = PushConfig( + host = json.getString("host"), + port = json.getInt("port"), + tls = json.optBoolean("tls", false), + tlsInsecure = json.optBoolean("tlsInsecure", false), + clientId = json.optString("clientId").ifEmpty { defaultPushClientId(appContext, authMethod, credential) }, + keepAlive = KEEP_ALIVE_SECONDS, + authMethod = authMethod, + credential = credential, + project = json.optString("project"), + ) + val list = JSONArray(subscriptionsJson) + val listeners = (0 until list.length()).map { index -> + val subscription = list.getJSONObject(index) + val id = subscription.getString("id") + PushListener( + topics = setOf(subscription.getString("topic")), + callback = {}, + acknowledgingCallback = { message, ack -> + val token = UUID.randomUUID().toString() + val now = SystemClock.elapsedRealtime() + acks.entries.removeIf { now - it.value.first > STALE_ACK_MS } + acks[token] = now to ack + events.onMessage(id, message, token) + }, + background = subscription.optBoolean("background", false), + title = if (subscription.isNull("title")) null else subscription.optString("title").ifEmpty { null }, + retry = subscription.optBoolean("retry", true), + ) + } + PushBackground.errorHandler = { error -> + if (errorCallback) { + events.onError(error.message ?: error.toString()) + } + errorCallback + } + PushBackground.host(appContext, config, listeners) { error -> + done(error?.let { it.message ?: it.toString() }) + } + } + + /** Acknowledge a message once the SDK's callback for it has run. */ + fun ack(token: String) { + acks.remove(token)?.second?.invoke() + } + + /** Stop hosting the live subscriptions, keeping the ones saved by an earlier run. */ + fun release() = PushBackground.release(appContext) + + /** Stop background delivery and forget every saved subscription (sign-out). */ + fun stop() = PushBackground.stop(appContext) + + /** Run background delivery in a foreground service; saved across restarts. */ + fun setForeground(enabled: Boolean) = PushBackground.setForeground(appContext, enabled) + + /** Whether an earlier run saved background subscriptions that are still delivered. */ + fun hasSaved(): Boolean = PushBackground.hasSaved(appContext) + + /** Resume saved background delivery now instead of at the next scheduled run. */ + fun resume() = PushBackground.resume(appContext) + + /** + * Record whether the app has an onError callback. Returns the refusal that stopped background + * delivery while it had none, once, so the app can deliver it now. + */ + fun setErrorCallback(registered: Boolean): String? { + errorCallback = registered + return if (registered) PushStore.takeStoppedError(appContext) else null + } + + /** The default client id for a credential, so a foreground connection shares its session. */ + fun defaultClientId(authMethod: String, credential: String): String = + defaultPushClientId(appContext, authMethod, credential) + + private companion object { + const val KEEP_ALIVE_SECONDS = 60 + + // Past the core's ten-second acknowledgement cap, after which the message was acknowledged. + const val STALE_ACK_MS = 30_000L + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushCore.kt b/android/src/main/kotlin/io/appwrite/services/PushCore.kt new file mode 100644 index 00000000..20c56242 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushCore.kt @@ -0,0 +1,374 @@ +package io.appwrite.services + +import android.content.Context +import android.os.Build +import android.util.Base64 +import com.hivemq.client.mqtt.MqttClient +import com.hivemq.client.mqtt.datatypes.MqttUtf8String +import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext +import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientConfig +import com.hivemq.client.mqtt.mqtt5.auth.Mqtt5EnhancedAuthMechanism +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5DisconnectException +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5Auth +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5AuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5EnhancedAuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAckReasonCode +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5DisconnectReasonCode +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONObject +import java.security.KeyStore +import java.security.Provider +import java.security.cert.X509Certificate +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ExecutionException +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import javax.net.ssl.ManagerFactoryParameters +import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.TrustManagerFactorySpi +import javax.net.ssl.X509TrustManager + +/** + * A message delivered on a subscribed topic — the MQTT push analog of a realtime event. + */ +data class PushMessage( + val topic: String, + val payload: ByteArray, + val qos: Int, +) { + /** The payload decoded as UTF-8 text, as it was sent. */ + val data: String + get() = String(payload, Charsets.UTF_8) +} + +/** Connection parameters shared between the in-process client and the foreground service. */ +internal data class PushConfig( + val host: String, + val port: Int, + val tls: Boolean, + val tlsInsecure: Boolean, + val clientId: String, + val keepAlive: Int, + val authMethod: String, + val credential: String, + val project: String, +) + +/** + * The userId claim from an Appwrite JWT, used as the default MQTT client id so the + * broker's replay cursor is stable per user. Returns "" when the token is not a decodable JWT + * (e.g. a session secret), so the caller can fall back to the raw credential. + */ +internal fun userIdFromJwt(jwt: String): String { + val parts = jwt.split('.') + if (parts.size < 2) { + return "" + } + return runCatching { + val json = String( + Base64.decode(parts[1], Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING), + Charsets.UTF_8, + ) + JSONObject(json).optString("userId", "") + }.getOrDefault("") +} + +/** The user `id` from an Appwrite session secret, or "" when it is not decodable. */ +internal fun userIdFromSession(session: String): String = runCatching { + val json = String(Base64.decode(session, Base64.DEFAULT), Charsets.UTF_8) + JSONObject(json).optString("id", "") +}.getOrDefault("") + +/** + * The default MQTT client id: one per user and install (`-`, or the install id + * alone when the credential names no user). The broker keeps the replay position per user and + * client id, so each device resumes its own backlog across restarts, and two devices of one user + * do not take over each other's session. + */ +internal fun defaultPushClientId(context: Context, authMethod: String, credential: String): String { + val userId = if (authMethod == "appwrite-session") userIdFromSession(credential) else userIdFromJwt(credential) + val installId = PushStore.installId(context) + return if (userId.isEmpty()) installId else "$userId-$installId" +} + +/** + * Build (but do not connect) an MQTT 5 client from [config]. [onError] receives every connection + * error (a lost connection, a failed automatic reconnect, a broker DISCONNECT) except a refused + * initial CONNECT, which [pushConnect] throws instead. + */ +internal fun buildPushClient( + config: PushConfig, + onConnected: (() -> Unit)? = null, + onDisconnected: (() -> Unit)? = null, + onError: ((Throwable) -> Unit)? = null, + onAuthRefused: ((Throwable) -> Unit)? = null, +): Mqtt5AsyncClient { + // config.clientId is stable per user (see buildConfig), so a reconnect rebuild reuses it + // and resumes the same session. + var builder = MqttClient.builder() + .useMqttVersion5() + .serverHost(config.host) + .serverPort(config.port) + // Recover from an unexpected disconnect (network drop, broker restart) with HiveMQ's + // exponential backoff. A user-initiated disconnect() (see close()) does not trigger it. + // Because clean start is off and the broker resumes the same session, subscriptions and + // the QoS-1 replay cursor persist, so delivery continues without resubscribing (which + // would stack a second per-subscription callback). + .automaticReconnectWithDefaultConfig() + + if (config.clientId.isNotEmpty()) { + builder = builder.identifier(config.clientId) + } + + // Whether this client has connected yet: until it has, a refused CONNECT is final. + val connected = AtomicBoolean(false) + builder = builder.addConnectedListener { + connected.set(true) + onConnected?.invoke() + } + builder = builder.addDisconnectedListener { context -> + // A refused first CONNECT (bad credential, rate limit) is final: stop the automatic + // reconnect so pushConnect fails with the broker's reason instead of retrying forever. + val refused = !connected.get() && context.cause is Mqtt5ConnAckException + // With [onAuthRefused], a credential refused later (a failed automatic reconnect or + // re-auth) is final too, instead of being retried with the same credential forever. + val authRefused = onAuthRefused != null && connected.get() && + context.source != MqttDisconnectSource.USER && isAuthRefusal(context.cause) + if (refused || authRefused) { + context.reconnector.reconnect(false) + } + onDisconnected?.invoke() + if (!refused) { + val error = pushDisconnectError(context) + if (authRefused && error != null) { + // Reported by onAuthRefused, which also stops for good. + onAuthRefused?.invoke(error) + } else { + error?.let { onError?.invoke(it) } + } + } + } + + if (config.tls) { + builder = if (config.tlsInsecure) { + builder.sslConfig() + .trustManagerFactory(PushInsecureTrustManagerFactory) + .hostnameVerifier { _, _ -> true } + .applySslConfig() + } else { + builder.sslWithDefaultConfig() + } + } + + return builder.buildAsync() +} + +/** + * Connect with Appwrite enhanced auth; blocks until CONNACK. Throws an + * [AppwriteException] on failure, whose message is the broker's MQTT 5 + * Reason String when it refused the CONNECT with one. + */ +internal fun Mqtt5AsyncClient.pushConnect(config: PushConfig) { + try { + sendPushConnect(config) + } catch (e: Exception) { + throw connectError((e as? ExecutionException)?.cause ?: e) + } +} + +/** The error a failed CONNECT reports: the broker's Reason String when it refused one. */ +internal fun connectError(cause: Throwable): AppwriteException = + if (cause is Mqtt5ConnAckException) { + connAckError(cause) + } else { + AppwriteException(cause.message ?: "MQTT connection failed") + } + +/** + * Whether [error] is the broker refusing the credential (a CONNECT or re-auth), which retrying + * with the same credential cannot fix, unlike a rate limit or a network failure. + */ +internal fun isAuthRefusal(error: Throwable?): Boolean = when (error) { + is Mqtt5ConnAckException -> error.mqttMessage.reasonCode in setOf( + Mqtt5ConnAckReasonCode.NOT_AUTHORIZED, + Mqtt5ConnAckReasonCode.BAD_USER_NAME_OR_PASSWORD, + Mqtt5ConnAckReasonCode.BAD_AUTHENTICATION_METHOD, + Mqtt5ConnAckReasonCode.BANNED, + ) + is Mqtt5DisconnectException -> error.mqttMessage.reasonCode == Mqtt5DisconnectReasonCode.NOT_AUTHORIZED + else -> false +} + +/** Send the CONNECT and wait for the CONNACK, at most [timeoutSeconds] when given. */ +internal fun Mqtt5AsyncClient.sendPushConnect(config: PushConfig, timeoutSeconds: Long? = null) { + val connAck = connectWith() + .enhancedAuth(PushAuthMechanism(config.authMethod, config.credential)) + // Clean start is always off, so the broker keeps this client's session and can + // redeliver missed messages to QoS-1 subscriptions on reconnect. + .cleanStart(false) + .keepAlive(config.keepAlive) + .userProperties() + .add("projectId", config.project) + .applyUserProperties() + .send() + if (timeoutSeconds == null) { + connAck.get() + } else { + connAck.get(timeoutSeconds, TimeUnit.SECONDS) + } +} + +/** + * The error a lost connection reports, or null when it is not an error (a disconnect the app + * asked for, or a broker DISCONNECT with a success reason code). The broker explains a refused + * CONNECT or a DISCONNECT it sends with an MQTT 5 Reason String, which becomes the message. + */ +internal fun pushDisconnectError(context: MqttClientDisconnectedContext): Throwable? { + val cause = context.cause + return when { + context.source == MqttDisconnectSource.USER -> null + cause is Mqtt5ConnAckException -> connAckError(cause) + cause is Mqtt5DisconnectException && context.source == MqttDisconnectSource.SERVER -> { + val disconnect = cause.mqttMessage + if (disconnect.reasonCode.isError) { + AppwriteException( + disconnect.reasonString.map { it.toString() } + .orElse("Disconnected by the broker (reason ${disconnect.reasonCode})"), + ) + } else { + null + } + } + else -> cause + } +} + +/** A refused CONNECT, with the CONNACK Reason String as its message when the broker sent one. */ +internal fun connAckError(e: Mqtt5ConnAckException): AppwriteException = + AppwriteException( + e.mqttMessage.reasonString.map { it.toString() }.orElse(e.message ?: "MQTT connection refused"), + ) + +internal fun Mqtt5Publish.toPushMessage(): PushMessage = + PushMessage( + topic = topic.toString(), + payload = payloadAsBytes, + qos = qos.code, + ) + +/** + * Single-step MQTT 5 enhanced auth: the method and credential are placed in the CONNECT + * packet and the broker accepts them in the CONNACK, with no AUTH round-trip. + */ +internal class PushAuthMechanism( + private val method: String, + private val credential: String, +) : Mqtt5EnhancedAuthMechanism { + + override fun getMethod(): MqttUtf8String = MqttUtf8String.of(method) + + override fun getTimeout(): Int = 30 + + override fun onAuth( + clientConfig: Mqtt5ClientConfig, + connect: Mqtt5Connect, + authBuilder: Mqtt5EnhancedAuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onReAuth( + clientConfig: Mqtt5ClientConfig, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onContinue( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthSuccess( + clientConfig: Mqtt5ClientConfig, + connAck: Mqtt5ConnAck, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onReAuthSuccess( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthRejected(clientConfig: Mqtt5ClientConfig, connAck: Mqtt5ConnAck) = Unit + + override fun onReAuthRejected(clientConfig: Mqtt5ClientConfig, disconnect: Mqtt5Disconnect) = Unit + + override fun onAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit + + override fun onReAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit +} + +/** + * A [TrustManagerFactory] that accepts any certificate — used when `tlsInsecure` is set + * (for a broker whose certificate does not chain to a public root). + */ +internal object PushInsecureTrustManagerFactory : TrustManagerFactory( + object : TrustManagerFactorySpi() { + override fun engineInit(keyStore: KeyStore?) = Unit + + override fun engineInit(parameters: ManagerFactoryParameters?) = Unit + + override fun engineGetTrustManagers(): Array = arrayOf( + object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + + override fun getAcceptedIssuers(): Array = emptyArray() + }, + ) + }, + @Suppress("DEPRECATION") object : Provider("AppwriteInsecure", 1.0, "insecure trust-all") {}, + "AppwriteInsecure", +) + +/** A live in-app subscription hosted in the background: its topics, callback, notification opt-in and QoS. */ +internal class PushListener( + val topics: Set, + val callback: (PushMessage) -> Unit, + val background: Boolean, + val title: String?, + val retry: Boolean, + // Called instead of [callback] when set, with the acknowledgement to run once the message was + // handled: the React Native and Flutter bridges acknowledge after their callback has run. + val acknowledgingCallback: ((PushMessage, () -> Unit) -> Unit)? = null, +) + +/** MQTT topic-filter match with '+' (single level) and '#' (multi level). */ +internal fun matchesTopic(filter: String, topic: String): Boolean { + val filterParts = filter.split('/') + val topicParts = topic.split('/') + for (i in filterParts.indices) { + if (filterParts[i] == "#") { + return true + } + if (i >= topicParts.size) { + return false + } + if (filterParts[i] != "+" && filterParts[i] != topicParts[i]) { + return false + } + } + return filterParts.size == topicParts.size +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt new file mode 100644 index 00000000..92d04727 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt @@ -0,0 +1,33 @@ +package io.appwrite.services + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * Handles background push messages in code when no in-app callback is listening, e.g. after + * the process was started in the background to reconnect. Subclass it and declare it in your + * manifest with the push message action: + * + * ```xml + * + * + * + * + * + * ``` + * + * The SDK calls [onMessage] directly on a background thread, under a wakelock of about ten + * seconds, so hand longer work to WorkManager. Messages a live callback receives do not + * reach it. + */ +abstract class PushReceiver : BroadcastReceiver() { + /** + * Handle [message]. Return true when you handled it yourself, so the SDK does not post its + * default notification; return false to have it posted as well. + */ + abstract fun onMessage(context: Context, message: PushMessage): Boolean + + // Messages arrive through onMessage, never as a broadcast. + final override fun onReceive(context: Context, intent: Intent) = Unit +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushService.kt b/android/src/main/kotlin/io/appwrite/services/PushService.kt new file mode 100644 index 00000000..e2a05f89 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushService.kt @@ -0,0 +1,67 @@ +package io.appwrite.services + +import android.app.Service +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.ServiceCompat + +/** + * The foreground mode of background push delivery ([Push.setForeground]): a foreground service + * that keeps the process at foreground priority, so the connection held by the process stays + * up and delivers immediately, also during Doze. The system restarts it after a kill, and it + * restores the saved subscriptions. Started by the SDK; not meant to be started directly. + */ +class PushService : Service() { + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + PushBackground.serviceRunning = true + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (!PushBackground.wantsService(this)) { + stopSelf() + return START_NOT_STICKY + } + try { + startForegroundCompat() + } catch (e: Exception) { + // E.g. a background start refused on Android 12+; the scheduled runs keep delivering. + stopSelf() + PushBackground.report(e) + return START_NOT_STICKY + } + PushBackground.tick(this) {} + // Recreated after a kill with a null intent; the saved subscriptions are restored then. + return START_STICKY + } + + private fun startForegroundCompat() { + val notification = PushBackground.ongoingNotification(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceCompat.startForeground( + this, + PushBackground.NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING, + ) + } else { + startForeground(PushBackground.NOTIFICATION_ID, notification) + } + } + + // Some devices kill the process shortly after its task is swiped away; a run a few seconds + // later restarts the service. + override fun onTaskRemoved(rootIntent: Intent?) { + PushBackground.scheduleRestart(this) + super.onTaskRemoved(rootIntent) + } + + override fun onDestroy() { + PushBackground.serviceRunning = false + super.onDestroy() + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt new file mode 100644 index 00000000..091fd528 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt @@ -0,0 +1,46 @@ +package io.appwrite.services + +import android.app.job.JobParameters +import android.app.job.JobService +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * The scheduled run of background push delivery: reconnects and re-arms itself. Scheduled + * by the SDK; not meant to be started directly. + */ +class PushJobService : JobService() { + override fun onStartJob(params: JobParameters): Boolean { + PushBackground.tick(this) { jobFinished(params, false) } + return true + } + + // The run re-arms the next one itself, so a stopped run needs no retry. + override fun onStopJob(params: JobParameters): Boolean = false +} + +/** + * The alarm that backs up the scheduled job when it runs late. Scheduled by the SDK; not meant + * to be sent directly. + */ +class PushAlarmReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != PushBackground.ACTION_TICK) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} + +/** Resumes background push delivery after a reboot or an app update. */ +class PushBootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index d444996d..c27fb328 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -10,5 +10,6 @@ Account account = Account(client); Session result = await account.createEmailPasswordSession( email: 'email@example.com', password: 'password', + duration: 60, // optional ); ``` diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index e8e8ba1a..388661a9 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -7,5 +7,7 @@ Client client = Client() Account account = Account(client); -await account.deleteSessions(); +await account.deleteSessions( + current: false, // optional +); ``` diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 18db93bb..3b148a7b 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -7,5 +7,7 @@ Client client = Client() Account account = Account(client); -SessionList result = await account.listSessions(); +SessionList result = await account.listSessions( + total: false, // optional +); ``` diff --git a/docs/examples/apps/create-installation-token.md b/docs/examples/apps/create-installation-token.md new file mode 100644 index 00000000..868044ba --- /dev/null +++ b/docs/examples/apps/create-installation-token.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +Oauth2Token result = await apps.createInstallationToken( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/create-key.md b/docs/examples/apps/create-key.md new file mode 100644 index 00000000..b22a1bd6 --- /dev/null +++ b/docs/examples/apps/create-key.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppKey result = await apps.createKey( + appId: '', +); +``` diff --git a/docs/examples/apps/create-secret.md b/docs/examples/apps/create-secret.md new file mode 100644 index 00000000..654f1eb5 --- /dev/null +++ b/docs/examples/apps/create-secret.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppSecretPlaintext result = await apps.createSecret( + appId: '', +); +``` diff --git a/docs/examples/apps/create.md b/docs/examples/apps/create.md new file mode 100644 index 00000000..77bd1430 --- /dev/null +++ b/docs/examples/apps/create.md @@ -0,0 +1,31 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +App result = await apps.create( + appId: '', + name: '', + redirectUris: [], + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + postLogoutRedirectUris: [], // optional + enabled: false, // optional + type: 'public', // optional + deviceFlow: false, // optional + teamId: '', // optional +); +``` diff --git a/docs/examples/apps/delete-installation.md b/docs/examples/apps/delete-installation.md new file mode 100644 index 00000000..55707ce0 --- /dev/null +++ b/docs/examples/apps/delete-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/delete-key.md b/docs/examples/apps/delete-key.md new file mode 100644 index 00000000..e6bd4065 --- /dev/null +++ b/docs/examples/apps/delete-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/delete-secret.md b/docs/examples/apps/delete-secret.md new file mode 100644 index 00000000..0e7a1506 --- /dev/null +++ b/docs/examples/apps/delete-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/delete-tokens.md b/docs/examples/apps/delete-tokens.md new file mode 100644 index 00000000..cdba07ee --- /dev/null +++ b/docs/examples/apps/delete-tokens.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteTokens( + appId: '', +); +``` diff --git a/docs/examples/apps/delete.md b/docs/examples/apps/delete.md new file mode 100644 index 00000000..e56502a6 --- /dev/null +++ b/docs/examples/apps/delete.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.delete( + appId: '', +); +``` diff --git a/docs/examples/apps/get-installation.md b/docs/examples/apps/get-installation.md new file mode 100644 index 00000000..e3364ae8 --- /dev/null +++ b/docs/examples/apps/get-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppInstallation result = await apps.getInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/get-key.md b/docs/examples/apps/get-key.md new file mode 100644 index 00000000..3e0a7979 --- /dev/null +++ b/docs/examples/apps/get-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppKey result = await apps.getKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/get-secret.md b/docs/examples/apps/get-secret.md new file mode 100644 index 00000000..63d047aa --- /dev/null +++ b/docs/examples/apps/get-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppSecret result = await apps.getSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/get.md b/docs/examples/apps/get.md new file mode 100644 index 00000000..be860f32 --- /dev/null +++ b/docs/examples/apps/get.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +App result = await apps.get( + appId: '', +); +``` diff --git a/docs/examples/apps/list-installation-scopes.md b/docs/examples/apps/list-installation-scopes.md new file mode 100644 index 00000000..de20ba96 --- /dev/null +++ b/docs/examples/apps/list-installation-scopes.md @@ -0,0 +1,11 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppScopeList result = await apps.listInstallationScopes(); +``` diff --git a/docs/examples/apps/list-installations.md b/docs/examples/apps/list-installations.md new file mode 100644 index 00000000..940de5d3 --- /dev/null +++ b/docs/examples/apps/list-installations.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppInstallationList result = await apps.listInstallations( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-keys.md b/docs/examples/apps/list-keys.md new file mode 100644 index 00000000..237d1487 --- /dev/null +++ b/docs/examples/apps/list-keys.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppKeyList result = await apps.listKeys( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-o-auth-2-scopes.md b/docs/examples/apps/list-o-auth-2-scopes.md new file mode 100644 index 00000000..2ef099df --- /dev/null +++ b/docs/examples/apps/list-o-auth-2-scopes.md @@ -0,0 +1,11 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppScopeList result = await apps.listOAuth2Scopes(); +``` diff --git a/docs/examples/apps/list-secrets.md b/docs/examples/apps/list-secrets.md new file mode 100644 index 00000000..244ed432 --- /dev/null +++ b/docs/examples/apps/list-secrets.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppSecretList result = await apps.listSecrets( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list.md b/docs/examples/apps/list.md new file mode 100644 index 00000000..78f88ba1 --- /dev/null +++ b/docs/examples/apps/list.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +AppsList result = await apps.list( + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/update-team.md b/docs/examples/apps/update-team.md new file mode 100644 index 00000000..6e70778c --- /dev/null +++ b/docs/examples/apps/update-team.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +App result = await apps.updateTeam( + appId: '', + teamId: '', +); +``` diff --git a/docs/examples/apps/update.md b/docs/examples/apps/update.md new file mode 100644 index 00000000..08ee2218 --- /dev/null +++ b/docs/examples/apps/update.md @@ -0,0 +1,32 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +App result = await apps.update( + appId: '', + name: '', + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + enabled: false, // optional + redirectUris: [], // optional + postLogoutRedirectUris: [], // optional + type: 'public', // optional + deviceFlow: false, // optional + installationScopes: [], // optional + installationRedirectUrl: 'https://example.com', // optional +); +``` diff --git a/docs/examples/avatars/delete-photo.md b/docs/examples/avatars/delete-photo.md new file mode 100644 index 00000000..390a3192 --- /dev/null +++ b/docs/examples/avatars/delete-photo.md @@ -0,0 +1,11 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +await avatars.deletePhoto(); +``` diff --git a/docs/examples/avatars/get-screenshot.md b/docs/examples/avatars/get-screenshot.md index daa38d17..1a22a692 100644 --- a/docs/examples/avatars/get-screenshot.md +++ b/docs/examples/avatars/get-screenshot.md @@ -15,8 +15,7 @@ Avatars avatars = Avatars(client); Uint8List bytes = await avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional @@ -46,8 +45,7 @@ FutureBuilder( future: avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional diff --git a/docs/examples/avatars/update-photo.md b/docs/examples/avatars/update-photo.md new file mode 100644 index 00000000..c2431d7a --- /dev/null +++ b/docs/examples/avatars/update-photo.md @@ -0,0 +1,14 @@ +```dart +import 'dart:io'; +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +Account result = await avatars.updatePhoto( + file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), +); +``` diff --git a/docs/examples/databases/list-transactions.md b/docs/examples/databases/list-transactions.md index ca9ff6fb..9ab66421 100644 --- a/docs/examples/databases/list-transactions.md +++ b/docs/examples/databases/list-transactions.md @@ -9,5 +9,6 @@ Databases databases = Databases(client); TransactionList result = await databases.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/documentsdb/create-documents.md b/docs/examples/documentsdb/create-documents.md index 6a508373..95dd8676 100644 --- a/docs/examples/documentsdb/create-documents.md +++ b/docs/examples/documentsdb/create-documents.md @@ -10,7 +10,16 @@ DocumentsDB documentsDB = DocumentsDB(client); DocumentList result = await documentsDB.createDocuments( databaseId: '', collectionId: '', - documents: [], + documents: [ + { + "$id": "example1", + "username": "walter.obrien", + "email": "walter.obrien@example.com", + "fullName": "Walter O'Brien", + "age": 30, + "isAdmin": false + } + ], transactionId: '', // optional ); ``` diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md index d2c09525..f6ab157d 100644 --- a/docs/examples/documentsdb/list-transactions.md +++ b/docs/examples/documentsdb/list-transactions.md @@ -9,5 +9,6 @@ DocumentsDB documentsDB = DocumentsDB(client); TransactionList result = await documentsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index 7ec3ba75..dca64159 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -8,6 +8,8 @@ Client client = Client() Graphql graphql = Graphql(client); Any result = await graphql.mutation( - query: {}, + query: { + "query": "mutation { accountUpdateName(name: \"Walter\") { name } }" + }, ); ``` diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index cac705e5..668c1845 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -8,6 +8,8 @@ Client client = Client() Graphql graphql = Graphql(client); Any result = await graphql.query( - query: {}, + query: { + "query": "query { localeGet { ip } }" + }, ); ``` diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index 23c375ba..2161cf85 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -LocaleCodeList result = await locale.listCodes(); +LocaleCodeList result = await locale.listCodes( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index 349be795..271db2ad 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -ContinentList result = await locale.listContinents(); +ContinentList result = await locale.listContinents( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-eu.md b/docs/examples/locale/list-countries-eu.md index f775aa2e..3b3d6927 100644 --- a/docs/examples/locale/list-countries-eu.md +++ b/docs/examples/locale/list-countries-eu.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountriesEU(); +CountryList result = await locale.listCountriesEU( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index ee368e29..eb66e362 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -PhoneList result = await locale.listCountriesPhones(); +PhoneList result = await locale.listCountriesPhones( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 17e0814f..fb2b2220 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountries(); +CountryList result = await locale.listCountries( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 751de786..05810fe6 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -CurrencyList result = await locale.listCurrencies(); +CurrencyList result = await locale.listCurrencies( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index 28b46a0a..559ccddd 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -7,5 +7,7 @@ Client client = Client() Locale locale = Locale(client); -LanguageList result = await locale.listLanguages(); +LanguageList result = await locale.listLanguages( + total: false, // optional +); ``` diff --git a/docs/examples/oauth2/approve.md b/docs/examples/oauth2/approve.md new file mode 100644 index 00000000..81a121c2 --- /dev/null +++ b/docs/examples/oauth2/approve.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Approve result = await oauth2.approve( + grantId: '', + authorizationDetails: '', // optional + scope: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize-post.md b/docs/examples/oauth2/authorize-post.md new file mode 100644 index 00000000..7bda4af9 --- /dev/null +++ b/docs/examples/oauth2/authorize-post.md @@ -0,0 +1,26 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Authorize result = await oauth2.authorizePost( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize.md b/docs/examples/oauth2/authorize.md new file mode 100644 index 00000000..46575c33 --- /dev/null +++ b/docs/examples/oauth2/authorize.md @@ -0,0 +1,26 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Authorize result = await oauth2.authorize( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-device-authorization.md b/docs/examples/oauth2/create-device-authorization.md new file mode 100644 index 00000000..b35d9286 --- /dev/null +++ b/docs/examples/oauth2/create-device-authorization.md @@ -0,0 +1,17 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2DeviceAuthorization result = await oauth2.createDeviceAuthorization( + clientId: '', // optional + scope: '', // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-grant.md b/docs/examples/oauth2/create-grant.md new file mode 100644 index 00000000..5d9fefa4 --- /dev/null +++ b/docs/examples/oauth2/create-grant.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Grant result = await oauth2.createGrant( + userCode: '', +); +``` diff --git a/docs/examples/oauth2/create-par.md b/docs/examples/oauth2/create-par.md new file mode 100644 index 00000000..016b8312 --- /dev/null +++ b/docs/examples/oauth2/create-par.md @@ -0,0 +1,25 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2PAR result = await oauth2.createPAR( + clientId: '', + redirectUri: 'https://example.com', + responseType: 'code', + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-token.md b/docs/examples/oauth2/create-token.md new file mode 100644 index 00000000..fcc22e59 --- /dev/null +++ b/docs/examples/oauth2/create-token.md @@ -0,0 +1,22 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Token result = await oauth2.createToken( + grantType: '', + code: '', // optional + refreshToken: '', // optional + deviceCode: '', // optional + clientId: '', // optional + clientSecret: '', // optional + codeVerifier: '', // optional + redirectUri: 'https://example.com', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/get-grant.md b/docs/examples/oauth2/get-grant.md new file mode 100644 index 00000000..b97ddde4 --- /dev/null +++ b/docs/examples/oauth2/get-grant.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Grant result = await oauth2.getGrant( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/list-organizations.md b/docs/examples/oauth2/list-organizations.md new file mode 100644 index 00000000..8006c9e6 --- /dev/null +++ b/docs/examples/oauth2/list-organizations.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2OrganizationList result = await oauth2.listOrganizations( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/list-projects.md b/docs/examples/oauth2/list-projects.md new file mode 100644 index 00000000..d973b0de --- /dev/null +++ b/docs/examples/oauth2/list-projects.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2ProjectList result = await oauth2.listProjects( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout-post.md b/docs/examples/oauth2/logout-post.md new file mode 100644 index 00000000..53e0873d --- /dev/null +++ b/docs/examples/oauth2/logout-post.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + + result = await oauth2.logoutPost( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout.md b/docs/examples/oauth2/logout.md new file mode 100644 index 00000000..7536d2d2 --- /dev/null +++ b/docs/examples/oauth2/logout.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + + result = await oauth2.logout( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/reject.md b/docs/examples/oauth2/reject.md new file mode 100644 index 00000000..beac37d6 --- /dev/null +++ b/docs/examples/oauth2/reject.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +Oauth2Reject result = await oauth2.reject( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/revoke.md b/docs/examples/oauth2/revoke.md new file mode 100644 index 00000000..988f3315 --- /dev/null +++ b/docs/examples/oauth2/revoke.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + + result = await oauth2.revoke( + token: '', + tokenTypeHint: 'access_token', // optional + clientId: '', // optional + clientSecret: '', // optional +); +``` diff --git a/docs/examples/tablesdb/list-transactions.md b/docs/examples/tablesdb/list-transactions.md index d95e5198..fd134437 100644 --- a/docs/examples/tablesdb/list-transactions.md +++ b/docs/examples/tablesdb/list-transactions.md @@ -9,5 +9,6 @@ TablesDB tablesDB = TablesDB(client); TransactionList result = await tablesDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index caab7926..01fa470e 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -9,7 +9,7 @@ Teams teams = Teams(client); Membership result = await teams.createMembership( teamId: '', - roles: [], + roles: ["editor"], email: 'email@example.com', // optional userId: '', // optional phone: '+12065550100', // optional diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 2d7c25c8..51b8178d 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -10,6 +10,6 @@ Teams teams = Teams(client); Membership result = await teams.updateMembership( teamId: '', membershipId: '', - roles: [], + roles: ["editor"], ); ``` diff --git a/docs/examples/vectorsdb/create-operations.md b/docs/examples/vectorsdb/create-operations.md index a994693e..bf2dacd1 100644 --- a/docs/examples/vectorsdb/create-operations.md +++ b/docs/examples/vectorsdb/create-operations.md @@ -16,7 +16,15 @@ Transaction result = await vectorsDB.createOperations( "collectionId": "", "documentId": "", "data": { - "name": "Walter O'Brien" + "embeddings": [ + 0.12, + -0.55, + 0.88, + 1.02 + ], + "metadata": { + "name": "First document" + } } } ], // optional diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md index fb7f83db..a22f32d0 100644 --- a/docs/examples/vectorsdb/list-transactions.md +++ b/docs/examples/vectorsdb/list-transactions.md @@ -9,5 +9,6 @@ VectorsDB vectorsDB = VectorsDB(client); TransactionList result = await vectorsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c80609e3..c2083c8a 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -24,6 +24,8 @@ export 'src/response.dart'; export 'src/client.dart'; export 'src/exception.dart'; export 'src/realtime.dart'; +export 'src/mqtt.dart'; +export 'src/mqtt_message.dart'; export 'src/upload_progress.dart'; export 'src/realtime_subscription.dart'; export 'src/realtime_message.dart'; @@ -33,9 +35,11 @@ part 'query.dart'; part 'permission.dart'; part 'role.dart'; part 'id.dart'; +part 'topic.dart'; part 'channel.dart'; part 'operator.dart'; part 'services/account.dart'; +part 'services/apps.dart'; part 'services/avatars.dart'; part 'services/databases.dart'; part 'services/documents_db.dart'; @@ -43,6 +47,7 @@ part 'services/functions.dart'; part 'services/graphql.dart'; part 'services/locale.dart'; part 'services/messaging.dart'; +part 'services/oauth2.dart'; part 'services/organization.dart'; part 'services/presences.dart'; part 'services/storage.dart'; diff --git a/lib/models.dart b/lib/models.dart index f1fca69d..ce40157d 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -31,6 +31,7 @@ part 'src/models/algo_bcrypt.dart'; part 'src/models/algo_scrypt.dart'; part 'src/models/algo_scrypt_modified.dart'; part 'src/models/algo_argon2.dart'; +part 'src/models/account.dart'; part 'src/models/preferences.dart'; part 'src/models/session.dart'; part 'src/models/identity.dart'; @@ -55,9 +56,29 @@ part 'src/models/mfa_factors.dart'; part 'src/models/transaction.dart'; part 'src/models/subscriber.dart'; part 'src/models/target.dart'; +part 'src/models/app.dart'; +part 'src/models/app_secret.dart'; +part 'src/models/app_secret_plaintext.dart'; +part 'src/models/app_scope.dart'; part 'src/models/app_installation.dart'; +part 'src/models/app_key.dart'; +part 'src/models/oauth2_authorize.dart'; +part 'src/models/oauth2_approve.dart'; +part 'src/models/oauth2_reject.dart'; +part 'src/models/oauth2_grant.dart'; +part 'src/models/oauth2_device_authorization.dart'; +part 'src/models/oauth2_par.dart'; +part 'src/models/oauth2_token.dart'; part 'src/models/oauth2_consent.dart'; part 'src/models/oauth2_consent_token.dart'; +part 'src/models/oauth2_project.dart'; +part 'src/models/oauth2_organization.dart'; +part 'src/models/oauth2_project_list.dart'; +part 'src/models/oauth2_organization_list.dart'; part 'src/models/oauth2_consent_list.dart'; part 'src/models/oauth2_consent_token_list.dart'; +part 'src/models/apps_list.dart'; +part 'src/models/app_secret_list.dart'; +part 'src/models/app_scope_list.dart'; part 'src/models/app_installation_list.dart'; +part 'src/models/app_key_list.dart'; diff --git a/lib/query.dart b/lib/query.dart index 1ad97bdc..aeb93797 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,27 +159,33 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => 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(); + static String or(List queries) { + return Query._( + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } + + static String and(List queries) { + return Query._( + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + static String elemMatch(String attribute, List queries) { + return Query._( + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Specify which attributes should be returned by the API call. static String select(List attributes) => diff --git a/lib/services/account.dart b/lib/services/account.dart index 48492bdb..9eda7926 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1246,10 +1246,14 @@ class Account extends Service { /// Get the list of active sessions across different devices for the currently /// logged in user. - Future listSessions() async { + Future listSessions({ + bool? total, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1267,11 +1271,16 @@ class Account extends Service { } /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { + /// from the end client. Pass `current` as false to keep the session making the + /// request and sign out of every other session. + Future deleteSessions({ + bool? current, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (current != null) 'current': current, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1319,6 +1328,9 @@ class Account extends Service { /// 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. + /// Use the optional `duration` parameter to create a shorter session, for + /// example when the user doesn't choose "remember me". It must be at least 60 + /// seconds and cannot exceed the project maximum session length. /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session @@ -1326,12 +1338,14 @@ class Account extends Service { Future createEmailPasswordSession({ required String email, required String password, + int? duration, }) async { final String apiPath = '/account/sessions/email'; final Map apiParams = { 'email': email, 'password': password, + if (duration != null) 'duration': duration, }; final Map apiHeaders = { diff --git a/lib/services/apps.dart b/lib/services/apps.dart new file mode 100644 index 00000000..1026e7ea --- /dev/null +++ b/lib/services/apps.dart @@ -0,0 +1,852 @@ +part of '../appwrite.dart'; + +/// The Apps service allows you to manage OAuth2 applications, their keys, +/// secrets, scopes, and installations. +class Apps extends Service { + /// Initializes a [Apps] service + Apps(super.client); + + /// List applications. + Future list({ + List? queries, + bool? total, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppsList.fromMap(res.data); + } + + /// Create a new application. + Future create({ + required String appId, + required String name, + required List redirectUris, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + List? postLogoutRedirectUris, + bool? enabled, + String? type, + bool? deviceFlow, + String? teamId, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + 'appId': appId, + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (enabled != null) 'enabled': enabled, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (teamId != null) 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// List scopes an application can request when installed on a team. + Future listInstallationScopes() async { + final String apiPath = '/apps/scopes/installations'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// List scopes an application can request during the OAuth2 flow. + Future listOAuth2Scopes() async { + final String apiPath = '/apps/scopes/oauth2'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// Get an application by its unique ID. + Future get({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Update an application by its unique ID. + Future update({ + required String appId, + required String name, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + bool? enabled, + List? redirectUris, + List? postLogoutRedirectUris, + String? type, + bool? deviceFlow, + List? installationScopes, + String? installationRedirectUrl, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + if (enabled != null) 'enabled': enabled, + if (redirectUris != null) 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (installationScopes != null) 'installationScopes': installationScopes, + if (installationRedirectUrl != null) + 'installationRedirectUrl': installationRedirectUrl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Delete an application by its unique ID. + Future delete({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List installations of an application. Requires an app key sent in the + /// `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, or a caller + /// with update access to the app. + Future listInstallations({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/installations'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallationList.fromMap(res.data); + } + + /// Get an installation of an application by its unique ID. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. + Future getInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallation.fromMap(res.data); + } + + /// Delete an installation of an application by its unique ID. Requires a + /// caller with update access to the app. Previously issued installation access + /// tokens are revoked. + Future deleteInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Create a token for an installation of an application. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. The returned token carries the + /// scopes and authorization details granted to the installation, and can be + /// used as an `Authorization: Bearer` header everywhere OAuth2 access tokens + /// are accepted. Multiple tokens can be active for the same installation at + /// once; each token stays valid until it expires or the installation is + /// updated or deleted. + Future createInstallationToken({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}/tokens' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } + + /// List app keys for an application. + Future listKeys({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKeyList.fromMap(res.data); + } + + /// Create a new app key for an application. App keys carry no scopes; send one + /// in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header to + /// list the application's installations and create installation access tokens. + Future createKey({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Get an app key by its unique ID. + Future getKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Delete an app key by its unique ID. + Future deleteKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List client secrets for an application. + Future listSecrets({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretList.fromMap(res.data); + } + + /// Create a new client secret for an application. + Future createSecret({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretPlaintext.fromMap(res.data); + } + + /// Get an application client secret by its unique ID. + Future getSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecret.fromMap(res.data); + } + + /// Delete an application client secret by its unique ID. + Future deleteSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Transfer an application to another team by its unique ID. + Future updateTeam({ + required String appId, + required String teamId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/team'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Revoke all tokens for an application by its unique ID. + Future deleteTokens({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/tokens'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index c57fb66e..f9b4cbd5 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -242,9 +242,9 @@ class Avatars extends Service { } /// Returns the best available profile photo for a user. The endpoint tries - /// each source in priority order and returns the first successful result: - /// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in - /// static fallback. + /// each source in priority order and returns the first successful result: a + /// custom uploaded photo (see avatars.updatePhoto), OAuth2 identity photo, + /// Gravatar, Libravatar, Appwrite Initials, built-in static fallback. /// /// Passing `userId` — `current()` for the authenticated user — resolves /// the photo from everything known about that user: identity photos, email, @@ -294,6 +294,68 @@ class Avatars extends Service { return res.data; } + /// Update the profile photo of the currently authenticated user. The uploaded + /// image takes priority over every other photo source, including OAuth2 + /// identity photos, Gravatar, and Libravatar. Updating an already customized + /// photo replaces it. The image must be at most 5MB and is sent in a single + /// request. + Future updatePhoto({ + required InputFile file, + Function(UploadProgress)? onProgress, + }) async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = { + 'file': file, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + String idParamName = ''; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + method: HttpMethod.put, + ); + + return models.Account.fromMap(res.data); + } + + /// Delete the profile photo of the currently authenticated user and store the + /// built-in static placeholder in its place. The placeholder is the user's + /// photo from then on, so it takes priority over every other photo source — + /// OAuth2 identity photos, Gravatar, Libravatar, and initials — until a new + /// photo is uploaded with avatars.updatePhoto. + Future deletePhoto() async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + /// 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({ diff --git a/lib/services/databases.dart b/lib/services/databases.dart index f1bb2510..96fed789 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -12,11 +12,13 @@ class Databases extends Service { ) Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/databases/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -189,11 +191,11 @@ class Databases extends Service { ); } - final String apiPath = - '/databases/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/documents_db.dart b/lib/services/documents_db.dart index 3ca77cdb..1d04aa9c 100644 --- a/lib/services/documents_db.dart +++ b/lib/services/documents_db.dart @@ -7,11 +7,13 @@ class DocumentsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/documentsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -65,11 +67,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -100,11 +102,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (commit != null) 'commit': commit, @@ -137,11 +139,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; diff --git a/lib/services/locale.dart b/lib/services/locale.dart index d4831b74..227f1a9b 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -34,10 +34,14 @@ class Locale extends Service { /// List of all locale codes in [ISO /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { + Future listCodes({ + bool? total, + }) async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -56,10 +60,14 @@ class Locale extends Service { /// List of all continents. You can use the locale header to get the data in a /// supported language. - Future listContinents() async { + Future listContinents({ + bool? total, + }) async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -78,10 +86,14 @@ class Locale extends Service { /// List of all countries. You can use the locale header to get the data in a /// supported language. - Future listCountries() async { + Future listCountries({ + bool? total, + }) async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -100,10 +112,14 @@ class Locale extends Service { /// 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 { + Future listCountriesEU({ + bool? total, + }) async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -122,10 +138,14 @@ class Locale extends Service { /// List of all countries phone codes. You can use the locale header to get the /// data in a supported language. - Future listCountriesPhones() async { + Future listCountriesPhones({ + bool? total, + }) async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -145,10 +165,14 @@ class Locale extends Service { /// 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 { + Future listCurrencies({ + bool? total, + }) async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -167,10 +191,14 @@ class Locale extends Service { /// 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 { + Future listLanguages({ + bool? total, + }) async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', diff --git a/lib/services/oauth2.dart b/lib/services/oauth2.dart new file mode 100644 index 00000000..1950338a --- /dev/null +++ b/lib/services/oauth2.dart @@ -0,0 +1,588 @@ +part of '../appwrite.dart'; + +/// The OAuth2 service allows you to authorize apps and issue standards-based +/// OAuth2 and OpenID Connect tokens. +class Oauth2 extends Service { + /// Initializes a [Oauth2] service + Oauth2(super.client); + + /// Approve an OAuth2 grant after the user gives consent. Returns the + /// `redirectUrl` the end user should be sent to. The consent screen may + /// optionally pass enriched `authorization_details` to record the concrete + /// resources the user selected. You can pass Accept header of + /// `application/json` to receive a JSON response instead of a redirect. + Future approve({ + required String grantId, + String? authorizationDetails, + String? scope, + }) async { + final String apiPath = '/oauth2/{project_id}/approve'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (scope != null) 'scope': scope, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Approve.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorize({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorizePost({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Start the OAuth2 Device Authorization Grant. Returns the device code, user + /// code, verification URL, expiration, and polling interval. + Future createDeviceAuthorization({ + String? clientId, + String? scope, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/device_authorization' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (scope != null) 'scope': scope, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2DeviceAuthorization.fromMap(res.data); + } + + /// Exchange a device flow user code for an OAuth2 grant. The authenticated + /// user is bound to the pending grant. Pass the returned grant ID to the get + /// grant endpoint to render the consent screen, then to the approve or reject + /// endpoint to complete the flow. + Future createGrant({ + required String userCode, + }) async { + final String apiPath = '/oauth2/{project_id}/grants'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'user_code': userCode, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// Get an OAuth2 grant by its ID. Used by the consent screen to display the + /// details of the authorization the user is being asked to approve. A grant + /// can only be read by the user it belongs to, or by server SDK. + Future getGrant({ + required String grantId, + }) async { + if (grantId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "grantId"', + ); + } + + final String apiPath = '/oauth2/{project_id}/grants/{grant_id}' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ) + .replaceAll( + '{grant_id}', + grantId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logout({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logoutPost({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List the organizations the OAuth2 access token can access. Resolves the + /// token's `organization` authorization details, expanding the `*` wildcard + /// into the concrete set of organizations the user can see. + Future listOrganizations({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/organizations'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2OrganizationList.fromMap(res.data); + } + + /// Store an OAuth2 authorization request server-side and receive a short-lived + /// request_uri handle for the authorize endpoint. + Future createPAR({ + required String clientId, + required String redirectUri, + required String responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/par'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'client_id': clientId, + 'redirect_uri': redirectUri, + 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2PAR.fromMap(res.data); + } + + /// List the projects the OAuth2 access token can access. Resolves the token's + /// `project` authorization details, expanding the `*` wildcard into the + /// concrete set of projects the user can see. + Future listProjects({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/projects'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2ProjectList.fromMap(res.data); + } + + /// Reject an OAuth2 grant when the user denies consent. Returns the + /// `redirectUrl` the end user should be sent to with an `access_denied` error. + /// You can pass Accept header of `application/json` to receive a JSON response + /// instead of a redirect. + Future reject({ + required String grantId, + }) async { + final String apiPath = '/oauth2/{project_id}/reject'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Reject.fromMap(res.data); + } + + /// Revoke an OAuth2 access token or refresh token. + Future revoke({ + required String token, + String? tokenTypeHint, + String? clientId, + String? clientSecret, + }) async { + final String apiPath = '/oauth2/{project_id}/revoke'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'token': token, + if (tokenTypeHint != null) 'token_type_hint': tokenTypeHint, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Exchange an OAuth2 authorization code, refresh token, or device code for + /// access and refresh tokens. + Future createToken({ + required String grantType, + String? code, + String? refreshToken, + String? deviceCode, + String? clientId, + String? clientSecret, + String? codeVerifier, + String? redirectUri, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/token'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_type': grantType, + if (code != null) 'code': code, + if (refreshToken != null) 'refresh_token': refreshToken, + if (deviceCode != null) 'device_code': deviceCode, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + if (codeVerifier != null) 'code_verifier': codeVerifier, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } +} diff --git a/lib/services/organization.dart b/lib/services/organization.dart index bbda874a..68b762c9 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -75,11 +75,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -112,11 +112,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -151,11 +151,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/storage.dart b/lib/services/storage.dart index 52a129a8..ec4522fe 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -104,6 +104,7 @@ class Storage extends Service { idParamName: idParamName, headers: apiHeaders, onProgress: onProgress, + method: HttpMethod.post, ); return models.File.fromMap(res.data); diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 4fdbb987..e7a5d4a3 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -9,11 +9,13 @@ class TablesDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/tablesdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -171,11 +173,11 @@ class TablesDB extends Service { ); } - final String apiPath = - '/tablesdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/vectors_db.dart b/lib/services/vectors_db.dart index e257b38c..fddd1087 100644 --- a/lib/services/vectors_db.dart +++ b/lib/services/vectors_db.dart @@ -7,11 +7,13 @@ class VectorsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/vectorsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -169,11 +171,11 @@ class VectorsDB extends Service { ); } - final String apiPath = - '/vectorsdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/vectorsdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/src/client.dart b/lib/src/client.dart index fedec03c..f456f011 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -41,6 +40,8 @@ abstract class Client { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }); /// Set self signed to [status]. @@ -56,6 +57,14 @@ abstract class Client { /// Set the Appwrite realtime endpoint. Client setEndPointRealtime(String endPoint); + /// Set the Appwrite push (MQTT broker) endpoint, e.g. + /// `mqtt://host:1883` or `mqtts://host:8883`. + Client setPushEndpoint(String endPoint); + + /// Set a stable push client id, so the broker resumes this client's offline-replay + /// cursor across restarts. Defaults to a per-connection id when unset. + Client setPushClientId(String pushClientId); + /// Set Project. /// /// Your project ID. diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 36e4bbc9..9897e898 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -47,6 +47,12 @@ abstract class ClientBase implements Client { @override Client setEndPointRealtime(String endPoint); + @override + Client setPushEndpoint(String endPoint); + + @override + Client setPushClientId(String pushClientId); + @override ClientBase addHeader(String key, String value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index d04f9bc6..182870c7 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -155,6 +155,18 @@ class ClientBrowser extends ClientBase with ClientMixin { return this; } + @override + ClientBrowser setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientBrowser setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientBrowser addHeader(String key, String value) { _headers![key] = value; @@ -182,7 +194,19 @@ class ClientBrowser extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.bytes == null) { throw AppwriteException("File bytes must be provided for Flutter web"); @@ -191,17 +215,18 @@ class ClientBrowser extends ClientBase with ClientMixin { int size = file.bytes!.length; late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { params[paramName] = http.MultipartFile.fromBytes( paramName, file.bytes!, filename: file.filename, ); return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -249,7 +274,7 @@ class ClientBrowser extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f228d17f..00e8954f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,9 +47,10 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = + HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -59,7 +60,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -185,6 +186,18 @@ class ClientIO extends ClientBase with ClientMixin { return this; } + @override + ClientIO setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientIO setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientIO addHeader(String key, String value) { _headers![key] = value; @@ -286,7 +299,19 @@ class ClientIO extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.path == null && file.bytes == null) { throw AppwriteException("File path or bytes must be provided"); @@ -305,7 +330,7 @@ class ClientIO extends ClientBase with ClientMixin { } late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { if (file.path != null) { params[paramName] = await http.MultipartFile.fromPath( paramName, @@ -320,10 +345,11 @@ class ClientIO extends ClientBase with ClientMixin { ); } return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -349,8 +375,13 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id, - [RandomAccessFile? raf]) async { + Future uploadChunk( + int index, + int start, + int end, + String? id, [ + RandomAccessFile? raf, + ]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -382,7 +413,7 @@ class ClientIO extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, @@ -474,9 +505,10 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: + callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -491,9 +523,10 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = + codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 952d7114..55a75c2c 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -31,6 +31,10 @@ mixin ClientMixin { }); } }); + } else if (value is Map) { + (request as http.MultipartRequest).fields.addAll({ + key: jsonEncode(value), + }); } else { (request as http.MultipartRequest).fields.addAll({ key: value.toString(), @@ -91,9 +95,10 @@ mixin ClientMixin { warnings.split(';').forEach((warning) => log('Warning: $warning')); } + final isJson = (res.headers['content-type'] ?? '').contains( + 'application/json', + ); if (res.statusCode >= 400) { - final isJson = - (res.headers['content-type'] ?? '').contains('application/json'); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -116,20 +121,16 @@ mixin ClientMixin { } } dynamic data; - if ((res.headers['content-type'] ?? '').contains('application/json')) { - if (responseType == ResponseType.json) { - data = json.decode(res.body); - } else if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + if (responseType == ResponseType.bytes) { + data = res.bodyBytes; + } else if (responseType == ResponseType.plain) { + // Decode as UTF-8 whatever the charset, since package:http falls back + // to latin1 when the content-type does not name one. + data = utf8.decode(res.bodyBytes); + } else if (isJson) { + data = json.decode(res.body); } else { - if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + data = res.body; } return Response(data: data); } @@ -141,10 +142,12 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 6b1e67cd..05253273 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,14 +17,15 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }).catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }) + .catchError((e, stackTrace) { + return request; + }); return request; } @@ -43,8 +44,9 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host), + scheme: response.request!.url.scheme, + host: response.request!.url.host, + ), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 595afdc2..0f250ea3 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes + bytes, } diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 02b85c7f..ab1b5668 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -43,6 +43,7 @@ enum OAuthProvider { tradeshift(value: "tradeshift"), tradeshiftBox(value: "tradeshiftBox"), twitch(value: "twitch"), + webflow(value: "webflow"), wordpress(value: "wordpress"), x(value: "x"), yahoo(value: "yahoo"), diff --git a/lib/src/input_file.dart b/lib/src/input_file.dart index c0be7c04..f1022c22 100644 --- a/lib/src/input_file.dart +++ b/lib/src/input_file.dart @@ -8,16 +8,38 @@ class InputFile { final String? contentType; @Deprecated('Use `InputFile.fromPath` or `InputFile.fromBytes` instead.') - InputFile({this.path, this.filename, this.contentType, this.bytes}) { + InputFile({ + String? path, + String? filename, + String? contentType, + List? bytes, + }) : this._( + path: path, + filename: filename, + contentType: contentType, + bytes: bytes, + ); + + InputFile._({this.path, String? filename, this.contentType, this.bytes}) + : filename = filename ?? _filenameFromPath(path) { if (path == null && bytes == null) { throw AppwriteException('One of `path` or `bytes` is required'); } } - InputFile._({this.path, this.filename, this.contentType, this.bytes}) { - if (path == null && bytes == null) { - throw AppwriteException('One of `path` or `bytes` is required'); + /// Mirrors how `package:http` derives a filename in `MultipartFile.fromPath`, + /// so a chunked upload sends the same `filename` as a single-request one. + /// Without it the chunk parts carry no `filename` and the server rejects them + /// as an empty file. + static String? _filenameFromPath(String? path) { + if (path == null) { + return null; } + + final segments = Uri.file(path).pathSegments; + final filename = segments.isEmpty ? '' : segments.last; + + return filename.isEmpty ? null : filename; } /// Provide a file using `path` diff --git a/lib/src/models/account.dart b/lib/src/models/account.dart new file mode 100644 index 00000000..31e79064 --- /dev/null +++ b/lib/src/models/account.dart @@ -0,0 +1,167 @@ +part of '../../models.dart'; + +/// Account +class Account 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; + + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked. + final bool? passwordPwned; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + Account({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + this.passwordPwned, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + factory Account.fromMap( + Map map, + ) { + return Account( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + registration: map['registration'].toString(), + status: map['status'], + labels: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + passwordPwned: map['passwordPwned'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "passwordPwned": passwordPwned, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } +} diff --git a/lib/src/models/app.dart b/lib/src/models/app.dart new file mode 100644 index 00000000..7f2a93cf --- /dev/null +++ b/lib/src/models/app.dart @@ -0,0 +1,177 @@ +part of '../../models.dart'; + +/// App +class App implements Model { + /// App ID. + final String $id; + + /// App creation time in ISO 8601 format. + final String $createdAt; + + /// App update date in ISO 8601 format. + final String $updatedAt; + + /// Application name. + final String name; + + /// Application description shown to users during OAuth2 consent. + final String description; + + /// Application homepage URL shown to users during OAuth2 consent. + final String clientUri; + + /// Application logo URL shown to users during OAuth2 consent. + final String logoUri; + + /// Application privacy policy URL shown to users during OAuth2 consent. + final String privacyPolicyUrl; + + /// Application terms of service URL shown to users during OAuth2 consent. + final String termsUrl; + + /// Application support or security contact emails. + final List contacts; + + /// Application tagline shown to users during OAuth2 consent. + final String tagline; + + /// Application tags shown to users during OAuth2 consent. + final List tags; + + /// Application labels. Read-only for clients; only a server SDK using a project API key can update them. + final List labels; + + /// Application image URLs shown to users during OAuth2 consent. + final List images; + + /// Application support URL shown to users during OAuth2 consent. + final String supportUrl; + + /// Application data deletion URL shown to users during OAuth2 consent. + final String dataDeletionUrl; + + /// List of authorized redirect URIs. These URIs can be used to redirect users after they authenticate. + final List redirectUris; + + /// List of authorized post-logout redirect URIs for OpenID Connect RP-Initiated Logout. The logout endpoint only redirects users to URIs in this list after ending their session. + final List postLogoutRedirectUris; + + /// Whether the app is enabled or not. + final bool enabled; + + /// OAuth2 client type. `public` for SPAs, mobile, and native apps that cannot keep a client secret (PKCE required); `confidential` for server-side clients that authenticate with a client secret. + final String type; + + /// Whether this client may use the OAuth2 Device Authorization Grant (RFC 8628). + final bool deviceFlow; + + /// ID of team that owns the application, if owned by team. Otherwise, user ID will be used. + final String teamId; + + /// ID of user who owns the application, if owned by user. Otherwise, team ID will be used. + final String userId; + + /// Scopes the application requests when installed on a team. Organization-level and project-level scopes only. + final List installationScopes; + + /// URL users are redirected to after creating or updating an installation of this application. Empty for no redirect. + final String installationRedirectUrl; + + /// List of application secrets. + final List secrets; + + App({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.description, + required this.clientUri, + required this.logoUri, + required this.privacyPolicyUrl, + required this.termsUrl, + required this.contacts, + required this.tagline, + required this.tags, + required this.labels, + required this.images, + required this.supportUrl, + required this.dataDeletionUrl, + required this.redirectUris, + required this.postLogoutRedirectUris, + required this.enabled, + required this.type, + required this.deviceFlow, + required this.teamId, + required this.userId, + required this.installationScopes, + required this.installationRedirectUrl, + required this.secrets, + }); + factory App.fromMap( + Map map, + ) { + return App( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + description: map['description'].toString(), + clientUri: map['clientUri'].toString(), + logoUri: map['logoUri'].toString(), + privacyPolicyUrl: map['privacyPolicyUrl'].toString(), + termsUrl: map['termsUrl'].toString(), + contacts: List.from(map['contacts'] ?? []), + tagline: map['tagline'].toString(), + tags: List.from(map['tags'] ?? []), + labels: List.from(map['labels'] ?? []), + images: List.from(map['images'] ?? []), + supportUrl: map['supportUrl'].toString(), + dataDeletionUrl: map['dataDeletionUrl'].toString(), + redirectUris: List.from(map['redirectUris'] ?? []), + postLogoutRedirectUris: List.from(map['postLogoutRedirectUris'] ?? []), + enabled: map['enabled'], + type: map['type'].toString(), + deviceFlow: map['deviceFlow'], + teamId: map['teamId'].toString(), + userId: map['userId'].toString(), + installationScopes: List.from(map['installationScopes'] ?? []), + installationRedirectUrl: map['installationRedirectUrl'].toString(), + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "description": description, + "clientUri": clientUri, + "logoUri": logoUri, + "privacyPolicyUrl": privacyPolicyUrl, + "termsUrl": termsUrl, + "contacts": contacts, + "tagline": tagline, + "tags": tags, + "labels": labels, + "images": images, + "supportUrl": supportUrl, + "dataDeletionUrl": dataDeletionUrl, + "redirectUris": redirectUris, + "postLogoutRedirectUris": postLogoutRedirectUris, + "enabled": enabled, + "type": type, + "deviceFlow": deviceFlow, + "teamId": teamId, + "userId": userId, + "installationScopes": installationScopes, + "installationRedirectUrl": installationRedirectUrl, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_key.dart b/lib/src/models/app_key.dart new file mode 100644 index 00000000..5834ee2d --- /dev/null +++ b/lib/src/models/app_key.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppKey +class AppKey implements Model { + /// App key ID. + final String $id; + + /// App key creation time in ISO 8601 format. + final String $createdAt; + + /// App key update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this app key belongs to. + final String appId; + + /// App key secret. + final String secret; + + /// Last few characters of the app key secret, used to help identify it. + final String hint; + + /// ID of the user who created the app key. + final String createdById; + + /// Name of the user who created the app key. + final String createdByName; + + /// Time the app key was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppKey({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppKey.fromMap( + Map map, + ) { + return AppKey( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_key_list.dart b/lib/src/models/app_key_list.dart new file mode 100644 index 00000000..f4175972 --- /dev/null +++ b/lib/src/models/app_key_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App keys list +class AppKeyList implements Model { + /// Total number of keys that matched your query. + final int total; + + /// List of keys. + final List keys; + + AppKeyList({ + required this.total, + required this.keys, + }); + factory AppKeyList.fromMap( + Map map, + ) { + return AppKeyList( + total: map['total'], + keys: List.from( + map['keys'].map((p) => AppKey.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "keys": keys.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_scope.dart b/lib/src/models/app_scope.dart new file mode 100644 index 00000000..456b614b --- /dev/null +++ b/lib/src/models/app_scope.dart @@ -0,0 +1,49 @@ +part of '../../models.dart'; + +/// AppScope +class AppScope implements Model { + /// Scope value as requested by apps. + final String value; + + /// Human-readable description of what the scope grants. + final String description; + + /// What the scope grants access to. One of `account`, `project`, or `organization`. Only `project` and `organization` scopes are installable. + final String type; + + /// Scope category, used to group scopes on consent and installation screens. + final String category; + + /// Whether the scope is deprecated. Deprecated scopes can still be requested but should not be offered for new grants. + final bool deprecated; + + AppScope({ + required this.value, + required this.description, + required this.type, + required this.category, + required this.deprecated, + }); + factory AppScope.fromMap( + Map map, + ) { + return AppScope( + value: map['value'].toString(), + description: map['description'].toString(), + type: map['type'].toString(), + category: map['category'].toString(), + deprecated: map['deprecated'], + ); + } + + @override + Map toMap() { + return { + "value": value, + "description": description, + "type": type, + "category": category, + "deprecated": deprecated, + }; + } +} diff --git a/lib/src/models/app_scope_list.dart b/lib/src/models/app_scope_list.dart new file mode 100644 index 00000000..b59e3e64 --- /dev/null +++ b/lib/src/models/app_scope_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App scopes list +class AppScopeList implements Model { + /// Total number of scopes that matched your query. + final int total; + + /// List of scopes. + final List scopes; + + AppScopeList({ + required this.total, + required this.scopes, + }); + factory AppScopeList.fromMap( + Map map, + ) { + return AppScopeList( + total: map['total'], + scopes: List.from( + map['scopes'].map((p) => AppScope.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "scopes": scopes.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret.dart b/lib/src/models/app_secret.dart new file mode 100644 index 00000000..b16b102b --- /dev/null +++ b/lib/src/models/app_secret.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecret +class AppSecret implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Always empty. The application client secret is returned only once, in the response of the createSecret method. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecret({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecret.fromMap( + Map map, + ) { + return AppSecret( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_secret_list.dart b/lib/src/models/app_secret_list.dart new file mode 100644 index 00000000..7eb90b7a --- /dev/null +++ b/lib/src/models/app_secret_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App secrets list +class AppSecretList implements Model { + /// Total number of secrets that matched your query. + final int total; + + /// List of secrets. + final List secrets; + + AppSecretList({ + required this.total, + required this.secrets, + }); + factory AppSecretList.fromMap( + Map map, + ) { + return AppSecretList( + total: map['total'], + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret_plaintext.dart b/lib/src/models/app_secret_plaintext.dart new file mode 100644 index 00000000..b70d06e1 --- /dev/null +++ b/lib/src/models/app_secret_plaintext.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecretPlaintext +class AppSecretPlaintext implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Application client secret. Returned only when the secret is created; subsequent reads always return an empty value. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecretPlaintext({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecretPlaintext.fromMap( + Map map, + ) { + return AppSecretPlaintext( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/apps_list.dart b/lib/src/models/apps_list.dart new file mode 100644 index 00000000..0492e9f4 --- /dev/null +++ b/lib/src/models/apps_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// Apps list +class AppsList implements Model { + /// Total number of apps that matched your query. + final int total; + + /// List of apps. + final List apps; + + AppsList({ + required this.total, + required this.apps, + }); + factory AppsList.fromMap( + Map map, + ) { + return AppsList( + total: map['total'], + apps: List.from( + map['apps'].map((p) => App.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "apps": apps.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_approve.dart b/lib/src/models/oauth2_approve.dart new file mode 100644 index 00000000..e4db0be4 --- /dev/null +++ b/lib/src/models/oauth2_approve.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Approve +class Oauth2Approve implements Model { + /// URL the end user should be redirected to after the grant is approved, carrying the authorization `code` and/or `id_token` along with the original `state`. + final String redirectUrl; + + Oauth2Approve({ + required this.redirectUrl, + }); + factory Oauth2Approve.fromMap( + Map map, + ) { + return Oauth2Approve( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_authorize.dart b/lib/src/models/oauth2_authorize.dart new file mode 100644 index 00000000..0e820c68 --- /dev/null +++ b/lib/src/models/oauth2_authorize.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 Authorize +class Oauth2Authorize implements Model { + /// OAuth2 grant ID. Set when the user must give explicit consent; pass it to the approve or reject endpoint. Empty when a redirect URL is returned instead. + final String grantId; + + /// URL the end user should be redirected to when the flow can complete without consent. Empty when consent is still required. + final String redirectUrl; + + Oauth2Authorize({ + required this.grantId, + required this.redirectUrl, + }); + factory Oauth2Authorize.fromMap( + Map map, + ) { + return Oauth2Authorize( + grantId: map['grantId'].toString(), + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "grantId": grantId, + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_device_authorization.dart b/lib/src/models/oauth2_device_authorization.dart new file mode 100644 index 00000000..010af212 --- /dev/null +++ b/lib/src/models/oauth2_device_authorization.dart @@ -0,0 +1,55 @@ +part of '../../models.dart'; + +/// OAuth2 Device Authorization +class Oauth2DeviceAuthorization implements Model { + /// Device verification code used by the client to poll the token endpoint. + final String device_code; + + /// Short code the end user enters on the verification page. + final String user_code; + + /// URL where the end user enters the user code. + final String verification_uri; + + /// Verification URL with the user code prefilled as a query parameter. + final String verification_uri_complete; + + /// Lifetime of the device code and user code in seconds. + final int expires_in; + + /// Minimum polling interval for the token endpoint in seconds. + final int interval; + + Oauth2DeviceAuthorization({ + required this.device_code, + required this.user_code, + required this.verification_uri, + required this.verification_uri_complete, + required this.expires_in, + required this.interval, + }); + factory Oauth2DeviceAuthorization.fromMap( + Map map, + ) { + return Oauth2DeviceAuthorization( + device_code: map['device_code'].toString(), + user_code: map['user_code'].toString(), + verification_uri: map['verification_uri'].toString(), + verification_uri_complete: map['verification_uri_complete'].toString(), + expires_in: map['expires_in'], + interval: map['interval'], + ); + } + + @override + Map toMap() { + return { + "device_code": device_code, + "user_code": user_code, + "verification_uri": verification_uri, + "verification_uri_complete": verification_uri_complete, + "expires_in": expires_in, + "interval": interval, + }; + } +} diff --git a/lib/src/models/oauth2_grant.dart b/lib/src/models/oauth2_grant.dart new file mode 100644 index 00000000..32f22b8f --- /dev/null +++ b/lib/src/models/oauth2_grant.dart @@ -0,0 +1,91 @@ +part of '../../models.dart'; + +/// OAuth2 Grant +class Oauth2Grant implements Model { + /// Grant ID. + final String $id; + + /// Grant creation time in ISO 8601 format. + final String $createdAt; + + /// Grant update date in ISO 8601 format. + final String $updatedAt; + + /// ID of the user the grant belongs to. + final String userId; + + /// ID of the OAuth2 client (app) the grant was requested for. + final String appId; + + /// Requested OAuth2 scopes the user is being asked to consent to. + final List scopes; + + /// Requested RFC 8707 resource indicators the user is being asked to consent to. + final List resources; + + /// Requested authorization_details the user is being asked to consent to, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; + + /// OIDC prompt directive the consent screen should honor. Space-separated list of: login, consent, select_account. + final String prompt; + + /// Redirect URI the user will be sent to after the flow completes. + final String redirectUri; + + /// Unix timestamp of when the user last authenticated. + final int authTime; + + /// Grant expiration time in ISO 8601 format. + final String expire; + + Oauth2Grant({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.appId, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.prompt, + required this.redirectUri, + required this.authTime, + required this.expire, + }); + factory Oauth2Grant.fromMap( + Map map, + ) { + return Oauth2Grant( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + prompt: map['prompt'].toString(), + redirectUri: map['redirectUri'].toString(), + authTime: map['authTime'], + expire: map['expire'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "appId": appId, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "prompt": prompt, + "redirectUri": redirectUri, + "authTime": authTime, + "expire": expire, + }; + } +} diff --git a/lib/src/models/oauth2_organization.dart b/lib/src/models/oauth2_organization.dart new file mode 100644 index 00000000..bef13975 --- /dev/null +++ b/lib/src/models/oauth2_organization.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Organization +class Oauth2Organization implements Model { + /// Organization ID. + final String $id; + + Oauth2Organization({ + required this.$id, + }); + factory Oauth2Organization.fromMap( + Map map, + ) { + return Oauth2Organization( + $id: map['\$id'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + }; + } +} diff --git a/lib/src/models/oauth2_organization_list.dart b/lib/src/models/oauth2_organization_list.dart new file mode 100644 index 00000000..e9136230 --- /dev/null +++ b/lib/src/models/oauth2_organization_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible organizations list +class Oauth2OrganizationList implements Model { + /// Total number of organizations that matched your query. + final int total; + + /// List of organizations. + final List organizations; + + Oauth2OrganizationList({ + required this.total, + required this.organizations, + }); + factory Oauth2OrganizationList.fromMap( + Map map, + ) { + return Oauth2OrganizationList( + total: map['total'], + organizations: List.from( + map['organizations'].map((p) => Oauth2Organization.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "organizations": organizations.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_par.dart b/lib/src/models/oauth2_par.dart new file mode 100644 index 00000000..24c14ec5 --- /dev/null +++ b/lib/src/models/oauth2_par.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 PAR +class Oauth2PAR implements Model { + /// Authorization request handle to pass to the authorize endpoint. + final String request_uri; + + /// Lifetime of the authorization request handle in seconds. + final int expires_in; + + Oauth2PAR({ + required this.request_uri, + required this.expires_in, + }); + factory Oauth2PAR.fromMap( + Map map, + ) { + return Oauth2PAR( + request_uri: map['request_uri'].toString(), + expires_in: map['expires_in'], + ); + } + + @override + Map toMap() { + return { + "request_uri": request_uri, + "expires_in": expires_in, + }; + } +} diff --git a/lib/src/models/oauth2_project.dart b/lib/src/models/oauth2_project.dart new file mode 100644 index 00000000..306faf36 --- /dev/null +++ b/lib/src/models/oauth2_project.dart @@ -0,0 +1,37 @@ +part of '../../models.dart'; + +/// OAuth2 Project +class Oauth2Project implements Model { + /// Project ID. + final String $id; + + /// Region ID the project is deployed in. + final String region; + + /// API endpoint of the region the project is deployed in. Empty when the region has no public hostname configured. + final String endpoint; + + Oauth2Project({ + required this.$id, + required this.region, + required this.endpoint, + }); + factory Oauth2Project.fromMap( + Map map, + ) { + return Oauth2Project( + $id: map['\$id'].toString(), + region: map['region'].toString(), + endpoint: map['endpoint'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "region": region, + "endpoint": endpoint, + }; + } +} diff --git a/lib/src/models/oauth2_project_list.dart b/lib/src/models/oauth2_project_list.dart new file mode 100644 index 00000000..6eef6c21 --- /dev/null +++ b/lib/src/models/oauth2_project_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible projects list +class Oauth2ProjectList implements Model { + /// Total number of projects that matched your query. + final int total; + + /// List of projects. + final List projects; + + Oauth2ProjectList({ + required this.total, + required this.projects, + }); + factory Oauth2ProjectList.fromMap( + Map map, + ) { + return Oauth2ProjectList( + total: map['total'], + projects: List.from( + map['projects'].map((p) => Oauth2Project.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "projects": projects.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_reject.dart b/lib/src/models/oauth2_reject.dart new file mode 100644 index 00000000..26b94257 --- /dev/null +++ b/lib/src/models/oauth2_reject.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Reject +class Oauth2Reject implements Model { + /// URL the end user should be redirected to after the grant is rejected, carrying an `access_denied` error. + final String redirectUrl; + + Oauth2Reject({ + required this.redirectUrl, + }); + factory Oauth2Reject.fromMap( + Map map, + ) { + return Oauth2Reject( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_token.dart b/lib/src/models/oauth2_token.dart new file mode 100644 index 00000000..590264b2 --- /dev/null +++ b/lib/src/models/oauth2_token.dart @@ -0,0 +1,61 @@ +part of '../../models.dart'; + +/// OAuth2 Token +class Oauth2Token implements Model { + /// OAuth2 access token. + final String access_token; + + /// OAuth2 token type. + final String token_type; + + /// Access token lifetime in seconds. + final int expires_in; + + /// OAuth2 refresh token. + final String refresh_token; + + /// Space-separated scopes granted to the access token. + final String scope; + + /// Granted RFC 9396 authorization details as a JSON string. + final String? authorization_details; + + /// OpenID Connect ID token. Returned when the `openid` scope is granted. + final String? id_token; + + Oauth2Token({ + required this.access_token, + required this.token_type, + required this.expires_in, + required this.refresh_token, + required this.scope, + this.authorization_details, + this.id_token, + }); + factory Oauth2Token.fromMap( + Map map, + ) { + return Oauth2Token( + access_token: map['access_token'].toString(), + token_type: map['token_type'].toString(), + expires_in: map['expires_in'], + refresh_token: map['refresh_token'].toString(), + scope: map['scope'].toString(), + authorization_details: map['authorization_details']?.toString(), + id_token: map['id_token']?.toString(), + ); + } + + @override + Map toMap() { + return { + "access_token": access_token, + "token_type": token_type, + "expires_in": expires_in, + "refresh_token": refresh_token, + "scope": scope, + "authorization_details": authorization_details, + "id_token": id_token, + }; + } +} diff --git a/lib/src/mqtt.dart b/lib/src/mqtt.dart new file mode 100644 index 00000000..d55f1e8e --- /dev/null +++ b/lib/src/mqtt.dart @@ -0,0 +1,129 @@ +import 'mqtt_browser.dart' if (dart.library.io) 'mqtt_io.dart'; +import 'service.dart'; +import 'client.dart'; +import 'mqtt_message.dart'; + +/// A callback invoked for every message delivered on a subscribed topic. +typedef PushCallback = void Function(PushMessage message); + +/// Handle for a live subscription created with [Push.subscribe]. +/// +/// Unlike the realtime service's bare unsubscribe callable, a push subscription carries +/// per-subscription state (background delivery, notification title), so [subscribe] +/// returns this handle instead: [unsubscribe] drops it (and closes the connection once +/// the last one is gone) and [update] toggles its options live without resubscribing. +abstract class PushSubscription { + /// Drop this subscription. Closes the connection once the last one is gone. + void unsubscribe(); + + /// Live-update this subscription's [background] delivery, notification [title] and/or + /// [retry] (QoS). Only the arguments you pass change; the rest stay as they + /// were. Changing [retry] re-subscribes this subscription's topics at the + /// new QoS. + void update({bool? background, String? title, bool? retry}); +} + +/// Appwrite native push service — the realtime analog delivered over an MQTT +/// broker, without FCM or APNS. While the app is alive the connection stays open and each +/// message is handed to your callback; a subscription can also opt into background +/// delivery (a notification per message, and on mobile continued delivery while the app is +/// backgrounded or closed). +/// +/// The connection has no tunables — it always keeps its session (clean start off) so the +/// broker can redeliver missed messages, and reliability is chosen per subscription via +/// [subscribe]'s `retry`. TLS (and skipping cert verification via a +/// `?tlsInsecure=true` query flag) is derived from the endpoint, so the whole connection +/// is described in one place. `subscribe` opens the connection lazily and returns a +/// [PushSubscription] handle. The credential is read off the client — set a JWT or session +/// on it (`Client.setJWT` / `Client.setSession`), the same way every other service reads +/// auth. The broker location comes from `Client.setPushEndpoint()` (or the client +/// endpoint) and a stable id from `Client.setPushClientId()`. +/// +/// ```dart +/// final client = Client().setEndpoint('...').setProject('...').setJWT(jwt); +/// final push = Push(client); +/// final sub = await push.subscribe('user/123/#', (message) { +/// print('${message.topic}: ${message.data}'); +/// }); +/// +/// // sub.update(background: true, title: 'Messages'); +/// sub.unsubscribe(); +/// ``` +abstract class Push extends Service { + /// Initializes a [Push] service. + factory Push(Client client) => createPush(client); + + /// Register a callback invoked when the connection opens (CONNACK success). + Push onOpen(void Function() callback); + + /// Register a callback invoked when the connection closes. + Push onClose(void Function() callback); + + /// Register a callback invoked with every error the service hits: a failed or refused + /// connect or reconnect (carrying the broker's reason string when it sent one), a + /// DISCONNECT from the broker, a rejected SUBSCRIBE and background delivery failures. + /// Errors a call also throws (such as [subscribe]'s) are reported here as well. Errors that + /// no call throws are never thrown, so they cannot crash the app: with no callback + /// registered they are logged. + Push onError(void Function(Object error) callback); + + /// Subscribe to one or more topics, resolving to a [PushSubscription] handle. + /// + /// [topics] is a single topic or a list of them, each a string or a `Topic` builder + /// (e.g. `Topic.path(['user', userId]).all()`). Pass `null` to subscribe to the + /// signed-in user's own `users/` topic ("messages for me") without knowing any + /// topic: the user id is read off the client's JWT (or, without one, its session) with + /// no network call, and `AppwriteException` is thrown when neither is set. + /// Like FCM/APNs delivery, the `null` form defaults to [background] `true` (topics default to + /// `false`) and, as always, [retry] `true` (QoS 1); pass either to override. + /// + /// ```dart + /// final sub = await push.subscribe(null, (message) { + /// print(message.data); + /// }); + /// ``` + /// + /// The future resolves only once every subscription has been acknowledged (SUBACK), so a + /// subscribe-then-publish is reliable, and [onOpen]/[onClose]/[onError] observe the + /// in-process connection. On Android a [background] subscription moves the connection to the + /// SDK's native plugin, which also resolves after SUBACK and forwards messages and errors (to + /// [onError]) but not its connection lifecycle, so [onOpen]/[onClose] do not fire for it. On + /// iOS it hands the connection to a background isolate, which subscribes asynchronously and + /// retries failures internally, so it resolves once the isolate has the subscription. + /// + /// [retry] chooses this subscription's delivery guarantee: `true` (the + /// default) subscribes at QoS 1 so the broker holds this topic's messages and redelivers + /// them on reconnect; `false` uses QoS 0 (at-most-once, may be lost). The connection + /// always keeps its session, so replay is a purely per-subscription choice. + /// + /// Set [background] to also keep receiving while the app is backgrounded or closed and post a + /// notification per message with [title] (defaulting to the message topic). Toggle these + /// later with [PushSubscription.update]. + /// + /// On Android the SDK's native plugin saves the subscription and keeps delivering after the + /// app is killed, the device restarts or the app updates, until it is unsubscribed or [close] + /// is called: a scheduled job and alarm wake the app every 15 to 60 seconds to reconnect, and + /// the broker replays what was sent in between ([retry]). [setForeground] adds a foreground + /// service for immediate delivery. It reconnects with the credential saved at subscribe time, + /// so use a session rather than a short-lived JWT. On iOS it runs the connection in a + /// background isolate via `flutter_background_service`; on the web it posts a browser + /// notification while the tab is open. + Future subscribe( + Object? topics, // String, Topic, ResolvedTopic, a List, or null (own user) + PushCallback callback, { + bool? background, + String? title, + bool retry, + }); + + /// Android: run background delivery in a foreground service (with a quiet ongoing + /// notification), for immediate delivery even after the app is killed and during Doze, + /// instead of only the scheduled wake-ups. Saved, so it applies after restarts too. Call it + /// while the app is in the foreground: Android 12+ refuses to start the service from the + /// background. It only affects [background] subscriptions. A no-op elsewhere. + Future setForeground(bool enabled); + + /// Tear down the connection and drop all subscriptions. On Android this also stops + /// background delivery, including subscriptions saved by an earlier run: call it on sign-out. + void close(); +} diff --git a/lib/src/mqtt_browser.dart b/lib/src/mqtt_browser.dart new file mode 100644 index 00000000..4e291b43 --- /dev/null +++ b/lib/src/mqtt_browser.dart @@ -0,0 +1,904 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +// ignore: avoid_web_libraries_in_flutter, deprecated_member_use +import 'dart:html' as html; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_browser_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_message.dart'; + +Push createPush(Client client) => PushWeb(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +/// Web push transport. A browser cannot open a raw TCP socket, so the connection is +/// MQTT over WebSocket (`ws://` / `wss://`) via [MqttBrowserClient]; the native +/// (`dart:io`) build in `mqtt_io.dart` uses a TCP socket instead. The API is identical. +class PushWeb implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final String _path; + + MqttBrowserClient? _mqtt; + Future? _connecting; + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across reloads; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushWeb(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "wss://host"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: WSS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = _pushEndpointPort(client) ?? (resolvedTls ? 443 : 80); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushWeb._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + path: _pushPath(client), + ); + } + + PushWeb._( + this.client, { + required String host, + required int port, + required bool tls, + required String path, + }) : _host = host, + _port = port, + _tls = tls, + _path = path; + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across reloads. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // The WebSocket path from an explicitly-set push endpoint, or the root path by + // default (the broker serves MQTT-over-WebSocket at the root; no "/mqtt" is appended). + static String _pushPath(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint != null) { + try { + final path = Uri.parse(endpoint).path; + if (path.isNotEmpty && path != '/') { + return path; + } + } catch (_) {} + } + return ''; + } + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + return this; + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + final MqttBrowserClient mqtt; + try { + topicList = _topicList(client, topics); + mqtt = await _connect(); + } catch (e) { + if (e is _Superseded) { + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + _notify(e); + rethrow; + } + final epoch = _connectionEpoch; + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + + if (wantsBackground) { + _requestNotificationPermission(); + } + + final ids = []; + final acks = >[]; + + void unsubscribe() { + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + // A filter that lost its last QoS-1 sub but still has QoS-0 subs must be re-subscribed + // lower, or the broker keeps replaying to at-most-once subs. + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + close(); + } + } + + // The broker only starts routing a topic once its subscription is registered, + // so publishing before the SUBACK races the message ahead of the subscription + // and it is dropped (no retained replay on MQTT). Awaiting makes it reliable. + // If any topic's SUBACK fails, roll this call's registrations back (and drop any + // now-unused broker filter) so a failed subscribe leaks no callback, then rethrow. + try { + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + + final completer = Completer(); + (_subAcks[topic] ??= >[]).add(completer); + acks.add(completer.future); + + final subscription = MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(topic), + _effectiveQos(topic), + ); + mqtt.subscribeWithSubscriptionList([subscription]); + } + await Future.wait(acks); + } catch (e) { + if (epoch != _connectionEpoch) { + for (final id in ids) { + _subscriptions.remove(id); + } + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + unsubscribe(); + _notify(e); + rethrow; + } + + void update({bool? background, String? title, bool? retry}) { + final changedFilters = {}; + for (final id in ids) { + final entry = _subscriptions[id]; + if (entry == null) { + continue; + } + if (background != null) { + entry.background = background; + } + if (title != null) { + entry.title = title; + } + if (retry != null && retry != entry.retry) { + entry.retry = retry; + changedFilters.add(entry.filter); + } + } + if (background == true) { + _requestNotificationPermission(); + } + // Re-subscribe affected filters at their new effective QoS. + // A rejected SUBACK reaches onError through [_onSubscribeFail]. + for (final filter in changedFilters) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } catch (e) { + _report(e); + } + } + } + + return _SubscriptionHandle(unsubscribe, update); + } + + void _requestNotificationPermission() { + if (html.Notification.permission != 'granted') { + unawaited( + html.Notification.requestPermission().then( + (_) {}, + onError: _report, + ), + ); + } + } + + // Background delivery on the web is a notification while the tab is open; there is no + // foreground service. + @override + Future setForeground(bool enabled) async {} + + @override + void close() { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _subscriptions.clear(); + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + _mqtt?.disconnect(); + _mqtt = null; + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + _path, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + final clientId = _resolvedClientId; + + final scheme = _tls ? 'wss' : 'ws'; + final mqtt = MqttBrowserClient.withPort( + '$scheme://$_host$_path', + clientId, + _port, + ); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // The broker negotiates the "mqtt" WebSocket subprotocol; offer exactly that so the + // handshake succeeds (a browser rejects the socket when the subprotocol is not echoed). + mqtt.websocketProtocols = MqttConstants.protocolsSingleDefault; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + final filters = _subscriptions.values.map((s) => s.filter).toSet(); + for (final filter in filters) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + // Notification is per-subscription: only subs that opted in show one, each + // with its own title. + if (subscription.background && + html.Notification.permission == 'granted') { + html.Notification(subscription.title ?? topic, body: message.data); + } + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect or a QoS change), so + // onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_foreground.dart b/lib/src/mqtt_foreground.dart new file mode 100644 index 00000000..8636f355 --- /dev/null +++ b/lib/src/mqtt_foreground.dart @@ -0,0 +1,322 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' show DartPluginRegistrant; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; + +/// Android/iOS background delivery for the native (dart:io) push service. +/// +/// Flutter cannot keep the app's own isolate running once the app is closed, so a +/// subscription with `background: true` runs the push connection inside a background isolate +/// held alive by an Android foreground service ([FlutterBackgroundService]). That isolate +/// owns the single MQTT connection, posts a local notification per message +/// ([FlutterLocalNotificationsPlugin]) for the filters that opted into background, and +/// forwards every message back to the app (when it is alive) over a service event so in-app +/// callbacks still fire — mirroring the Android/React Native SDKs' foreground mode. +/// +/// Config is handed to the isolate through a small JSON file in the app documents +/// directory (the isolate does not share the app's memory), and the running isolate is kept +/// in sync via service events. The config file (which holds the credential) is deleted when +/// background delivery stops. + +const String _channelId = 'appwrite-push'; +const String _channelName = 'Notifications'; +const String _messageEvent = 'appwrite.push.message'; +const String _topicsEvent = 'appwrite.push.topics'; +const String _stopEvent = 'appwrite.push.stop'; +const String _errorEvent = 'appwrite.push.error'; + +// How long to wait before retrying a background subscription that failed (SUBACK/connect), +// so delivery converges instead of silently missing messages. +const Duration _retryDelay = Duration(seconds: 2); + +/// The service event the app listens on to forward background messages to callbacks. +String get pushForegroundMessageEvent => _messageEvent; + +/// The service event the isolate relays its errors on, so the app's onError sees them. +String get pushForegroundErrorEvent => _errorEvent; + +// Relay an isolate error to the app (if alive) as its message. +void _relayError(ServiceInstance service, Object error) { + service.invoke(_errorEvent, { + 'message': + error is AppwriteException + ? (error.message ?? error.toString()) + : error.toString(), + }); +} + +Future _configFile() async { + final dir = await getApplicationDocumentsDirectory(); + return File('${dir.path}/appwrite_push_foreground.json'); +} + +Future _writeConfig( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + final config = { + 'endpoint': client.endPoint, + 'endpointPush': client.config['endpointPush'], + 'project': client.config['project'] ?? '', + 'jwt': client.config['jwt'] ?? client.config['jWT'], + 'session': client.config['session'], + 'pushClientId': client.config['pushClientId'], + 'title': serviceTitle, + 'topics': topics, + 'notify': notify, + 'qos': qos, + }; + (await _configFile()).writeAsStringSync(jsonEncode(config)); +} + +// Delete the config file (which holds the credential) so it does not linger on disk after +// background delivery ends. +Future _deleteConfig() async { + try { + final file = await _configFile(); + if (file.existsSync()) { + file.deleteSync(); + } + } catch (_) {} +} + +/// Start the background service (or, if already running, update its topics/notify config +/// live). Called on the app isolate whenever the set of background subscriptions changes. +/// [topics] is the full union the single connection subscribes to; [notify] maps the filters +/// that opted into background to their notification titles. +Future syncPushForeground( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + await _writeConfig( + client, + serviceTitle: serviceTitle, + topics: topics, + notify: notify, + qos: qos, + ); + + final service = FlutterBackgroundService(); + if (await service.isRunning()) { + // The isolate is already up: hand it the new topic/notify/qos set so a later + // subscribe/unsubscribe/update takes effect without a restart. + service.invoke(_topicsEvent, { + 'topics': topics, + 'notify': notify, + 'qos': qos, + }); + return; + } + + await service.configure( + androidConfiguration: AndroidConfiguration( + onStart: pushForegroundEntry, + isForegroundMode: true, + autoStart: false, + notificationChannelId: _channelId, + initialNotificationTitle: serviceTitle, + initialNotificationContent: 'Listening for messages', + ), + iosConfiguration: IosConfiguration( + onForeground: pushForegroundEntry, + autoStart: false, + ), + ); + await service.startService(); +} + +/// Ask the background service to disconnect and stop, and delete the config file. +Future stopPushForeground() async { + FlutterBackgroundService().invoke(_stopEvent); + await _deleteConfig(); +} + +Map _notifyOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', '$value')); + } + return {}; +} + +Map _qosOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', (value as num).toInt())); + } + return {}; +} + +/// Background isolate entry point: opens the connection, subscribes to the persisted +/// topics (kept in sync via [_topicsEvent]), posts a notification per message for the +/// filters that opted into background and forwards every message to the app. +@pragma('vm:entry-point') +Future pushForegroundEntry(ServiceInstance service) async { + WidgetsFlutterBinding.ensureInitialized(); + DartPluginRegistrant.ensureInitialized(); + + final notifications = FlutterLocalNotificationsPlugin(); + final Map config; + try { + await notifications.initialize( + const InitializationSettings( + android: AndroidInitializationSettings('@mipmap/ic_launcher'), + iOS: DarwinInitializationSettings(), + ), + ); + config = + jsonDecode((await _configFile()).readAsStringSync()) + as Map; + } catch (e) { + _relayError( + service, + AppwriteException('Background push failed to start: $e'), + ); + await _deleteConfig(); + service.stopSelf(); + return; + } + + final client = Client() + .setEndpoint(config['endpoint'] as String) + .setProject(config['project'] as String); + final jwt = config['jwt'] as String?; + final session = config['session'] as String?; + if (jwt != null && jwt.isNotEmpty) { + client.setJWT(jwt); + } else if (session != null && session.isNotEmpty) { + client.setSession(session); + } + final endpointPush = config['endpointPush'] as String?; + if (endpointPush != null && endpointPush.isNotEmpty) { + client.setPushEndpoint(endpointPush); + } + final pushClientId = config['pushClientId'] as String?; + if (pushClientId != null && pushClientId.isNotEmpty) { + client.setPushClientId(pushClientId); + } + + // Connection, subscribe and broker errors go to the app's onError. A failed subscribe + // reaches it through here and is then retried below. + final push = Push(client).onError((error) => _relayError(service, error)); + + // filter -> notification title, for the filters that opted into background. Reassigned on + // each [_topicsEvent]; the subscribe closures read the current map, so title/opt-in changes + // take effect without resubscribing. + var notify = _notifyOf(config['notify']); + // filter -> QoS (1 reliable / 0 not) requested by the app for each topic. + var qos = _qosOf(config['qos']); + + // One broker subscription per topic so topics can be added/removed independently as the + // app's subscriptions change, plus the QoS each is currently subscribed at (so a QoS + // change resubscribes rather than being skipped as "already subscribed"). + final subscriptions = {}; + final subscribedQos = {}; + + Future applyTopics(List topics) async { + final wanted = topics.toSet(); + for (final topic in subscriptions.keys.toList()) { + if (!wanted.contains(topic)) { + subscriptions.remove(topic)?.unsubscribe(); + subscribedQos.remove(topic); + } + } + for (final topic in wanted) { + final desiredQos = qos[topic] ?? 1; + if (subscriptions.containsKey(topic)) { + if (subscribedQos[topic] == desiredQos) { + continue; + } + // QoS changed for this topic: drop and resubscribe at the new level. + subscriptions.remove(topic)?.unsubscribe(); + } + final filter = topic; + subscribedQos[topic] = desiredQos; + subscriptions[topic] = await push.subscribe(topic, (message) { + // Notify only for filters that opted into background, each with its own title. + final title = notify[filter]; + if (title != null) { + notifications.show( + message.topic.hashCode, + title, + message.data, + const NotificationDetails( + android: AndroidNotificationDetails( + _channelId, + _channelName, + importance: Importance.high, + ), + iOS: DarwinNotificationDetails(), + ), + ); + } + // Forward to the app isolate (if alive) so in-app callbacks still fire. + service.invoke(_messageEvent, { + 'topic': message.topic, + 'payload': message.data, + 'qos': message.qos, + }); + }, retry: desiredQos == 1); + } + } + + // Serialize topic updates: applyTopics awaits push.subscribe, so overlapping runs could + // otherwise subscribe a topic twice (losing an unsubscribe handle) or apply out of order. + // Chaining runs them one at a time, in arrival order. + var topicQueue = Future.value(); + // The last requested topic set, so a failed subscribe can be retried against what is + // currently wanted (topics may have changed again by the time the retry fires). + var wantedTopics = []; + var retryScheduled = false; + + void queueTopics(List topics) { + wantedTopics = topics; + // A subscribe can fail (SUBACK refused, connection dropped mid-CONNECT); applyTopics + // skips already-subscribed topics, so retrying the current wanted set converges on the + // missing ones instead of silently dropping them. + topicQueue = topicQueue.then((_) => applyTopics(topics)).catchError(( + Object _, + ) { + if (retryScheduled) { + return; + } + retryScheduled = true; + Timer(_retryDelay, () { + retryScheduled = false; + queueTopics(wantedTopics); + }); + }); + } + + service.on(_topicsEvent).listen((data) { + notify = _notifyOf(data?['notify']); + qos = _qosOf(data?['qos']); + final topics = + ((data?['topics'] as List?) ?? const []).cast(); + queueTopics(topics); + }); + + service.on(_stopEvent).listen((_) async { + for (final subscription in subscriptions.values) { + subscription.unsubscribe(); + } + push.close(); + await _deleteConfig(); + service.stopSelf(); + }); + + queueTopics((config['topics'] as List).cast()); +} diff --git a/lib/src/mqtt_io.dart b/lib/src/mqtt_io.dart new file mode 100644 index 00000000..de665f10 --- /dev/null +++ b/lib/src/mqtt_io.dart @@ -0,0 +1,1333 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_server_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_foreground.dart'; +import 'mqtt_message.dart'; +import 'mqtt_native.dart'; + +Push createPush(Client client) => PushIO(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +class PushIO implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final bool _tlsInsecure; + + MqttServerClient? _mqtt; + Future? _connecting; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across restarts; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Whether the connection currently lives in the background isolate (foreground service) + // rather than in-process. The connection relocates there while any subscription wants + // background delivery, and back in-process once none do — one connection either way, so + // the broker never sees two sessions with the same client id. + bool _isolateActive = false; + StreamSubscription?>? _serviceListener; + StreamSubscription?>? _serviceErrorListener; + + // On Android the native plugin hosts background delivery instead of the isolate, on the same + // core as the Android SDK. Null elsewhere. + final PushNative? _native = PushNative.instance; + // Whether the subscriptions currently live on the native plugin's connection. + bool _nativeActive = false; + // Bumped when the subscriptions move to the native host, or the credential changes, + // superseding an _open in flight. + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + StreamSubscription>? _nativeListener; + + // Every Push on Android shares the one native host (one connection per client id), which hosts + // the union of their subscriptions. Native calls run one at a time in call order, so a sign-out + // is never undone by a subscribe still on its way. + static final Set _nativeHosts = {}; + // Every Push with live subscriptions, so the native host can take over their connections. + static final Set _livePushes = {}; + static Future _nativeQueue = Future.value(); + + static Future _enqueueNative(Future Function() op) { + final result = _nativeQueue.then((_) => op()); + _nativeQueue = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Serializes background config writes (topic/notify syncs and stops). Each write is a + // file write plus a service event, so unserialized rapid calls could interleave and apply + // out of order. Chaining runs them in call order; each reads the current state when it + // runs, so the last requested value always wins. + Future _backgroundSync = Future.value(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushIO(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "mqtts://host:8883"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: TLS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = + _pushEndpointPort(client) ?? (resolvedTls ? 8883 : 1883); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushIO._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + tlsInsecure: _insecureFlag(client), + ); + } + + PushIO._( + this.client, { + required String host, + required int port, + required bool tls, + required bool tlsInsecure, + }) : _host = host, + _port = port, + _tls = tls, + _tlsInsecure = tlsInsecure { + // Resume background delivery saved by an earlier run now, instead of at its next + // scheduled wake-up. + unawaited(_native?.resume().catchError(_report)); + } + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across restarts. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // Skip TLS cert verification (self-signed brokers / testing) via a query flag on the push + // endpoint, e.g. "mqtts://host:8883?tlsInsecure=true" — so the whole connection is + // described by one URL, not a second config knob. + static bool _insecureFlag(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return false; + } + try { + final value = Uri.parse(endpoint).queryParameters['tlsInsecure']; + return value == 'true' || value == '1'; + } catch (_) { + return false; + } + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + // On Android, a refused credential that stopped background delivery while no callback + // was registered is delivered now. + final native = _native; + if (native != null) { + unawaited(() async { + try { + final stopped = await native.setErrorCallback(true); + if (stopped != null) { + _report(AppwriteException(stopped)); + } + } catch (e) { + _report(e); + } + }()); + } + return this; + } + + @override + Future setForeground(bool enabled) async { + await _native?.setForeground(enabled); + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + if (error is _Superseded) { + // Internal: a connection superseded by the native host, not a failure. + return; + } + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + try { + topicList = _topicList(client, topics); + } catch (e) { + _notify(e); + rethrow; + } + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + _livePushes.add(this); + + final ids = []; + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + } + + try { + final native = _native; + if (native != null && + (_backgroundWanted || + _nativeHosts.isNotEmpty || + await native.hasSaved())) { + // Android: the native plugin hosts the single connection while any subscription, live + // or saved by an earlier run, wants background. + await _hostNative(); + } else if (_backgroundWanted) { + // Any sub wants background: the isolate hosts the single connection (relocating + // off the in-process one if it was up) and covers the whole topic union. + await _hostInIsolate(); + } else { + while (true) { + try { + await _subscribeInProcess(ids); + break; + } on _Superseded { + // Another Push moved this one's subscriptions to the native host meanwhile: this + // subscribe goes there too. + if (_nativeActive) { + await _hostNative(); + break; + } + } + } + } + } catch (e) { + for (final id in ids) { + _subscriptions.remove(id); + } + // Return to a consistent host for whatever subscriptions remain. + _reconcile(); + _notify(e); + rethrow; + } + + return _SubscriptionHandle( + () => _unsubscribeIds(ids), + ({bool? background, String? title, bool? retry}) => + _updateIds(ids, background: background, title: title, retry: retry), + ); + } + + // In-process host: connect and register this call's new filters, awaiting each SUBACK. + Future _subscribeInProcess(List ids) async { + final mqtt = await _connect(); + final acks = >[]; + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + final completer = Completer(); + (_subAcks[sub.filter] ??= >[]).add(completer); + acks.add(completer.future); + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(sub.filter), + _effectiveQos(sub.filter), + ), + ]); + } + // The broker only starts routing a topic once its subscription is registered, so + // publishing before the SUBACK races the message ahead of it. Awaiting makes it reliable. + await Future.wait(acks); + } + + // Host every subscription of every Push on the native plugin's connection (Android), closing + // this one's in-process connection. Completes once the connection is up and every filter is + // subscribed (SUBACK), or throws why not. + Future _hostNative() { + final native = _native!; + final key = _credentialKey; + // The native host carries one connection, so it serves one credential: instances hosted for + // another move back to their own connection. Instances with this credential share its client + // id, so their in-process connections would take over the broker session: they move to the + // native host too. + for (final push in _nativeHosts.toList()) { + if (push._credentialKey != key) { + push._leaveToInProcess(); + if (push._backgroundWanted) { + push._report(AppwriteException(_backgroundDisplaced)); + } + } + } + // Once moved, they stay: if hosting fails, the native host keeps their subscriptions and + // retries on its scheduled runs, and a second connection with the same client id would take + // over its broker session. + for (final push in _livePushes.toList()) { + if (push._subscriptions.isNotEmpty && push._credentialKey == key) { + push._joinNative(native); + } + } + _joinNative(native); + return _enqueueNative(() => _sendToNative(native)); + } + + // Host every native host's subscriptions with this Push's credential. + Future _sendToNative(PushNative native) async { + // Host what is subscribed when this runs, so a close() or an unsubscribe queued meanwhile + // is not undone by an older request. + final subscriptions = [ + for (final push in _nativeHosts) ...push._nativeEntries, + ]; + if (subscriptions.isEmpty) { + return; + } + final (authMethod, credential) = _credential(); + final config = { + 'host': _host, + 'port': _port, + 'tls': _tls, + 'tlsInsecure': _tlsInsecure, + 'clientId': _resolvedClientId, + 'authMethod': authMethod, + 'credential': credential, + 'project': client.config['project'] ?? '', + }; + await native.setErrorCallback( + _nativeHosts.any((push) => push._onError != null), + ); + await native.host(jsonEncode(config), jsonEncode(subscriptions)); + } + + // Move this Push's subscriptions onto the native host, closing its own connection. + void _joinNative(PushNative native) { + // An _open still in flight sees this and closes what it opened, and a subscribe still waiting + // for its SUBACK continues on the native host. + _dropConnection(); + _nativeListener ??= native.listen( + onMessage: (message) { + final sub = _subscriptions[message.id]; + if (sub == null) { + return; + } + try { + sub.callback( + PushMessage( + topic: message.topic, + payload: message.payload, + qos: message.qos, + ), + ); + } catch (e) { + _report(e); + } + // Acknowledged once its callback has run, as on the in-process connection. + unawaited(native.ack(message.ackToken).catchError(_report)); + }, + onError: (message) => _report(AppwriteException(message)), + ); + _nativeHosts.add(this); + _nativeActive = true; + } + + void _dropConnection() { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + } + } + + // Move this Push's subscriptions back onto its own connection. + void _leaveToInProcess() { + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + + // Identifies the connection this Push authenticates: one native host serves one. + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + // This Push's subscriptions in the native plugin's format. + List> get _nativeEntries => [ + for (final entry in _subscriptions.entries) + { + 'id': entry.key, + 'topic': entry.value.filter, + 'background': entry.value.background, + 'title': entry.value.title, + 'retry': entry.value.retry, + }, + ]; + + // After an unsubscribe or update on Android: keep the native plugin hosting while any + // subscription, live (of any Push) or saved, wants background, else move the live ones back + // in-process. + Future _reconcileNative(PushNative native) async { + if (_subscriptions.isEmpty) { + // This Push has nothing left; saved subscriptions keep delivering in the background. + if (_nativeActive) { + await _leaveNative(native); + } + return; + } + final wanted = + {..._nativeHosts, this}.any((push) => push._backgroundWanted) || + await native.hasSaved(); + if (wanted) { + await _hostNative(); + return; + } + // Nothing wants background: every Push moves back to its own connection. + final hosts = _nativeHosts.toList(); + _nativeHosts.clear(); + for (final push in hosts) { + push._nativeActive = false; + } + await _enqueueNative(() => native.release()); + for (final push in {...hosts, this}) { + if (push._subscriptions.isNotEmpty) { + await push._ensureInProcessSubscribed(); + } + } + } + + // Stop hosting this Push natively; the others' subscriptions stay hosted. + Future _leaveNative(PushNative native) { + _nativeHosts.remove(this); + _nativeActive = false; + if (_nativeHosts.isNotEmpty) { + return _nativeHosts.first._hostNative(); + } + return _enqueueNative(() => native.release()); + } + + // Relocate the connection into the background isolate and sync it with the current topic + // union and per-subscription notification config. + Future _hostInIsolate() async { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + await _syncBackground(); + } + + // Listen for messages the background isolate relays back and forward them to every + // matching in-app callback (so callbacks still fire while the app is alive, background or + // not). Idempotent. + void _attachServiceListener() { + _serviceListener ??= FlutterBackgroundService() + .on(pushForegroundMessageEvent) + .listen((data) { + if (data == null) { + return; + } + final topic = data['topic'] as String? ?? ''; + final payload = Uint8List.fromList( + utf8.encode(data['payload'] as String? ?? ''), + ); + final message = PushMessage( + topic: topic, + payload: payload, + qos: data['qos'] as int? ?? 0, + ); + for (final sub in _subscriptions.values) { + if (_matches(sub.filter, topic)) { + sub.callback(message); + } + } + }); + // The isolate's own connection/subscribe errors, relayed as their message. + _serviceErrorListener ??= FlutterBackgroundService() + .on(pushForegroundErrorEvent) + .listen((data) { + _report( + AppwriteException( + data?['message'] as String? ?? 'Background push failed', + ), + ); + }); + } + + void _detachServiceListener() { + _serviceListener?.cancel(); + _serviceListener = null; + _serviceErrorListener?.cancel(); + _serviceErrorListener = null; + } + + bool get _backgroundWanted => _subscriptions.values.any((s) => s.background); + + // The union of every subscription's filter (the isolate hosts one connection for all). + List get _backgroundTopics => + _subscriptions.values.map((s) => s.filter).toSet().toList(); + + // filter -> notification title, for filters that have at least one background subscription + // (those are the only ones that post a notification, each with its own title). + Map get _notifyConfig { + final map = {}; + for (final sub in _subscriptions.values) { + if (sub.background) { + map[sub.filter] = sub.title ?? _defaultTitle; + } + } + return map; + } + + String get _defaultTitle => 'Appwrite'; + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + // filter -> QoS (1 reliable / 0 not), handed to the isolate so it subscribes each topic + // at the right level. + Map get _qosConfig { + final map = {}; + for (final filter in _backgroundTopics) { + map[filter] = _effectiveQos(filter) == MqttQos.atLeastOnce ? 1 : 0; + } + return map; + } + + // Run a background config write after any already-queued one, so writes never interleave + // or reorder. The returned future carries this write's own result to its caller, while the + // chain itself never rejects (a failed write must not stall later ones). + Future _enqueueBackground(Future Function() op) { + final result = _backgroundSync.then((_) => op()); + _backgroundSync = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Sync the running/started isolate with the current topic union and notify config. + Future _syncBackground() => _enqueueBackground(() async { + // Skip if background was turned off after this was queued, so a stale write can't + // recreate the credential file after shutdown deleted it. + if (!_backgroundWanted) { + return; + } + await syncPushForeground( + client, + serviceTitle: _defaultTitle, + topics: _backgroundTopics, + notify: _notifyConfig, + qos: _qosConfig, + ); + }); + + // Enqueue the background stop after any pending config write, so the credential file is + // always deleted last — a write queued just before shutdown cannot recreate it afterwards. + void _enqueueStop() { + unawaited( + _enqueueBackground(() async { + // Skip if background is wanted again by the time this runs, so a stale stop can't + // tear down a live connection or delete a credential config that is still in use. + if (_backgroundWanted) { + return; + } + await stopPushForeground(); + }).catchError(_report), + ); + } + + // Ensure the correct host (in-process vs isolate) for whatever subscriptions remain, and + // sync it. Called after an unsubscribe/update may have flipped whether background is wanted. + void _reconcile() { + final native = _native; + if (native != null) { + unawaited(_reconcileNative(native).catchError(_report)); + return; + } + if (_subscriptions.isEmpty) { + return; + } + if (_backgroundWanted) { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + unawaited(_syncBackground().catchError(_report)); + } else { + if (_isolateActive) { + _isolateActive = false; + _detachServiceListener(); + _enqueueStop(); + } + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + } + + // Bring up the in-process connection and (re)register every filter — used when the last + // background subscription goes away and the connection relocates back in-process. Nobody + // awaits it, so a rejected SUBACK reaches onError through [_onSubscribeFail]. + Future _ensureInProcessSubscribed() async { + final mqtt = await _connect(); + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + + void _unsubscribeIds(List ids) { + // Filters whose removed sub was QoS 1: their effective QoS may now drop. + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed && _mqtt != null) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + // The last live subscription is gone; on Android, saved ones keep delivering. + _teardown(); + _reconcile(); + return; + } + // A removed sub may have been the last background one (relocate in-process) or just + // change the isolate's topic/notify set (the isolate re-sync carries the new QoS map). + _reconcile(); + // In-process, a filter that lost its last QoS-1 sub but still has QoS-0 subs must be + // re-subscribed lower, or the broker keeps replaying to at-most-once subs. + if (!_backgroundWanted && !_nativeActive && _mqtt != null) { + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + } + } + + void _updateIds( + List ids, { + bool? background, + String? title, + bool? retry, + }) { + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + if (background != null) { + sub.background = background; + } + if (title != null) { + sub.title = title; + } + if (retry != null) { + sub.retry = retry; + } + } + // reconcile re-subscribes (in-process) / re-syncs the isolate at the new effective QoS. + _reconcile(); + } + + /// Tear down the connection and drop all subscriptions. On Android, closing the last Push that + /// uses background delivery also stops it, including subscriptions saved by an earlier run: + /// call it on sign-out. While other Push instances still use it, it keeps delivering their + /// subscriptions and the saved ones. + @override + void close() { + _teardown(); + final native = _native; + if (native == null) { + return; + } + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_nativeListener?.cancel()); + _nativeListener = null; + if (_nativeHosts.isNotEmpty) { + final other = _nativeHosts.first; + unawaited(other._hostNative().catchError(other._report)); + return; + } + unawaited(_enqueueNative(() => native.stop()).catchError(_report)); + } + + // Close the in-process connection (and the isolate host) and drop the live subscriptions. + void _teardown() { + _livePushes.remove(this); + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _detachServiceListener(); + _subscriptions.clear(); + if (_isolateActive) { + _isolateActive = false; + _enqueueStop(); + } + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _dropConnection(); + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + // On Android the native plugin's per-user-and-install id is used when none was set, so this + // connection and the background one share the broker session. + final native = _native; + final clientId = + _resolvedClientId.isEmpty && native != null + ? await native.defaultClientId(authMethod, credential) + : _resolvedClientId; + // The subscriptions moved to the native host while this was waiting: its connection would + // share the host's client id and take over the broker session. + if (epoch != _connectionEpoch) { + throw const _Superseded(); + } + + final mqtt = MqttServerClient.withPort(_host, clientId, _port); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + if (_tls) { + mqtt.secure = true; + if (_tlsInsecure) { + mqtt.onBadCertificate = (dynamic certificate) => true; + } + } + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + // Superseded by the native host, which closed this connection on purpose. + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect, a QoS change or a + // relocation back in-process), so onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +// Reported to a Push whose background delivery stopped because a Push with another credential +// took over the native host, which carries one connection and so serves one credential. +const String _backgroundDisplaced = + 'Background delivery stopped: a Push with another credential started background delivery, ' + 'and the device hosts one. These subscriptions still deliver while the app runs.'; + +// An in-process connect superseded by moving the subscriptions to the native host, or by a +// connect with another credential. +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_message.dart b/lib/src/mqtt_message.dart new file mode 100644 index 00000000..9faa825a --- /dev/null +++ b/lib/src/mqtt_message.dart @@ -0,0 +1,24 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// A message delivered on a subscribed topic — the MQTT push analog of a +/// realtime event. +class PushMessage { + /// The topic the message was published to. + final String topic; + + /// The raw message payload. + final Uint8List payload; + + /// The MQTT quality of service the message was delivered with. + final int qos; + + const PushMessage({ + required this.topic, + required this.payload, + required this.qos, + }); + + /// The payload decoded as UTF-8 text, as it was sent. + String get data => utf8.decode(payload); +} diff --git a/lib/src/mqtt_native.dart b/lib/src/mqtt_native.dart new file mode 100644 index 00000000..11509936 --- /dev/null +++ b/lib/src/mqtt_native.dart @@ -0,0 +1,128 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// A message the native Android plugin delivers for a hosted subscription. +class NativePushMessage { + final String id; + final String topic; + final Uint8List payload; + final int qos; + + /// Passed to [PushNative.ack] once the callback has run; the broker's PUBACK waits for it. + final String ackToken; + + NativePushMessage(this.id, this.topic, this.payload, this.qos, this.ackToken); +} + +/// The SDK's native Android plugin (see android/), which hosts background delivery on the same +/// core as the Appwrite Android SDK: saved subscriptions, scheduled wake-ups after +/// the app is killed, reboot resume, notifications and foreground mode. +class PushNative { + static const String _methodChannel = 'appwrite.push'; + static const String _eventChannel = 'appwrite.push/events'; + static final PushNative _plugin = PushNative._( + const MethodChannel(_methodChannel), + const EventChannel(_eventChannel), + ); + + final MethodChannel _methods; + final EventChannel _events; + Stream>? _stream; + + PushNative._(this._methods, this._events); + + /// The plugin's channels on [messenger] instead of the engine's, for tests that stand in for + /// the plugin. + @visibleForTesting + PushNative.forMessenger(BinaryMessenger messenger) + : _methods = MethodChannel( + _methodChannel, + const StandardMethodCodec(), + messenger, + ), + _events = EventChannel( + _eventChannel, + const StandardMethodCodec(), + messenger, + ); + + /// Used instead of the plugin by [Push] instances created while it is set, in tests. + @visibleForTesting + static PushNative? debugInstance; + + /// The plugin on Android, else null. + static PushNative? get instance => + debugInstance ?? (Platform.isAndroid ? _plugin : null); + + /// Host [subscriptionsJson] on the background connection described by [configJson]. Completes + /// once the connection is up and every filter is subscribed, or throws why not. + Future host(String configJson, String subscriptionsJson) => + _methods.invokeMethod('host', { + 'config': configJson, + 'subscriptions': subscriptionsJson, + }); + + /// Acknowledge a message once its callback has run. + Future ack(String token) => + _methods.invokeMethod('ack', {'token': token}); + + /// Stop hosting the live subscriptions, keeping the ones saved by an earlier run. + Future release() => _methods.invokeMethod('release'); + + /// Stop background delivery and forget every saved subscription. + Future stop() => _methods.invokeMethod('stop'); + + /// Run background delivery in a foreground service; saved across restarts. + Future setForeground(bool enabled) => + _methods.invokeMethod('setForeground', {'enabled': enabled}); + + /// Whether an earlier run saved background subscriptions that are still delivered. + Future hasSaved() async => + await _methods.invokeMethod('hasSaved') ?? false; + + /// Resume saved background delivery now instead of at the next scheduled run. + Future resume() => _methods.invokeMethod('resume'); + + /// Record whether onError is registered; returns a refusal kept while it was not, once. + Future setErrorCallback(bool registered) => _methods + .invokeMethod('setErrorCallback', {'registered': registered}); + + /// The default client id for a credential, so a foreground connection shares its session. + Future defaultClientId(String authMethod, String credential) async => + await _methods.invokeMethod('defaultClientId', { + 'authMethod': authMethod, + 'credential': credential, + }) ?? + ''; + + /// Listen to the plugin's messages and errors. + StreamSubscription> listen({ + required void Function(NativePushMessage message) onMessage, + required void Function(String message) onError, + }) { + final stream = + _stream ??= + _events + .receiveBroadcastStream() + .map((event) => event as Map) + .asBroadcastStream(); + return stream.listen((event) { + if (event['type'] == 'message') { + onMessage( + NativePushMessage( + event['id'] as String, + event['topic'] as String, + event['payload'] as Uint8List, + event['qos'] as int, + event['ackToken'] as String, + ), + ); + } else if (event['type'] == 'error') { + onError(event['message'] as String? ?? 'Background push failed'); + } + }); + } +} diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index a0f4193a..e56b7ddd 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,10 +25,12 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace(queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }); + uri = uri.replace( + queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }, + ); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..ab1c3b42 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,9 +37,11 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel((client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers)); + final websok = IOWebSocketChannel( + (client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers), + ); return websok; } @@ -73,13 +75,18 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, Map headers) async { + Uri uri, + Map headers, + ) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = - (X509Certificate cert, String host, int port) { + client.badCertificateCallback = ( + X509Certificate cert, + String host, + int port, + ) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index ee4c4c30..e1a32db8 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,74 +100,80 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen((response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add(jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - })); + _websocketSubscription = _websok?.stream.listen( + (response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add( + jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + }), + ); + } + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; - } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': - break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': break; - } + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { + break; + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); + } } - } - break; - } - }, onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }); + break; + } + }, + onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, + onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }, + ); } catch (e) { if (e is AppwriteException) { rethrow; @@ -197,27 +203,30 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server"); + "Please set endPointRealtime to connect to realtime server", + ); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = + (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", + ); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -227,10 +236,12 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add(jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + }), + ); } String _generateUniqueSubscriptionId() { @@ -292,10 +303,12 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add(jsonEncode({ - 'type': 'subscribe', - 'data': rows, - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'subscribe', + 'data': rows, + }), + ); } void _flushPendingPresence() { @@ -312,8 +325,10 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo( + List channels, [ + List queries = const [], + ]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); @@ -383,7 +398,9 @@ mixin RealtimeMixin { void handleError(RealtimeResponse response) { if (response.data['code'] == status.policyViolation) { final error = AppwriteException( - response.data["message"], response.data["code"]); + response.data["message"], + response.data["code"], + ); for (var subscription in _subscriptions.values) { subscription.controller.addError(error); } diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..631afe31 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,6 +2,7 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => throw UnsupportedError( +RealtimeBase createRealtime(Client client) => + throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index e572b519..6461e344 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/lib/topic.dart b/lib/topic.dart new file mode 100644 index 00000000..e3c43a55 --- /dev/null +++ b/lib/topic.dart @@ -0,0 +1,85 @@ +part of 'appwrite.dart'; + +/// Helper to build MQTT topics for `Push`, level by level. +/// +/// ```dart +/// Topic.path(['user', userId, 'notification']); // "user/123/notification" +/// Topic.path(['user']).any().path(['notification']); // "user/+/notification" +/// Topic.path(['org']).any().path(['logs']).all(); // "org/+/logs/#" +/// ``` +/// +/// `any()` matches exactly one level and `all()` everything below, at any depth +/// (including the parent itself). `all()` ends the topic, so it returns a +/// [ResolvedTopic]. +class Topic { + final List _levels; + + Topic._(this._levels); + + /// Start a topic with the given levels, e.g. `Topic.path(['user', userId])`. + static Topic path(List levels) => Topic._(_topicLevelsOf(levels)); + + /// Start a topic with a single-level wildcard (`+`). + static Topic any() => Topic._(const ['+']); + + /// The multi-level wildcard alone (`#`): matches every topic. + static ResolvedTopic all() => ResolvedTopic._(const ['#']); + + @override + String toString() => _levels.join('/'); +} + +/// Appends levels to a [Topic]: `Topic.path(['user']).any().path(['notification'])`. +extension TopicLevels on Topic { + /// Append the given levels. + Topic path(List levels) => + Topic._([..._levels, ..._topicLevelsOf(levels)]); + + /// Append a single-level wildcard (`+`): matches exactly one level. + Topic any() => Topic._([..._levels, '+']); + + /// Append the multi-level wildcard (`#`) and end the topic. + ResolvedTopic all() => ResolvedTopic._([..._levels, '#']); +} + +/// A topic ended by `all()`: nothing can be appended after the `#` wildcard. +class ResolvedTopic { + final List _levels; + + ResolvedTopic._(this._levels); + + @override + String toString() => _levels.join('/'); +} + +/// Validate the levels passed to `path()`: a non-empty list of non-empty +/// strings, none holding the level separator `/` or the wildcards `+` and `#` +/// (use `any()` and `all()` for those). +List _topicLevelsOf(List levels) { + if (levels.isEmpty) { + throw ArgumentError('path() needs at least one level'); + } + for (var index = 0; index < levels.length; index++) { + final level = levels[index]; + if (level.isEmpty) { + throw ArgumentError('empty level at index $index'); + } + if (level.contains('/')) { + final parts = level.split('/').map((part) => "'$part'").join(', '); + throw ArgumentError('"$level" contains "/", split it: path([$parts])'); + } + if (level == '+') { + throw ArgumentError('"+" is reserved, use any()'); + } + if (level.contains('+')) { + throw ArgumentError('"$level" contains "+", use any() for wildcards'); + } + if (level == '#') { + throw ArgumentError('"#" is reserved, use all()'); + } + if (level.contains('#')) { + throw ArgumentError('"$level" contains "#", use all() for wildcards'); + } + } + return List.unmodifiable(levels); +} diff --git a/pubspec.yaml b/pubspec.yaml index b04bee5a..21f452d7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 27.0.0 +version: 27.1.0-rc.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -23,8 +23,12 @@ dependencies: device_info_plus: '>=11.5.0 <14.0.0' flutter_web_auth_2: ^5.0.0 http: '>=0.13.6 <2.0.0' + mqtt5_client: ^4.12.0 + flutter_background_service: ^5.0.5 + flutter_local_notifications: ^18.0.1 package_info_plus: '>=8.0.2 <11.0.0' path_provider: ^2.1.4 + typed_data: ^1.3.2 web_socket_channel: ^3.0.1 web: ^1.0.0 @@ -34,3 +38,12 @@ dev_dependencies: flutter_test: sdk: flutter mockito: ^5.4.4 + +# Android: the native half of Push, which runs background delivery on the same core as the +# Appwrite Android SDK. Other platforms need no native code. +flutter: + plugin: + platforms: + android: + package: io.appwrite.flutter + pluginClass: AppwritePushPlugin diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..5ed52b81 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect(Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents'); + expect( + Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents', + ); }); test('returns database channel with action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), - 'databases.db1.collections.col1.documents.doc1.create'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').create().toString(), + 'databases.db1.collections.col1.documents.doc1.create', + ); }); test('returns database channel with upsert action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), - 'databases.db1.collections.col1.documents.doc1.upsert'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').upsert().toString(), + 'databases.db1.collections.col1.documents.doc1.upsert', + ); }); }); @@ -39,18 +39,17 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect(Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows'); + expect( + Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows', + ); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), - 'tablesdb.db1.tables.table1.rows.row1.update'); + Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + 'tablesdb.db1.tables.table1.rows.row1.update', + ); }); }); @@ -67,12 +66,16 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files', + ); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete'); + expect( + Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete', + ); }); }); @@ -116,13 +119,17 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect( + Channel.membership('membership1').toString(), + 'memberships.membership1', + ); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), - 'memberships.membership1.update'); + expect( + Channel.membership('membership1').update().toString(), + 'memberships.membership1.update', + ); }); }); @@ -140,23 +147,31 @@ void main() { }); test('returns presence channel with create action', () { - expect(Channel.presence('presence1').create().toString(), - 'presences.presence1.create'); + expect( + Channel.presence('presence1').create().toString(), + 'presences.presence1.create', + ); }); test('returns presence channel with upsert action', () { - expect(Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert'); + expect( + Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert', + ); }); test('returns presence channel with update action', () { - expect(Channel.presence('presence1').update().toString(), - 'presences.presence1.update'); + expect( + Channel.presence('presence1').update().toString(), + 'presences.presence1.update', + ); }); test('returns presence channel with delete action', () { - expect(Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete'); + expect( + Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete', + ); }); }); } diff --git a/test/services/account_test.dart b/test/services/account_test.dart index ef1bc31b..25047e20 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/apps_test.dart b/test/services/apps_test.dart new file mode 100644 index 00000000..a60f0d67 --- /dev/null +++ b/test/services/apps_test.dart @@ -0,0 +1,524 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Apps test', () { + late MockClient client; + late Apps apps; + + setUp(() { + client = MockClient(); + apps = Apps(client); + }); + + test('test method list()', () async { + final Map data = { + 'total': 5, + 'apps': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.list(); + expect(response, isA()); + }); + + test('test method create()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.create( + appId: "", + name: "", + redirectUris: [], + ); + expect(response, isA()); + }); + + test('test method listInstallationScopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallationScopes(); + expect(response, isA()); + }); + + test('test method listOAuth2Scopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listOAuth2Scopes(); + expect(response, isA()); + }); + + test('test method get()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.get( + appId: "", + ); + expect(response, isA()); + }); + + test('test method update()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.update( + appId: "", + name: "", + ); + expect(response, isA()); + }); + + test('test method delete()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.delete( + appId: "", + ); + }); + + test('test method listInstallations()', () async { + final Map data = { + 'total': 5, + 'installations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallations( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getInstallation()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", + 'scopes': [], + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getInstallation( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method deleteInstallation()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteInstallation( + appId: "", + installationId: "", + ); + }); + + test('test method createInstallationToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createInstallationToken( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method listKeys()', () async { + final Map data = { + 'total': 5, + 'keys': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listKeys( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createKey( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getKey( + appId: "", + keyId: "", + ); + expect(response, isA()); + }); + + test('test method deleteKey()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteKey( + appId: "", + keyId: "", + ); + }); + + test('test method listSecrets()', () async { + final Map data = { + 'total': 5, + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listSecrets( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createSecret( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': "", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getSecret( + appId: "", + secretId: "", + ); + expect(response, isA()); + }); + + test('test method deleteSecret()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteSecret( + appId: "", + secretId: "", + ); + }); + + test('test method updateTeam()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.updateTeam( + appId: "", + teamId: "", + ); + expect(response, isA()); + }); + + test('test method deleteTokens()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteTokens( + appId: "", + ); + }); + }); +} diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 835e2951..18c4d03d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ @@ -152,6 +154,52 @@ void main() { expect(response, isA()); }); + test('test method updatePhoto()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", + 'status': true, + 'labels': [], + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + ), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.updatePhoto( + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + + test('test method deletePhoto()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.deletePhoto(); + }); + test('test method getQR()', () async { final Uint8List data = Uint8List.fromList([]); diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index d92a7381..eb03954a 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/documents_db_test.dart b/test/services/documents_db_test.dart index 6e7d3a62..4312cced 100644 --- a/test/services/documents_db_test.dart +++ b/test/services/documents_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 75d34f13..93a7bc81 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 779767e3..3333a66e 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index c9bb5236..77ee7ddd 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 823af01e..5bf1cbd3 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/oauth2_test.dart b/test/services/oauth2_test.dart new file mode 100644 index 00000000..41976a32 --- /dev/null +++ b/test/services/oauth2_test.dart @@ -0,0 +1,300 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Oauth2 test', () { + late MockClient client; + late Oauth2 oauth2; + + setUp(() { + client = MockClient(); + oauth2 = Oauth2(client); + }); + + test('test method approve()', () async { + final Map data = { + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.approve( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method authorize()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorize(); + expect(response, isA()); + }); + + test('test method authorizePost()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorizePost(); + expect(response, isA()); + }); + + test('test method createDeviceAuthorization()', () async { + final Map data = { + 'device_code': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'user_code': "ABCD-EFGH", + 'verification_uri': "https://appwrite.io/oauth2/device", + 'verification_uri_complete': + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + 'expires_in': 900, + 'interval': 5, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createDeviceAuthorization(); + expect(response, isA()); + }); + + test('test method createGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createGrant( + userCode: "", + ); + expect(response, isA()); + }); + + test('test method getGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.getGrant( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method logout()', () async { + final data = ''; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logout(); + }); + + test('test method logoutPost()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logoutPost(); + }); + + test('test method listOrganizations()', () async { + final Map data = { + 'total': 5, + 'organizations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listOrganizations(); + expect(response, isA()); + }); + + test('test method createPAR()', () async { + final Map data = { + 'request_uri': "urn:appwrite:oauth2:request:5e5ea5c16897e", + 'expires_in': 600, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createPAR( + clientId: "", + redirectUri: "https://example.com", + responseType: "code", + ); + expect(response, isA()); + }); + + test('test method listProjects()', () async { + final Map data = { + 'total': 5, + 'projects': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listProjects(); + expect(response, isA()); + }); + + test('test method reject()', () async { + final Map data = { + 'redirectUrl': + "https://example.com/callback?error=access_denied&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.reject( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method revoke()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.revoke( + token: "", + ); + }); + + test('test method createToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createToken( + grantType: "", + ); + expect(response, isA()); + }); + }); +} diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart index a6ea2c70..7354def0 100644 --- a/test/services/organization_test.dart +++ b/test/services/organization_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 9de09725..9f160e79 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 92d858ee..d1e6f09b 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 47f0eee8..90a55af7 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index cafe8858..7c9f2faf 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/vectors_db_test.dart b/test/services/vectors_db_test.dart index 14660ed0..dc13e38d 100644 --- a/test/services/vectors_db_test.dart +++ b/test/services/vectors_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 3d301a85..bc1c08ae 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,22 +7,26 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); @@ -30,11 +34,40 @@ void main() { final inputFile = InputFile.fromPath(path: '/path/to/file'); expect(inputFile.path, '/path/to/file'); - expect(inputFile.filename, isNull); + expect(inputFile.filename, 'file'); expect(inputFile.contentType, isNull); expect(inputFile.bytes, isNull); }); + test('derives filename from path when none is given', () { + expect( + InputFile.fromPath(path: '/path/to/video.mp4').filename, + 'video.mp4', + reason: 'chunks of a file over 5MB are sent as bytes, and without a ' + 'filename the server rejects them as an empty file', + ); + expect(InputFile.fromPath(path: './relative/image.png').filename, + 'image.png'); + expect(InputFile.fromPath(path: 'video.mp4').filename, 'video.mp4'); + }); + + test('keeps an explicitly provided filename', () { + final inputFile = InputFile.fromPath( + path: '/path/to/video.mp4', + filename: 'renamed.mp4', + ); + + expect(inputFile.filename, 'renamed.mp4'); + }); + + test('derives filename from path on the deprecated constructor', () { + expect(InputFile(path: '/path/to/video.mp4').filename, 'video.mp4'); + }); + + test('leaves filename null when the path has no final segment', () { + expect(InputFile.fromPath(path: '/path/to/').filename, isNull); + }); + test('creates InputFile from bytes', () { final inputFile = InputFile.fromBytes( bytes: [1, 2, 3], diff --git a/test/src/models/account_test.dart b/test/src/models/account_test.dart new file mode 100644 index 00000000..9c4da2e1 --- /dev/null +++ b/test/src/models/account_test.dart @@ -0,0 +1,46 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Account', () { + test('model', () { + final model = Account( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "John Doe", + registration: "2020-10-15T06:38:00.000+00:00", + status: true, + labels: [], + passwordUpdate: "2020-10-15T06:38:00.000+00:00", + email: "john@appwrite.io", + phone: "+4930901820", + emailVerification: true, + phoneVerification: true, + mfa: true, + prefs: Preferences(data: {}), + targets: [], + accessedAt: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Account.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "John Doe"); + expect(result.registration, "2020-10-15T06:38:00.000+00:00"); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, "2020-10-15T06:38:00.000+00:00"); + expect(result.email, "john@appwrite.io"); + expect(result.phone, "+4930901820"); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/app_key_list_test.dart b/test/src/models/app_key_list_test.dart new file mode 100644 index 00000000..556e98a1 --- /dev/null +++ b/test/src/models/app_key_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKeyList', () { + test('model', () { + final model = AppKeyList( + total: 5, + keys: [], + ); + + final map = model.toMap(); + final result = AppKeyList.fromMap(map); + + expect(result.total, 5); + expect(result.keys, []); + }); + }); +} diff --git a/test/src/models/app_key_test.dart b/test/src/models/app_key_test.dart new file mode 100644 index 00000000..a4aedc6a --- /dev/null +++ b/test/src/models/app_key_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKey', () { + test('model', () { + final model = AppKey( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppKey.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_scope_list_test.dart b/test/src/models/app_scope_list_test.dart new file mode 100644 index 00000000..f14fe488 --- /dev/null +++ b/test/src/models/app_scope_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScopeList', () { + test('model', () { + final model = AppScopeList( + total: 5, + scopes: [], + ); + + final map = model.toMap(); + final result = AppScopeList.fromMap(map); + + expect(result.total, 5); + expect(result.scopes, []); + }); + }); +} diff --git a/test/src/models/app_scope_test.dart b/test/src/models/app_scope_test.dart new file mode 100644 index 00000000..edf43230 --- /dev/null +++ b/test/src/models/app_scope_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScope', () { + test('model', () { + final model = AppScope( + value: "organization:organization.read", + description: "Access to read the organization", + type: "organization", + category: "Organization", + deprecated: true, + ); + + final map = model.toMap(); + final result = AppScope.fromMap(map); + + expect(result.value, "organization:organization.read"); + expect(result.description, "Access to read the organization"); + expect(result.type, "organization"); + expect(result.category, "Organization"); + expect(result.deprecated, true); + }); + }); +} diff --git a/test/src/models/app_secret_list_test.dart b/test/src/models/app_secret_list_test.dart new file mode 100644 index 00000000..7e77552a --- /dev/null +++ b/test/src/models/app_secret_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretList', () { + test('model', () { + final model = AppSecretList( + total: 5, + secrets: [], + ); + + final map = model.toMap(); + final result = AppSecretList.fromMap(map); + + expect(result.total, 5); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/app_secret_plaintext_test.dart b/test/src/models/app_secret_plaintext_test.dart new file mode 100644 index 00000000..801dfc74 --- /dev/null +++ b/test/src/models/app_secret_plaintext_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretPlaintext', () { + test('model', () { + final model = AppSecretPlaintext( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecretPlaintext.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_secret_test.dart b/test/src/models/app_secret_test.dart new file mode 100644 index 00000000..856e8c33 --- /dev/null +++ b/test/src/models/app_secret_test.dart @@ -0,0 +1,31 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecret', () { + test('model', () { + final model = AppSecret( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: "", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecret.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.secret, ""); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_test.dart b/test/src/models/app_test.dart new file mode 100644 index 00000000..a1cf013a --- /dev/null +++ b/test/src/models/app_test.dart @@ -0,0 +1,67 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('App', () { + test('model', () { + final model = App( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "My Application", + description: "Connect your workspace to My Application.", + clientUri: "https://example.com", + logoUri: "https://example.com/logo.png", + privacyPolicyUrl: "https://example.com/privacy", + termsUrl: "https://example.com/terms", + contacts: [], + tagline: "Automate your workspace.", + tags: [], + labels: [], + images: [], + supportUrl: "https://example.com/support", + dataDeletionUrl: "https://example.com/data-deletion", + redirectUris: [], + postLogoutRedirectUris: [], + enabled: true, + type: "confidential", + deviceFlow: true, + teamId: "5e5ea5c16897e", + userId: "5e5ea5c16897e", + installationScopes: [], + installationRedirectUrl: "https://example.com/setup", + secrets: [], + ); + + final map = model.toMap(); + final result = App.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "My Application"); + expect(result.description, "Connect your workspace to My Application."); + expect(result.clientUri, "https://example.com"); + expect(result.logoUri, "https://example.com/logo.png"); + expect(result.privacyPolicyUrl, "https://example.com/privacy"); + expect(result.termsUrl, "https://example.com/terms"); + expect(result.contacts, []); + expect(result.tagline, "Automate your workspace."); + expect(result.tags, []); + expect(result.labels, []); + expect(result.images, []); + expect(result.supportUrl, "https://example.com/support"); + expect(result.dataDeletionUrl, "https://example.com/data-deletion"); + expect(result.redirectUris, []); + expect(result.postLogoutRedirectUris, []); + expect(result.enabled, true); + expect(result.type, "confidential"); + expect(result.deviceFlow, true); + expect(result.teamId, "5e5ea5c16897e"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.installationScopes, []); + expect(result.installationRedirectUrl, "https://example.com/setup"); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/apps_list_test.dart b/test/src/models/apps_list_test.dart new file mode 100644 index 00000000..19150689 --- /dev/null +++ b/test/src/models/apps_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppsList', () { + test('model', () { + final model = AppsList( + total: 5, + apps: [], + ); + + final map = model.toMap(); + final result = AppsList.fromMap(map); + + expect(result.total, 5); + expect(result.apps, []); + }); + }); +} diff --git a/test/src/models/oauth2_approve_test.dart b/test/src/models/oauth2_approve_test.dart new file mode 100644 index 00000000..a045bfcf --- /dev/null +++ b/test/src/models/oauth2_approve_test.dart @@ -0,0 +1,20 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Approve', () { + test('model', () { + final model = Oauth2Approve( + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Approve.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_authorize_test.dart b/test/src/models/oauth2_authorize_test.dart new file mode 100644 index 00000000..f1546316 --- /dev/null +++ b/test/src/models/oauth2_authorize_test.dart @@ -0,0 +1,22 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Authorize', () { + test('model', () { + final model = Oauth2Authorize( + grantId: "5e5ea5c16897e", + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Authorize.fromMap(map); + + expect(result.grantId, "5e5ea5c16897e"); + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_device_authorization_test.dart b/test/src/models/oauth2_device_authorization_test.dart new file mode 100644 index 00000000..d68181a5 --- /dev/null +++ b/test/src/models/oauth2_device_authorization_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2DeviceAuthorization', () { + test('model', () { + final model = Oauth2DeviceAuthorization( + device_code: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + user_code: "ABCD-EFGH", + verification_uri: "https://appwrite.io/oauth2/device", + verification_uri_complete: + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + expires_in: 900, + interval: 5, + ); + + final map = model.toMap(); + final result = Oauth2DeviceAuthorization.fromMap(map); + + expect( + result.device_code, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.user_code, "ABCD-EFGH"); + expect(result.verification_uri, "https://appwrite.io/oauth2/device"); + expect( + result.verification_uri_complete, + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + ); + expect(result.expires_in, 900); + expect(result.interval, 5); + }); + }); +} diff --git a/test/src/models/oauth2_grant_test.dart b/test/src/models/oauth2_grant_test.dart new file mode 100644 index 00000000..65a866a9 --- /dev/null +++ b/test/src/models/oauth2_grant_test.dart @@ -0,0 +1,43 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Grant', () { + test('model', () { + final model = Oauth2Grant( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c16897e", + appId: "5e5ea5c16897e", + scopes: [], + resources: [], + authorizationDetails: + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + prompt: "login", + redirectUri: "https://example.com/callback", + authTime: 1592981250, + expire: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Oauth2Grant.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.scopes, []); + expect(result.resources, []); + expect( + result.authorizationDetails, + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + ); + expect(result.prompt, "login"); + expect(result.redirectUri, "https://example.com/callback"); + expect(result.authTime, 1592981250); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/oauth2_organization_list_test.dart b/test/src/models/oauth2_organization_list_test.dart new file mode 100644 index 00000000..e55d8efd --- /dev/null +++ b/test/src/models/oauth2_organization_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2OrganizationList', () { + test('model', () { + final model = Oauth2OrganizationList( + total: 5, + organizations: [], + ); + + final map = model.toMap(); + final result = Oauth2OrganizationList.fromMap(map); + + expect(result.total, 5); + expect(result.organizations, []); + }); + }); +} diff --git a/test/src/models/oauth2_organization_test.dart b/test/src/models/oauth2_organization_test.dart new file mode 100644 index 00000000..7d56d71c --- /dev/null +++ b/test/src/models/oauth2_organization_test.dart @@ -0,0 +1,17 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Organization', () { + test('model', () { + final model = Oauth2Organization( + $id: "5e5ea5c16897e", + ); + + final map = model.toMap(); + final result = Oauth2Organization.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + }); + }); +} diff --git a/test/src/models/oauth2_par_test.dart b/test/src/models/oauth2_par_test.dart new file mode 100644 index 00000000..8ccc1d58 --- /dev/null +++ b/test/src/models/oauth2_par_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2PAR', () { + test('model', () { + final model = Oauth2PAR( + request_uri: "urn:appwrite:oauth2:request:5e5ea5c16897e", + expires_in: 600, + ); + + final map = model.toMap(); + final result = Oauth2PAR.fromMap(map); + + expect(result.request_uri, "urn:appwrite:oauth2:request:5e5ea5c16897e"); + expect(result.expires_in, 600); + }); + }); +} diff --git a/test/src/models/oauth2_project_list_test.dart b/test/src/models/oauth2_project_list_test.dart new file mode 100644 index 00000000..1f6cf6a6 --- /dev/null +++ b/test/src/models/oauth2_project_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ProjectList', () { + test('model', () { + final model = Oauth2ProjectList( + total: 5, + projects: [], + ); + + final map = model.toMap(); + final result = Oauth2ProjectList.fromMap(map); + + expect(result.total, 5); + expect(result.projects, []); + }); + }); +} diff --git a/test/src/models/oauth2_project_test.dart b/test/src/models/oauth2_project_test.dart new file mode 100644 index 00000000..9771b53f --- /dev/null +++ b/test/src/models/oauth2_project_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Project', () { + test('model', () { + final model = Oauth2Project( + $id: "5e5ea5c16897e", + region: "fra", + endpoint: "https://fra.cloud.appwrite.io/v1", + ); + + final map = model.toMap(); + final result = Oauth2Project.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.region, "fra"); + expect(result.endpoint, "https://fra.cloud.appwrite.io/v1"); + }); + }); +} diff --git a/test/src/models/oauth2_reject_test.dart b/test/src/models/oauth2_reject_test.dart new file mode 100644 index 00000000..79aacf6a --- /dev/null +++ b/test/src/models/oauth2_reject_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Reject', () { + test('model', () { + final model = Oauth2Reject( + redirectUrl: + "https://example.com/callback?error=access_denied&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Reject.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?error=access_denied&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_token_test.dart b/test/src/models/oauth2_token_test.dart new file mode 100644 index 00000000..5dafe749 --- /dev/null +++ b/test/src/models/oauth2_token_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Token', () { + test('model', () { + final model = Oauth2Token( + access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + scope: "openid email profile", + ); + + final map = model.toMap(); + final result = Oauth2Token.fromMap(map); + + expect(result.access_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."); + expect(result.token_type, "Bearer"); + expect(result.expires_in, 3600); + expect(result.refresh_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."); + expect(result.scope, "openid email profile"); + }); + }); +} diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 4435280a..029c35bf 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,7 +48,9 @@ void main() { final responseString = response1.toString(); expect( - responseString, equals('RealtimeResponse(type: $type, data: $data)')); + responseString, + equals('RealtimeResponse(type: $type, data: $data)'), + ); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index 1515f1a3..d19e6eac 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,15 +8,18 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction( - {List? channels, List? queries}) async {} + Future mockUpdateFunction({ + List? channels, + List? queries, + }) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const []); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const [], + ); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index d21607ec..3dce66c9 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded + "chunksUploaded": chunksUploaded, }; final uploadProgress = UploadProgress( $id: id, diff --git a/test/topic_test.dart b/test/topic_test.dart new file mode 100644 index 00000000..ba797dfa --- /dev/null +++ b/test/topic_test.dart @@ -0,0 +1,70 @@ +import 'package:appwrite/appwrite.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('path()', () { + test('joins levels', () { + expect(Topic.path(['user']).toString(), 'user'); + expect( + Topic.path(['user', 'notification']).toString(), + 'user/notification', + ); + }); + + test('appends levels', () { + expect( + Topic.path(['user']).path(['notification']).toString(), + 'user/notification', + ); + }); + }); + + group('any()', () { + test('appends a single-level wildcard', () { + expect( + Topic.path(['user']).any().path(['notification']).toString(), + 'user/+/notification', + ); + expect( + Topic.path(['chat']).any().any().path(['message']).toString(), + 'chat/+/+/message', + ); + }); + + test('starts a topic', () { + expect(Topic.any().path(['notification']).toString(), '+/notification'); + }); + }); + + group('all()', () { + test('ends a topic', () { + expect( + Topic.path(['org']).any().path(['logs']).all().toString(), + 'org/+/logs/#', + ); + }); + + test('matches every topic', () { + expect(Topic.all().toString(), '#'); + }); + }); + + group('errors', () { + final invalid = >{ + 'an empty path': [], + 'an empty level': ['user', ''], + 'a slash': ['user/123'], + 'a lone +': ['user', '+'], + 'an embedded +': ['user', 'a+b'], + 'a lone #': ['user', '#'], + 'an embedded #': ['user', 'a#b'], + }; + + invalid.forEach((name, levels) { + test('rejects $name', () { + expect(() => Topic.path(levels), throwsArgumentError); + expect(() => Topic.any().path(levels), throwsArgumentError); + }); + }); + }); +} From 08faf7a958f35ecea43c3f35f2781e48629d0baf Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Tue, 6 Oct 2026 08:03:24 +0000 Subject: [PATCH 17/17] chore: update Flutter SDK to 27.1.0-rc.0 --- CHANGELOG.md | 11 + README.md | 56 +- android/.editorconfig | 39 + android/build.gradle | 56 + android/consumer-rules.pro | 27 + android/settings.gradle | 1 + android/src/main/AndroidManifest.xml | 41 + .../appwrite/exceptions/AppwriteException.kt | 6 + .../io/appwrite/flutter/AppwritePushPlugin.kt | 108 ++ .../io/appwrite/services/PushBackground.kt | 1009 +++++++++++++ .../kotlin/io/appwrite/services/PushBridge.kt | 135 ++ .../kotlin/io/appwrite/services/PushCore.kt | 374 +++++ .../io/appwrite/services/PushReceiver.kt | 33 + .../io/appwrite/services/PushService.kt | 67 + .../io/appwrite/services/PushWakeups.kt | 46 + .../account/create-anonymous-session.md | 3 +- .../account/create-email-password-session.md | 4 +- docs/examples/account/create-email-token.md | 3 +- .../account/create-email-verification-otp.md | 3 +- .../account/create-email-verification.md | 3 +- .../account/create-id-token-session.md | 3 +- docs/examples/account/create-jwt.md | 3 +- .../account/create-magic-url-token.md | 3 +- .../account/create-mfa-authenticator.md | 3 +- docs/examples/account/create-mfa-challenge.md | 3 +- .../account/create-mfa-recovery-codes.md | 3 +- docs/examples/account/create-phone-token.md | 3 +- .../account/create-phone-verification.md | 3 +- docs/examples/account/create-push-target.md | 3 +- docs/examples/account/create-recovery-otp.md | 3 +- docs/examples/account/create-recovery.md | 3 +- docs/examples/account/create-session.md | 3 +- docs/examples/account/create-verification.md | 3 +- docs/examples/account/create.md | 3 +- docs/examples/account/delete-sessions.md | 4 +- docs/examples/account/get-consent-token.md | 3 +- docs/examples/account/get-consent.md | 3 +- .../account/get-mfa-recovery-codes.md | 3 +- docs/examples/account/get-prefs.md | 3 +- docs/examples/account/get-session.md | 3 +- docs/examples/account/get.md | 3 +- docs/examples/account/list-consent-tokens.md | 3 +- docs/examples/account/list-consents.md | 3 +- docs/examples/account/list-identities.md | 3 +- docs/examples/account/list-mfa-factors.md | 3 +- docs/examples/account/list-sessions.md | 5 +- .../account/update-email-verification-otp.md | 3 +- .../account/update-email-verification.md | 3 +- docs/examples/account/update-email.md | 3 +- .../account/update-magic-url-session.md | 3 +- .../account/update-mfa-authenticator.md | 3 +- docs/examples/account/update-mfa-challenge.md | 3 +- .../account/update-mfa-recovery-codes.md | 3 +- docs/examples/account/update-mfa.md | 3 +- docs/examples/account/update-name.md | 3 +- docs/examples/account/update-password.md | 3 +- docs/examples/account/update-phone-session.md | 3 +- .../account/update-phone-verification.md | 3 +- docs/examples/account/update-phone.md | 3 +- docs/examples/account/update-prefs.md | 3 +- docs/examples/account/update-push-target.md | 3 +- docs/examples/account/update-recovery-otp.md | 3 +- docs/examples/account/update-recovery.md | 3 +- docs/examples/account/update-session.md | 3 +- docs/examples/account/update-status.md | 3 +- docs/examples/account/update-verification.md | 3 +- .../apps/create-installation-token.md | 15 + docs/examples/apps/create-key.md | 14 + docs/examples/apps/create-secret.md | 14 + docs/examples/apps/create.md | 32 + docs/examples/apps/delete-installation.md | 14 + docs/examples/apps/delete-key.md | 14 + docs/examples/apps/delete-secret.md | 14 + docs/examples/apps/delete-tokens.md | 13 + docs/examples/apps/delete.md | 13 + docs/examples/apps/get-installation.md | 15 + docs/examples/apps/get-key.md | 15 + docs/examples/apps/get-secret.md | 15 + docs/examples/apps/get.md | 14 + .../examples/apps/list-installation-scopes.md | 12 + docs/examples/apps/list-installations.md | 16 + docs/examples/apps/list-keys.md | 16 + docs/examples/apps/list-o-auth-2-scopes.md | 12 + docs/examples/apps/list-secrets.md | 16 + docs/examples/apps/list.md | 15 + docs/examples/apps/update-team.md | 15 + docs/examples/apps/update.md | 33 + docs/examples/avatars/delete-photo.md | 11 + docs/examples/avatars/get-screenshot.md | 6 +- docs/examples/avatars/update-photo.md | 15 + docs/examples/databases/create-document.md | 3 +- docs/examples/databases/create-operations.md | 3 +- docs/examples/databases/create-transaction.md | 3 +- .../databases/decrement-document-attribute.md | 3 +- docs/examples/databases/get-document.md | 3 +- docs/examples/databases/get-transaction.md | 3 +- .../databases/increment-document-attribute.md | 3 +- docs/examples/databases/list-documents.md | 3 +- docs/examples/databases/list-transactions.md | 4 +- docs/examples/databases/update-document.md | 3 +- docs/examples/databases/update-transaction.md | 3 +- docs/examples/databases/upsert-document.md | 3 +- docs/examples/documentsdb/create-document.md | 3 +- docs/examples/documentsdb/create-documents.md | 14 +- .../examples/documentsdb/create-operations.md | 3 +- .../documentsdb/create-transaction.md | 3 +- .../decrement-document-attribute.md | 3 +- docs/examples/documentsdb/get-document.md | 3 +- docs/examples/documentsdb/get-transaction.md | 3 +- .../increment-document-attribute.md | 3 +- docs/examples/documentsdb/list-documents.md | 3 +- .../examples/documentsdb/list-transactions.md | 4 +- docs/examples/documentsdb/update-document.md | 3 +- .../documentsdb/update-transaction.md | 3 +- docs/examples/documentsdb/upsert-document.md | 3 +- docs/examples/functions/create-execution.md | 3 +- docs/examples/functions/get-execution.md | 3 +- docs/examples/functions/list-executions.md | 3 +- docs/examples/graphql/mutation.md | 7 +- docs/examples/graphql/query.md | 7 +- docs/examples/locale/get.md | 3 +- docs/examples/locale/list-codes.md | 5 +- docs/examples/locale/list-continents.md | 5 +- docs/examples/locale/list-countries-eu.md | 5 +- docs/examples/locale/list-countries-phones.md | 5 +- docs/examples/locale/list-countries.md | 5 +- docs/examples/locale/list-currencies.md | 5 +- docs/examples/locale/list-languages.md | 5 +- docs/examples/messaging/create-subscriber.md | 3 +- docs/examples/oauth2/approve.md | 16 + docs/examples/oauth2/authorize-post.md | 27 + docs/examples/oauth2/authorize.md | 27 + .../oauth2/create-device-authorization.md | 18 + docs/examples/oauth2/create-grant.md | 14 + docs/examples/oauth2/create-par.md | 26 + docs/examples/oauth2/create-token.md | 23 + docs/examples/oauth2/get-grant.md | 14 + docs/examples/oauth2/list-organizations.md | 16 + docs/examples/oauth2/list-projects.md | 16 + docs/examples/oauth2/logout-post.md | 18 + docs/examples/oauth2/logout.md | 18 + docs/examples/oauth2/reject.md | 14 + docs/examples/oauth2/revoke.md | 16 + .../organization/create-installation.md | 3 +- .../examples/organization/get-installation.md | 3 +- .../organization/list-installations.md | 3 +- .../organization/update-installation.md | 3 +- docs/examples/presences/get.md | 3 +- docs/examples/presences/list.md | 3 +- docs/examples/presences/update.md | 3 +- docs/examples/presences/upsert.md | 3 +- docs/examples/storage/create-file.md | 3 +- docs/examples/storage/get-file.md | 3 +- docs/examples/storage/list-files.md | 3 +- docs/examples/storage/update-file.md | 3 +- docs/examples/tablesdb/create-operations.md | 3 +- docs/examples/tablesdb/create-row.md | 3 +- docs/examples/tablesdb/create-transaction.md | 3 +- .../examples/tablesdb/decrement-row-column.md | 3 +- docs/examples/tablesdb/get-row.md | 3 +- docs/examples/tablesdb/get-transaction.md | 3 +- .../examples/tablesdb/increment-row-column.md | 3 +- docs/examples/tablesdb/list-rows.md | 3 +- docs/examples/tablesdb/list-transactions.md | 4 +- docs/examples/tablesdb/update-row.md | 3 +- docs/examples/tablesdb/update-transaction.md | 3 +- docs/examples/tablesdb/upsert-row.md | 3 +- docs/examples/teams/create-installation.md | 3 +- docs/examples/teams/create-membership.md | 5 +- docs/examples/teams/create.md | 3 +- docs/examples/teams/get-installation.md | 3 +- docs/examples/teams/get-membership.md | 3 +- docs/examples/teams/get-prefs.md | 3 +- docs/examples/teams/get.md | 3 +- docs/examples/teams/list-installations.md | 3 +- docs/examples/teams/list-memberships.md | 3 +- docs/examples/teams/list.md | 3 +- docs/examples/teams/update-installation.md | 3 +- .../teams/update-membership-status.md | 3 +- docs/examples/teams/update-membership.md | 5 +- docs/examples/teams/update-name.md | 3 +- docs/examples/teams/update-prefs.md | 3 +- docs/examples/vectorsdb/create-document.md | 3 +- docs/examples/vectorsdb/create-operations.md | 13 +- docs/examples/vectorsdb/create-query.md | 3 +- docs/examples/vectorsdb/create-transaction.md | 3 +- docs/examples/vectorsdb/get-document.md | 3 +- docs/examples/vectorsdb/get-transaction.md | 3 +- docs/examples/vectorsdb/list-documents.md | 3 +- docs/examples/vectorsdb/list-transactions.md | 4 +- docs/examples/vectorsdb/update-document.md | 3 +- docs/examples/vectorsdb/update-transaction.md | 3 +- docs/examples/vectorsdb/upsert-document.md | 3 +- lib/appwrite.dart | 5 + lib/models.dart | 21 + lib/query.dart | 38 +- lib/services/account.dart | 24 +- lib/services/apps.dart | 852 +++++++++++ lib/services/avatars.dart | 68 +- lib/services/databases.dart | 12 +- lib/services/documents_db.dart | 32 +- lib/services/locale.dart | 56 +- lib/services/oauth2.dart | 588 ++++++++ lib/services/organization.dart | 30 +- lib/services/storage.dart | 1 + lib/services/tables_db.dart | 12 +- lib/services/vectors_db.dart | 12 +- lib/src/client.dart | 13 +- lib/src/client_base.dart | 6 + lib/src/client_browser.dart | 33 +- lib/src/client_io.dart | 63 +- lib/src/client_mixin.dart | 41 +- lib/src/cookie_manager.dart | 22 +- lib/src/enums.dart | 2 +- lib/src/enums/o_auth_provider.dart | 1 + lib/src/input_file.dart | 30 +- lib/src/models/account.dart | 167 +++ lib/src/models/app.dart | 177 +++ lib/src/models/app_key.dart | 73 + lib/src/models/app_key_list.dart | 33 + lib/src/models/app_scope.dart | 49 + lib/src/models/app_scope_list.dart | 33 + lib/src/models/app_secret.dart | 73 + lib/src/models/app_secret_list.dart | 33 + lib/src/models/app_secret_plaintext.dart | 73 + lib/src/models/apps_list.dart | 33 + lib/src/models/oauth2_approve.dart | 25 + lib/src/models/oauth2_authorize.dart | 31 + .../models/oauth2_device_authorization.dart | 55 + lib/src/models/oauth2_grant.dart | 91 ++ lib/src/models/oauth2_organization.dart | 25 + lib/src/models/oauth2_organization_list.dart | 33 + lib/src/models/oauth2_par.dart | 31 + lib/src/models/oauth2_project.dart | 37 + lib/src/models/oauth2_project_list.dart | 33 + lib/src/models/oauth2_reject.dart | 25 + lib/src/models/oauth2_token.dart | 61 + lib/src/mqtt.dart | 129 ++ lib/src/mqtt_browser.dart | 904 +++++++++++ lib/src/mqtt_foreground.dart | 322 ++++ lib/src/mqtt_io.dart | 1333 +++++++++++++++++ lib/src/mqtt_message.dart | 24 + lib/src/mqtt_native.dart | 128 ++ lib/src/realtime_browser.dart | 10 +- lib/src/realtime_io.dart | 19 +- lib/src/realtime_mixin.dart | 185 +-- lib/src/realtime_stub.dart | 3 +- lib/src/realtime_subscription.dart | 2 +- lib/topic.dart | 85 ++ pubspec.yaml | 15 +- test/channel_test.dart | 89 +- test/services/account_test.dart | 2 + test/services/apps_test.dart | 524 +++++++ test/services/avatars_test.dart | 48 + test/services/databases_test.dart | 2 + test/services/documents_db_test.dart | 2 + test/services/functions_test.dart | 2 + test/services/graphql_test.dart | 2 + test/services/locale_test.dart | 2 + test/services/messaging_test.dart | 2 + test/services/oauth2_test.dart | 300 ++++ test/services/organization_test.dart | 2 + test/services/presences_test.dart | 2 + test/services/storage_test.dart | 2 + test/services/tables_db_test.dart | 2 + test/services/teams_test.dart | 2 + test/services/vectors_db_test.dart | 2 + test/src/input_file_test.dart | 55 +- test/src/models/account_test.dart | 46 + test/src/models/app_key_list_test.dart | 19 + test/src/models/app_key_test.dart | 35 + test/src/models/app_scope_list_test.dart | 19 + test/src/models/app_scope_test.dart | 25 + test/src/models/app_secret_list_test.dart | 19 + .../src/models/app_secret_plaintext_test.dart | 35 + test/src/models/app_secret_test.dart | 31 + test/src/models/app_test.dart | 67 + test/src/models/apps_list_test.dart | 19 + test/src/models/oauth2_approve_test.dart | 20 + test/src/models/oauth2_authorize_test.dart | 22 + .../oauth2_device_authorization_test.dart | 35 + test/src/models/oauth2_grant_test.dart | 43 + .../models/oauth2_organization_list_test.dart | 19 + test/src/models/oauth2_organization_test.dart | 17 + test/src/models/oauth2_par_test.dart | 19 + test/src/models/oauth2_project_list_test.dart | 19 + test/src/models/oauth2_project_test.dart | 21 + test/src/models/oauth2_reject_test.dart | 21 + test/src/models/oauth2_token_test.dart | 25 + test/src/realtime_response_test.dart | 4 +- test/src/realtime_subscription_test.dart | 19 +- test/src/upload_progress_test.dart | 2 +- test/topic_test.dart | 70 + 293 files changed, 10697 insertions(+), 444 deletions(-) create mode 100644 android/.editorconfig create mode 100644 android/build.gradle create mode 100644 android/consumer-rules.pro create mode 100644 android/settings.gradle create mode 100644 android/src/main/AndroidManifest.xml create mode 100644 android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt create mode 100644 android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushBackground.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushBridge.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushCore.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushReceiver.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushService.kt create mode 100644 android/src/main/kotlin/io/appwrite/services/PushWakeups.kt create mode 100644 docs/examples/apps/create-installation-token.md create mode 100644 docs/examples/apps/create-key.md create mode 100644 docs/examples/apps/create-secret.md create mode 100644 docs/examples/apps/create.md create mode 100644 docs/examples/apps/delete-installation.md create mode 100644 docs/examples/apps/delete-key.md create mode 100644 docs/examples/apps/delete-secret.md create mode 100644 docs/examples/apps/delete-tokens.md create mode 100644 docs/examples/apps/delete.md create mode 100644 docs/examples/apps/get-installation.md create mode 100644 docs/examples/apps/get-key.md create mode 100644 docs/examples/apps/get-secret.md create mode 100644 docs/examples/apps/get.md create mode 100644 docs/examples/apps/list-installation-scopes.md create mode 100644 docs/examples/apps/list-installations.md create mode 100644 docs/examples/apps/list-keys.md create mode 100644 docs/examples/apps/list-o-auth-2-scopes.md create mode 100644 docs/examples/apps/list-secrets.md create mode 100644 docs/examples/apps/list.md create mode 100644 docs/examples/apps/update-team.md create mode 100644 docs/examples/apps/update.md create mode 100644 docs/examples/avatars/delete-photo.md create mode 100644 docs/examples/avatars/update-photo.md create mode 100644 docs/examples/oauth2/approve.md create mode 100644 docs/examples/oauth2/authorize-post.md create mode 100644 docs/examples/oauth2/authorize.md create mode 100644 docs/examples/oauth2/create-device-authorization.md create mode 100644 docs/examples/oauth2/create-grant.md create mode 100644 docs/examples/oauth2/create-par.md create mode 100644 docs/examples/oauth2/create-token.md create mode 100644 docs/examples/oauth2/get-grant.md create mode 100644 docs/examples/oauth2/list-organizations.md create mode 100644 docs/examples/oauth2/list-projects.md create mode 100644 docs/examples/oauth2/logout-post.md create mode 100644 docs/examples/oauth2/logout.md create mode 100644 docs/examples/oauth2/reject.md create mode 100644 docs/examples/oauth2/revoke.md create mode 100644 lib/services/apps.dart create mode 100644 lib/services/oauth2.dart create mode 100644 lib/src/models/account.dart create mode 100644 lib/src/models/app.dart create mode 100644 lib/src/models/app_key.dart create mode 100644 lib/src/models/app_key_list.dart create mode 100644 lib/src/models/app_scope.dart create mode 100644 lib/src/models/app_scope_list.dart create mode 100644 lib/src/models/app_secret.dart create mode 100644 lib/src/models/app_secret_list.dart create mode 100644 lib/src/models/app_secret_plaintext.dart create mode 100644 lib/src/models/apps_list.dart create mode 100644 lib/src/models/oauth2_approve.dart create mode 100644 lib/src/models/oauth2_authorize.dart create mode 100644 lib/src/models/oauth2_device_authorization.dart create mode 100644 lib/src/models/oauth2_grant.dart create mode 100644 lib/src/models/oauth2_organization.dart create mode 100644 lib/src/models/oauth2_organization_list.dart create mode 100644 lib/src/models/oauth2_par.dart create mode 100644 lib/src/models/oauth2_project.dart create mode 100644 lib/src/models/oauth2_project_list.dart create mode 100644 lib/src/models/oauth2_reject.dart create mode 100644 lib/src/models/oauth2_token.dart create mode 100644 lib/src/mqtt.dart create mode 100644 lib/src/mqtt_browser.dart create mode 100644 lib/src/mqtt_foreground.dart create mode 100644 lib/src/mqtt_io.dart create mode 100644 lib/src/mqtt_message.dart create mode 100644 lib/src/mqtt_native.dart create mode 100644 lib/topic.dart create mode 100644 test/services/apps_test.dart create mode 100644 test/services/oauth2_test.dart create mode 100644 test/src/models/account_test.dart create mode 100644 test/src/models/app_key_list_test.dart create mode 100644 test/src/models/app_key_test.dart create mode 100644 test/src/models/app_scope_list_test.dart create mode 100644 test/src/models/app_scope_test.dart create mode 100644 test/src/models/app_secret_list_test.dart create mode 100644 test/src/models/app_secret_plaintext_test.dart create mode 100644 test/src/models/app_secret_test.dart create mode 100644 test/src/models/app_test.dart create mode 100644 test/src/models/apps_list_test.dart create mode 100644 test/src/models/oauth2_approve_test.dart create mode 100644 test/src/models/oauth2_authorize_test.dart create mode 100644 test/src/models/oauth2_device_authorization_test.dart create mode 100644 test/src/models/oauth2_grant_test.dart create mode 100644 test/src/models/oauth2_organization_list_test.dart create mode 100644 test/src/models/oauth2_organization_test.dart create mode 100644 test/src/models/oauth2_par_test.dart create mode 100644 test/src/models/oauth2_project_list_test.dart create mode 100644 test/src/models/oauth2_project_test.dart create mode 100644 test/src/models/oauth2_reject_test.dart create mode 100644 test/src/models/oauth2_token_test.dart create mode 100644 test/topic_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 1344896b..547ce7c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change Log +## 27.1.0-rc.0 + +* Added: `Apps` service to manage OAuth2 apps, keys, secrets, and installations +* Added: `Oauth2` service for authorization, consent, device, PAR, and token flows +* Added: `Push` service for MQTT realtime push with iOS background delivery +* Added: `Topic` builder and a native `android` module for push +* Added: `Client.setPushEndpoint()` and `Client.setPushClientId()` +* Added: `Avatars.updatePhoto()` and `Avatars.deletePhoto()` methods +* Added: `App`, `Oauth2*`, and `Account` models +* Added: `webflow` to the `OAuthProvider` enum + ## 27.0.0 * Breaking: removed `Account.listLogs` and the `Log`, `LogList` models diff --git a/README.md b/README.md index bbc066a7..000ae1df 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^27.0.0 + appwrite: ^27.1.0-rc.0 ``` You can install packages from the command line: @@ -28,6 +28,58 @@ You can install packages from the command line: flutter pub add appwrite ``` +### Push on Android + +`Push` includes a native Android plugin, so the SDK needs Android 7.0 (API 24) or later: apps +with a lower `minSdk` fail to build until they raise it. `flutter_local_notifications` also needs +core library desugaring. Add both to `android/app/build.gradle.kts` (desugaring is configured when +the app is assembled, so a plugin cannot apply it for you): + +```kotlin +android { + defaultConfig { + minSdk = 24 + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") +} +``` + +A subscription with `background: true` keeps delivering after the app is backgrounded, killed or +the device restarts, until it is unsubscribed or `push.close()` is called (do this on sign-out). +The plugin saves the subscription, and a scheduled job and alarm wake the app every 15 to 60 +seconds to reconnect; the broker replays what was sent in between (`retry: true`). Messages no +in-app callback receives are posted as notifications that open the app. It reconnects with the +credential saved at subscribe time, so use a session rather than a short-lived JWT. + +On Android 13 and later, notifications only appear once the user grants the +`POST_NOTIFICATIONS` runtime permission. Without it, the subscription still delivers to your +callback but posts no notification, so ask before subscribing, for example with +`flutter_local_notifications`: + +```dart +await FlutterLocalNotificationsPlugin() + .resolvePlatformSpecificImplementation() + ?.requestNotificationsPermission(); + +final sub = await push.subscribe('news', (message) => print(message.data), + background: true, title: 'News'); + +// Optional: immediate delivery even after a kill and during Doze, with a quiet ongoing +// notification (call while the app is in the foreground). +await push.setForeground(true); +``` + +Foreground mode runs a `remoteMessaging` foreground service, which Google Play asks apps to +declare in the Play Console. Apps that never enable it can remove the service from their merged +manifest with `tools:node="remove"` on `io.appwrite.services.PushService` and +`android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING`. + ## Getting Started @@ -38,6 +90,8 @@ From the options, choose to add a new **Flutter** platform and add your app cred If you are building your Flutter application for multiple devices, you have to follow this process for each different device. +> On Android, iOS and macOS, call `createOAuth2Session` without the `success` and `failure` URLs. The SDK only returns to your app through the `appwrite-callback-[PROJECT_ID]` scheme, and only the default redirect carries the new session with it. A custom URL, such as an https App Link, makes the call fail (for example with `PlatformException(CANCELED)`) even when the login itself succeeded. Await the returned `Future` and navigate from your Dart code instead. + ### Android For **Android** first add your app name and package name, Your package name is generally the **applicationId** in your app-level build.gradle file. By registering your new app platform, you are allowing your app to communicate with the Appwrite API. diff --git a/android/.editorconfig b/android/.editorconfig new file mode 100644 index 00000000..f0895a33 --- /dev/null +++ b/android/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*.{kt,kts}] +ktlint_code_style = ktlint_official +ktlint_standard_annotation = disabled +ktlint_standard_argument-list-wrapping = disabled +ktlint_standard_blank-line-before-declaration = disabled +ktlint_standard_blank-line-between-when-conditions = disabled +ktlint_standard_chain-method-continuation = disabled +ktlint_standard_class-signature = disabled +ktlint_standard_function-expression-body = disabled +ktlint_standard_function-signature = disabled +ktlint_standard_function-start-of-body-spacing = disabled +ktlint_standard_if-else-bracing = disabled +ktlint_standard_if-else-wrapping = disabled +ktlint_standard_max-line-length = disabled +ktlint_standard_multiline-expression-wrapping = disabled +ktlint_standard_multiline-if-else = disabled +ktlint_standard_no-blank-line-before-rbrace = disabled +ktlint_standard_no-blank-line-in-list = disabled +ktlint_standard_no-empty-first-line-in-class-body = disabled +ktlint_standard_no-line-break-before-assignment = disabled +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_parameter-list-wrapping = disabled +ktlint_standard_spacing-between-declarations-with-annotations = disabled +ktlint_standard_spacing-between-declarations-with-comments = disabled +ktlint_standard_string-template = disabled +ktlint_standard_trailing-comma-on-call-site = disabled +ktlint_standard_trailing-comma-on-declaration-site = disabled +ktlint_standard_when-entry-bracing = disabled +ktlint_standard_wrapping = disabled + +[**/Channel.kt] +# Marker types intentionally use leading underscores to distinguish channel states. +ktlint_standard_class-naming = disabled + +[**/models/*.kt] +# Model imports follow schema property order so generated declarations stay deterministic. +ktlint_standard_import-ordering = disabled diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 00000000..47df6fdf --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,56 @@ +// The native half of Push on Android: background delivery that survives the process being +// killed, a reboot and an app update, shared with the Appwrite Android SDK. +group = "io.appwrite.flutter" +version = "27.1.0-rc.0" + +buildscript { + ext.kotlin_version = "2.1.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.7.3") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" +apply plugin: "kotlin-android" + +android { + namespace = "io.appwrite.flutter" + compileSdk = 35 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + sourceSets { + main.java.srcDirs += "src/main/kotlin" + } + + defaultConfig { + minSdk = 24 + // R8 rules for the bundled MQTT client, applied to the app. + consumerProguardFiles("consumer-rules.pro") + } +} + +dependencies { + implementation("com.hivemq:hivemq-mqtt-client-shaded:1.3.6") + implementation("androidx.core:core-ktx:1.13.1") +} diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro new file mode 100644 index 00000000..04d7db2c --- /dev/null +++ b/android/consumer-rules.pro @@ -0,0 +1,27 @@ +# Push: rules applied to apps that shrink with R8. +# +# The shaded HiveMQ MQTT client relocates Netty and JCTools under +# com.hivemq.client.internal.shaded. Netty references optional classes that are never loaded +# on Android: native transports, the HTTP/WebSocket codecs, proxy handlers, alternative TLS +# providers (tcnative, BouncyCastle, Conscrypt, Jetty ALPN) and logging backends. +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.epoll.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.kqueue.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.codec.http.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.proxy.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.internal.tcnative.** +-dontwarn org.bouncycastle.** +-dontwarn org.conscrypt.** +-dontwarn org.eclipse.jetty.** +-dontwarn org.apache.log4j.** +-dontwarn org.apache.logging.log4j.** +-dontwarn org.slf4j.** +-dontwarn reactor.blockhound.** + +# Netty and JCTools reach their own fields by name, through atomic field updaters and Unsafe offsets. +-keepclassmembernames class com.hivemq.client.internal.shaded.io.netty.** { ; } +-keepclassmembers class com.hivemq.client.internal.shaded.org.jctools.** { ; } + +# Netty's leak detector looks these methods up by name when its classes load. +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AbstractByteBufAllocator { *** toLeakAwareBuffer(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AdvancedLeakAwareByteBuf { *** recordLeakNonRefCountingOperation(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.util.ReferenceCountUtil { *** touch(...); } diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 00000000..137b5997 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'appwrite' diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..44f894ed --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt new file mode 100644 index 00000000..81b0d30e --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt @@ -0,0 +1,6 @@ +package io.appwrite.exceptions + +/** A push error. When the broker explained a refusal or a disconnect, that is its message. */ +class AppwriteException( + override val message: String? = null, +) : Exception(message) diff --git a/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt new file mode 100644 index 00000000..c68a60c6 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt @@ -0,0 +1,108 @@ +package io.appwrite.flutter + +import android.os.Handler +import android.os.Looper +import io.appwrite.services.PushBridge +import io.appwrite.services.PushMessage +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +/** + * The Flutter side of [PushBridge]: the SDK's `Push` hosts its background subscriptions here on + * Android over a method channel, and receives their messages and errors over an event channel. + */ +class AppwritePushPlugin : + FlutterPlugin, + MethodChannel.MethodCallHandler, + EventChannel.StreamHandler { + private val main = Handler(Looper.getMainLooper()) + private var methods: MethodChannel? = null + private var events: EventChannel? = null + private var sink: EventChannel.EventSink? = null + private var bridge: PushBridge? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + bridge = PushBridge( + binding.applicationContext, + object : PushBridge.Events { + override fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) = send( + mapOf( + "type" to "message", + "id" to subscriptionId, + "topic" to message.topic, + "payload" to message.payload, + "qos" to message.qos, + "ackToken" to ackToken, + ), + ) + + override fun onError(message: String) = send(mapOf("type" to "error", "message" to message)) + }, + ) + methods = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL).also { it.setMethodCallHandler(this) } + events = EventChannel(binding.binaryMessenger, EVENT_CHANNEL).also { it.setStreamHandler(this) } + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + methods?.setMethodCallHandler(null) + events?.setStreamHandler(null) + methods = null + events = null + sink = null + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + val bridge = bridge ?: return result.error(ERROR_CODE, "Push plugin is not attached", null) + try { + if (call.method == "host") { + // Replies once the connection is up and every filter is subscribed, or with why not. + bridge.host(call.argument("config")!!, call.argument("subscriptions")!!) { error -> + main.post { + if (error == null) { + result.success(null) + } else { + result.error(ERROR_CODE, error, null) + } + } + } + return + } + result.success( + when (call.method) { + "ack" -> bridge.ack(call.argument("token")!!).let { null } + "release" -> bridge.release().let { null } + "stop" -> bridge.stop().let { null } + "setForeground" -> bridge.setForeground(call.argument("enabled") == true).let { null } + "hasSaved" -> bridge.hasSaved() + "resume" -> bridge.resume().let { null } + "setErrorCallback" -> bridge.setErrorCallback(call.argument("registered") == true) + "defaultClientId" -> bridge.defaultClientId(call.argument("authMethod")!!, call.argument("credential")!!) + else -> return result.notImplemented() + }, + ) + } catch (e: Exception) { + result.error(ERROR_CODE, e.message, null) + } + } + + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + sink = events + } + + override fun onCancel(arguments: Any?) { + sink = null + } + + // The bridge calls back on background threads; event sinks must be used on the main thread. + private fun send(event: Map) { + main.post { sink?.success(event) } + } + + private companion object { + const val METHOD_CHANNEL = "appwrite.push" + const val EVENT_CHANNEL = "appwrite.push/events" + const val ERROR_CODE = "appwrite_push" + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBackground.kt b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt new file mode 100644 index 00000000..52517344 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt @@ -0,0 +1,1009 @@ +package io.appwrite.services + +import android.app.AlarmManager +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.job.JobInfo +import android.app.job.JobScheduler +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.Network +import android.os.Build +import android.os.PowerManager +import android.os.SystemClock +import android.util.AtomicFile +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.hivemq.client.mqtt.MqttGlobalPublishFilter +import com.hivemq.client.mqtt.datatypes.MqttQos +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.util.UUID +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger + +private const val LOG_TAG = "AppwritePush" + +/** A background subscription saved across restarts: its filter, QoS choice and notification title. */ +internal data class PushEntry( + val filter: String, + val retry: Boolean, + val title: String?, +) + +/** + * The adaptive heartbeat: its interval, the current streak of failed heartbeats, and when the + * interval last shrank (wall-clock ms, as it must survive reboots). + */ +internal data class PushHeartbeat( + val intervalMs: Long, + val failures: Int = 0, + val shrunkAt: Long = 0L, +) + +/** + * The process-wide host of the background push connection, modelled on how socket push + * services survive on Android without keeping a service alive. + * + * The background subscriptions and their connection config are saved to private storage (see + * [PushStore]), so delivery survives the process being killed, a reboot and an app update. A + * job ([PushJobService]) that reschedules itself on every run, backed by an alarm + * ([PushAlarmReceiver]), wakes the process every 15 seconds (60 when the app may use exact + * alarms or is exempt from battery optimisation). Each run holds a short wakelock and + * reconnects when the connection is gone or the default network changed, sends a heartbeat + * when one is due, and re-arms the job. While the process is alive between runs the socket + * stays open and messages arrive immediately; while it is dead the broker keeps the backlog + * for this client id and replays it when the next run subscribes again. + * + * With foreground mode enabled ([Push.setForeground]) a foreground service ([PushService]) also keeps + * the process at foreground priority, so delivery is immediate after a kill and during Doze. + * + * Messages go to the live in-app callbacks that match them. When none match (the process was + * started in the background), a declared [PushReceiver] gets the message, and a notification + * is posted unless it returns true. + */ +internal object PushBackground { + const val CHANNEL_ID = "appwrite-push" + const val NOTIFICATION_ID = 1911 + const val ACTION_TICK = "io.appwrite.push.TICK" + const val ACTION_MESSAGE = "io.appwrite.push.MESSAGE" + const val NOTIFICATION_ICON = "io.appwrite.push.notification_icon" + const val EXTRA_TOPIC = "io.appwrite.push.TOPIC" + const val EXTRA_PAYLOAD = "io.appwrite.push.PAYLOAD" + + private const val SERVICE_CHANNEL_ID = "appwrite-push-service" + private const val JOB_ID = 0x50555348 + private const val INTERVAL_MS = 15_000L + private const val PRIVILEGED_INTERVAL_MS = 60_000L + private const val RESTART_DELAY_MS = 3_000L + // An upper bound covering a run's connect (20 s) and its requests (10 s each); the wakelock is + // released as soon as the run finishes. + private const val WAKE_LOCK_MS = 60_000L + private const val KEEP_ALIVE_SECONDS = 300 + + // The heartbeat interval: below the broker's 1.5 x keep-alive expiry, measured on a clock that + // counts deep sleep. Networks that drop idle connections sooner (carrier NATs) make heartbeats + // fail; after HEARTBEAT_FAILURES in a row the interval shrinks by a quarter, down to + // MIN_HEARTBEAT_MS, and returns to the default HEARTBEAT_RESET_MS after the last shrink, in + // case the device moved to a better network. + const val HEARTBEAT_MS = 180_000L + private const val MIN_HEARTBEAT_MS = 60_000L + private const val HEARTBEAT_FAILURES = 3 + private const val HEARTBEAT_RESET_MS = 3 * 24 * 60 * 60 * 1_000L + private const val REQUEST_TIMEOUT_SECONDS = 10L + private const val CONNECT_TIMEOUT_SECONDS = 20L + + // How long a message waits for a listener that acknowledges it itself (the React Native and + // Flutter bridges, once their callback has run) before it is acknowledged anyway, so one stuck + // callback cannot hold back the acknowledgements after it. + private const val ACK_TIMEOUT_SECONDS = 10L + + // Unsubscribing a filter nothing subscribes to is a harmless round trip the broker always + // acknowledges, so it proves the connection is alive. The broker ignores client PUBLISHes + // without a PUBACK, so a publish cannot serve as the heartbeat. + private const val HEARTBEAT_FILTER = "\$heartbeat" + + @Volatile + var channelName: String = "Notifications" + + @Volatile + var ongoingTitle: String = "Appwrite" + + // Reports errors to the Push instance that hosts its subscriptions here. Returns whether the + // app's onError received the error (false when it registered none). + @Volatile + var errorHandler: ((Throwable) -> Boolean)? = null + + @Volatile + var serviceRunning = false + + // Whether a refused service start was reported, so a job that retries it every run does not + // report the same failure every 15 seconds. + @Volatile + private var serviceStartReported = false + + // The live in-app subscriptions hosted here, each with its callback. Empty after the process + // was restarted in the background, until the app subscribes again. + val listeners = CopyOnWriteArrayList() + + // Guards the saved state below and its copy on disk. + private val lock = Any() + private var loaded = false + private var config: PushConfig? = null + + // Background subscriptions saved by an earlier run that no live subscription has taken over. + private var saved: List = emptyList() + + // Every MQTT call runs on this thread, in order, so the connection state below needs no lock. + private val worker = Executors.newSingleThreadScheduledExecutor { runnable -> + Thread(runnable, "AppwritePushBackground").apply { isDaemon = true } + } + private var mqtt: Mqtt5AsyncClient? = null + private var connectedConfig: PushConfig? = null + private var connectedNetwork: Network? = null + private var lastHeartbeat = 0L + private var heartbeatState: PushHeartbeat? = null + private val subscribed = mutableMapOf() + private var networkCallback: ConnectivityManager.NetworkCallback? = null + + // Worker thread only. While a caller waits for a converge (host with a completion), its + // failures go to that caller, which reports them, instead of onError. + private var waiting = false + private var failure: Throwable? = null + + /** + * Host [newListeners] (the app's live subscriptions) on the background connection with + * [newConfig], save the background ones, and arm the scheduled wake-ups. Saved subscriptions + * from an earlier run stay unless a live subscription on the same filter takes them over + * (with background on or off), or [newConfig] is for another client id (another user), whose + * saved subscriptions are dropped. + * + * With [done], it is called once the connection is up and every filter is subscribed (SUBACK), + * or with the failure, which is then not reported to onError: the caller reports it. + */ + fun host( + context: Context, + newConfig: PushConfig, + newListeners: List, + done: ((Throwable?) -> Unit)? = null, + ) { + val app = context.applicationContext + synchronized(lock) { + load(app) + if (config != null && config?.clientId != newConfig.clientId) { + saved = emptyList() + } + // A live subscription on a saved filter takes it over, whether or not it wants background: + // one that turned background off, or is later unsubscribed, must not leave the saved + // entry delivering in the background. + saved = saved.filter { entry -> newListeners.none { entry.filter in it.topics } } + config = newConfig + listeners.clear() + listeners.addAll(newListeners) + persist(app) + } + activate(app, done) + } + + /** + * Stop hosting the app's live subscriptions, keeping the saved ones from an earlier run. + * Shuts down when none remain. + */ + fun release(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + listeners.clear() + persist(app) + isActive() + } + if (active) { + worker.execute { converge(app, heartbeat = false) } + } else { + shutdown(app) + } + } + + /** Stop background delivery completely and forget every saved subscription. */ + fun stop(context: Context) { + val app = context.applicationContext + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = true + PushStore.clearState(app) + } + shutdown(app) + } + + /** Whether subscriptions saved by an earlier run are still delivered in the background. */ + fun hasSaved(context: Context): Boolean = synchronized(lock) { + load(context.applicationContext) + saved.isNotEmpty() + } + + /** Persist the foreground-mode choice and start or stop the foreground service to match. */ + fun setForeground(context: Context, enabled: Boolean) { + val app = context.applicationContext + PushStore.setForeground(app, enabled) + serviceStartReported = false + ensureService(app) + } + + /** Whether the foreground service should run: foreground mode is enabled and there is work to do. */ + fun wantsService(context: Context): Boolean { + val app = context.applicationContext + return PushStore.foreground(app) && synchronized(lock) { + load(app) + isActive() + } + } + + /** Resume saved background delivery when the app starts, without waiting for the next run. */ + fun resume(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + tick(app) {} + } + } + + /** + * One scheduled run: under a wakelock, reconnect if needed, send a heartbeat when one is due, + * re-arm the next run, and call [done] once finished. Shuts down when nothing is saved. + */ + fun tick(context: Context, done: () -> Unit) { + val app = context.applicationContext + val wakeLock = acquireWakeLock(app) + worker.execute { + try { + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + // Arm the next run first, so a run cut short (killed, or a slow broker outlasting + // the wakelock) still leaves the chain armed. A refused credential in converge() + // shuts down, cancelling it again. + schedule(app, INTERVAL_MS) + ensureService(app) + registerNetworkCallback(app) + converge(app, heartbeat = true) + } else { + shutdown(app) + } + } catch (e: Exception) { + report(e) + } finally { + releaseWakeLock(wakeLock) + done() + } + } + } + + /** Run once more shortly after the task was removed, so an OEM kill that follows is undone. */ + fun scheduleRestart(context: Context) { + schedule(context.applicationContext, RESTART_DELAY_MS, jobToo = false) + } + + /** + * Forget everything held in memory, as the process dying does, keeping only what is saved. + * For tests of what happens after the app's process was killed. + */ + internal fun dropProcessState(context: Context) { + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = false + } + errorHandler = null + unregisterNetworkCallback(context.applicationContext) + worker.submit { disconnect() }.get() + } + + /** Report an error to the hosting Push instance's onError; logged when there is none. */ + fun report(error: Throwable): Boolean { + val delivered = try { + errorHandler?.invoke(error) ?: false + } catch (callbackError: Exception) { + Log.e(LOG_TAG, "Push onError threw", callbackError) + true + } + if (!delivered) { + Log.e(LOG_TAG, "Push background error", error) + } + return delivered + } + + // Must hold [lock]. + private fun load(context: Context) { + if (loaded) { + return + } + loaded = true + val state = PushStore.loadState(context) ?: return + config = state.first + saved = state.second + } + + // Must hold [lock]. + private fun isActive(): Boolean = config != null && (saved.isNotEmpty() || listeners.isNotEmpty()) + + // Must hold [lock]. Every background subscription, live or saved, one per filter and title. + // Subscriptions sharing a filter and title are saved once, with QoS 1 when any of them wants it. + private fun entries(): List = + (saved + listeners.filter { it.background }.flatMap { listener -> listener.topics.map { PushEntry(it, listener.retry, listener.title) } }) + .groupBy { it.filter to it.title } + .map { (key, group) -> PushEntry(key.first, group.any { it.retry }, key.second) } + + // Must hold [lock]. + private fun persist(context: Context) { + val current = config + val entries = entries() + if (current == null || entries.isEmpty()) { + PushStore.clearState(context) + } else { + PushStore.saveState(context, current, entries) + } + } + + // Must hold [lock]. The broker subscriptions wanted, at the highest QoS any subscription on a + // filter asks for. + private fun wanted(): Map { + val qos = linkedMapOf() + fun want(filter: String, retry: Boolean) { + if (retry) { + qos[filter] = MqttQos.AT_LEAST_ONCE + } else if (filter !in qos) { + qos[filter] = MqttQos.AT_MOST_ONCE + } + } + for (listener in listeners) { + listener.topics.forEach { want(it, listener.retry) } + } + saved.forEach { want(it.filter, it.retry) } + return qos + } + + private fun activate(context: Context, done: ((Throwable?) -> Unit)? = null) { + registerNetworkCallback(context) + schedule(context, INTERVAL_MS) + ensureService(context) + worker.execute { converge(context, heartbeat = false, done) } + } + + private fun shutdown(context: Context) { + cancelSchedule(context) + unregisterNetworkCallback(context) + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + worker.execute { disconnect() } + } + + // Worker thread only. Bring the connection to the wanted state: reconnect when the config or + // the default network changed or a due heartbeat fails, then subscribe and unsubscribe the + // difference. With [done], failures go to it (see [waiting]) instead of onError. + private fun converge(context: Context, heartbeat: Boolean, done: ((Throwable?) -> Unit)? = null) { + waiting = done != null + failure = null + try { + convergeOnce(context, heartbeat) + } catch (e: Exception) { + fail(e) + } finally { + waiting = false + done?.invoke(failure) + } + } + + // Worker thread only. Record a failure for the waiting caller, or report it. + private fun fail(error: Throwable) { + if (failure == null) { + failure = error + } + if (!waiting) { + report(error) + } + } + + private fun convergeOnce(context: Context, heartbeat: Boolean) { + val (current, wanted) = synchronized(lock) { config to wanted() } + if (current == null || wanted.isEmpty()) { + disconnect() + return + } + var client = mqtt + if (client != null && (current != connectedConfig || networkChanged(context))) { + disconnect() + client = null + } + if (client != null && heartbeat && SystemClock.elapsedRealtime() - lastHeartbeat >= heartbeatInterval(context)) { + val alive = sendHeartbeat(client) + recordHeartbeat(context, alive) + if (alive) { + lastHeartbeat = SystemClock.elapsedRealtime() + } else { + disconnect() + client = null + } + } + if (client == null) { + client = connect(context, current) ?: return + } + for (filter in subscribed.keys - wanted.keys) { + request { client.unsubscribeWith().topicFilter(filter).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) } + subscribed.remove(filter) + } + for ((filter, qos) in wanted) { + if (subscribed[filter] != qos && subscribe(client, filter, qos)) { + subscribed[filter] = qos + } + } + } + + // Worker thread only. Connect with [config], or report why not and return null. A refused + // credential stops background delivery: retrying it would only be refused again. + private fun connect(context: Context, config: PushConfig): Mqtt5AsyncClient? { + // A failed first connect of a waited-for converge goes to the waiting caller only. + val quiet = waiting + val connected = AtomicBoolean(false) + val client = buildPushClient( + config.copy(keepAlive = KEEP_ALIVE_SECONDS), + onError = { error -> + if (!quiet || connected.get()) { + report(error) + } + }, + onAuthRefused = { error -> worker.execute { refused(context, error) } }, + ) + // Registered before connecting, so the backlog the broker replays right after each + // SUBSCRIBE reaches the app however the subscription was made (including the ones the + // client restores itself after an automatic reconnect). Acknowledged by hand, once the + // message was delivered (see [deliver]). + client.publishes(MqttGlobalPublishFilter.ALL, { publish -> deliver(context, publish) }, true) + try { + client.sendPushConnect(config.copy(keepAlive = KEEP_ALIVE_SECONDS), CONNECT_TIMEOUT_SECONDS) + } catch (e: Exception) { + val cause = (e as? ExecutionException)?.cause ?: e + client.disconnect() + val error = connectError(cause) + when { + isAuthRefusal(cause) -> refused(context, error) + waiting -> fail(error) + // A network failure already reached onError through the client's disconnect + // listener; a refused CONNECT and a timeout did not. + cause is Mqtt5ConnAckException || cause is TimeoutException -> report(error) + } + return null + } + connected.set(true) + mqtt = client + connectedConfig = config + connectedNetwork = activeNetwork(context) + lastHeartbeat = SystemClock.elapsedRealtime() + subscribed.clear() + return client + } + + // Worker thread only. + private fun subscribe(client: Mqtt5AsyncClient, filter: String, qos: MqttQos): Boolean = request { + val subAck = client.subscribeWith().topicFilter(filter).qos(qos).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + val code = subAck.reasonCodes.firstOrNull { it.isError } + if (code != null) { + throw AppwriteException( + subAck.reasonString.map { it.toString() }.orElse("Subscribing to $filter was refused (reason $code)"), + ) + } + } + + // Worker thread only. The current heartbeat interval, back at the default once a shrink is + // old enough. + private fun heartbeatInterval(context: Context): Long { + val state = heartbeatState ?: PushStore.heartbeat(context).also { heartbeatState = it } + if (state.intervalMs < HEARTBEAT_MS && System.currentTimeMillis() - state.shrunkAt >= HEARTBEAT_RESET_MS) { + saveHeartbeat(context, PushHeartbeat(HEARTBEAT_MS)) + return HEARTBEAT_MS + } + return state.intervalMs + } + + // Worker thread only. Count a failed heartbeat (a connection the network dropped silently), + // shrinking the interval after HEARTBEAT_FAILURES in a row; a delivered one ends the streak. + private fun recordHeartbeat(context: Context, alive: Boolean) { + val state = heartbeatState ?: PushStore.heartbeat(context) + val next = when { + alive -> state.copy(failures = 0) + state.failures + 1 < HEARTBEAT_FAILURES -> state.copy(failures = state.failures + 1) + else -> PushHeartbeat(maxOf(MIN_HEARTBEAT_MS, state.intervalMs * 3 / 4), 0, System.currentTimeMillis()) + } + if (next != state) { + saveHeartbeat(context, next) + } + } + + private fun saveHeartbeat(context: Context, state: PushHeartbeat) { + heartbeatState = state + PushStore.setHeartbeat(context, state) + } + + // Worker thread only. + private fun sendHeartbeat(client: Mqtt5AsyncClient): Boolean = try { + client.unsubscribeWith().topicFilter(HEARTBEAT_FILTER).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + true + } catch (e: Exception) { + false + } + + // Run a broker request, recording or reporting its failure. Returns whether it succeeded. + private fun request(block: () -> Unit): Boolean = try { + block() + true + } catch (e: Exception) { + fail((e as? ExecutionException)?.cause ?: e) + false + } + + // Worker thread only. + private fun disconnect() { + mqtt?.disconnect() + mqtt = null + connectedConfig = null + connectedNetwork = null + subscribed.clear() + } + + // Worker thread only. The broker refused the credential: report it and stop. With no onError + // registered the message is also saved, and the next onError registration receives it. A + // waiting caller receives it instead. + private fun refused(context: Context, error: Throwable) { + if (waiting) { + fail(error) + } else if (!report(error)) { + PushStore.setStoppedError(context, error.message ?: "Push connection refused") + } + stop(context) + } + + // Deliver a message, then acknowledge it: right away, or once every listener that acknowledges + // messages itself has done so (at most ACK_TIMEOUT_SECONDS later). + private fun deliver(context: Context, publish: Mqtt5Publish) { + val acknowledged = AtomicBoolean(false) + val acknowledge = { + if (acknowledged.compareAndSet(false, true)) { + runCatching { publish.acknowledge() } + } + } + val pending = AtomicInteger(1) + val settle = { + if (pending.decrementAndGet() == 0) { + acknowledge() + } + } + try { + deliverMessage(context, publish.toPushMessage()) { + pending.incrementAndGet() + val once = AtomicBoolean(false) + val ack: () -> Unit = { + if (once.compareAndSet(false, true)) { + settle() + } + } + ack + } + } finally { + settle() + } + if (!acknowledged.get()) { + worker.schedule({ acknowledge() }, ACK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + } + } + + // Deliver a message to the matching live callbacks; with none, to the declared PushReceiver + // and/or a notification per saved subscription that matches it. [deferAck] hands a listener + // that acknowledges messages itself its acknowledgement. + private fun deliverMessage(context: Context, message: PushMessage, deferAck: () -> () -> Unit) { + val matching = listeners.filter { listener -> listener.topics.any { matchesTopic(it, message.topic) } } + // Saved background subscriptions no live one has taken over; they deliver even when a live + // foreground-only subscription on an overlapping filter received the message too. + val entries = synchronized(lock) { saved }.filter { matchesTopic(it.filter, message.topic) } + if (matching.isEmpty() && entries.isEmpty()) { + return + } + for (listener in matching) { + try { + val acknowledging = listener.acknowledgingCallback + if (acknowledging != null) { + acknowledging(message, deferAck()) + } else { + listener.callback(message) + } + } catch (e: Exception) { + report(e) + } + } + val wakeLock = acquireWakeLock(context) + try { + // The app's PushReceiver gets only messages no live callback received. + val handled = matching.isEmpty() && deliverToReceivers(context, message) + val titles = matching.filter { it.background }.map { it.title ?: message.topic } + + if (handled) emptyList() else entries.map { it.title ?: message.topic } + titles.distinct().forEach { notify(context, message, it) } + } finally { + releaseWakeLock(wakeLock) + } + } + + // Call every PushReceiver the app declares. Returns whether one handled the message. + private fun deliverToReceivers(context: Context, message: PushMessage): Boolean { + val intent = Intent(ACTION_MESSAGE).setPackage(context.packageName) + val receivers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.queryBroadcastReceivers(intent, PackageManager.ResolveInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + context.packageManager.queryBroadcastReceivers(intent, 0) + } + var handled = false + for (info in receivers) { + val name = info.activityInfo?.name ?: continue + try { + val receiver = Class.forName(name, true, context.classLoader).getDeclaredConstructor().newInstance() + if (receiver is PushReceiver && receiver.onMessage(context, message)) { + handled = true + } + } catch (e: Exception) { + report(e) + } + } + return handled + } + + /** Post a notification for [message] that opens the app, with the message in its extras. */ + fun notify(context: Context, message: PushMessage, title: String) { + val manager = NotificationManagerCompat.from(context) + if (!manager.areNotificationsEnabled()) { + return + } + createChannels(context) + val id = 31 * message.hashCode() + title.hashCode() + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setContentTitle(title) + .setContentText(message.data) + .setSmallIcon(notificationIcon(context)) + .setAutoCancel(true) + context.packageManager.getLaunchIntentForPackage(context.packageName)?.let { launch -> + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(EXTRA_TOPIC, message.topic) + .putExtra(EXTRA_PAYLOAD, message.data) + builder.setContentIntent( + PendingIntent.getActivity(context, id, launch, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE), + ) + } + try { + manager.notify(id, builder.build()) + } catch (e: SecurityException) { + // POST_NOTIFICATIONS not granted; nothing to show. + } + } + + /** The ongoing notification the foreground service shows, on its own quiet channel. */ + fun ongoingNotification(context: Context) = NotificationCompat.Builder(context, SERVICE_CHANNEL_ID) + .also { createChannels(context) } + .setContentTitle(ongoingTitle) + .setContentText("Listening for messages") + .setSmallIcon(notificationIcon(context)) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOngoing(true) + .build() + + private fun createChannels(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return + } + val manager = context.getSystemService(NotificationManager::class.java) ?: return + manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH)) + manager.createNotificationChannel( + NotificationChannel(SERVICE_CHANNEL_ID, "Background connection", NotificationManager.IMPORTANCE_LOW), + ) + } + + // The icon named by the app's ``, else a + // generic one. + private fun notificationIcon(context: Context): Int { + val metaData = runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.getApplicationInfo(context.packageName, PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong())) + } else { + @Suppress("DEPRECATION") + context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) + }.metaData + }.getOrNull() + return metaData?.getInt(NOTIFICATION_ICON, 0)?.takeIf { it != 0 } ?: android.R.drawable.stat_notify_chat + } + + private fun ensureService(context: Context) { + if (!wantsService(context)) { + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + return + } + if (serviceRunning) { + return + } + try { + ContextCompat.startForegroundService(context, Intent(context, PushService::class.java)) + } catch (e: Exception) { + // Android 12+ refuses a foreground-service start from the background; the scheduled + // runs keep delivering, and the next start from the foreground succeeds. + if (!serviceStartReported) { + serviceStartReported = true + report(e) + } + } + } + + // Arm the next run in [delayMs]: the job, and an alarm just after it in case the job is late. + private fun schedule(context: Context, delayMs: Long, jobToo: Boolean = true) { + val interval = if (delayMs == INTERVAL_MS && privileged(context)) PRIVILEGED_INTERVAL_MS else delayMs + if (jobToo) { + try { + val job = JobInfo.Builder(JOB_ID, ComponentName(context, PushJobService::class.java)) + .setMinimumLatency(interval) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) + .setPersisted(true) + .build() + context.getSystemService(JobScheduler::class.java)?.schedule(job) + } catch (e: Exception) { + report(e) + } + } + val alarms = context.getSystemService(AlarmManager::class.java) ?: return + val at = SystemClock.elapsedRealtime() + interval + 1_000L + val intent = tickIntent(context) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarms.canScheduleExactAlarms()) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } else { + alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } catch (e: SecurityException) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } + + private fun cancelSchedule(context: Context) { + context.getSystemService(JobScheduler::class.java)?.cancel(JOB_ID) + context.getSystemService(AlarmManager::class.java)?.cancel(tickIntent(context)) + } + + private fun tickIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( + context, + 0, + Intent(context, PushAlarmReceiver::class.java).setAction(ACTION_TICK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + // Allowed exact alarms or exempt from battery optimisation: the alarm is reliable, so the + // runs can be spaced further apart. + private fun privileged(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.S || + context.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true || + context.getSystemService(PowerManager::class.java)?.isIgnoringBatteryOptimizations(context.packageName) == true + + private fun activeNetwork(context: Context): Network? = + runCatching { context.getSystemService(ConnectivityManager::class.java)?.activeNetwork }.getOrNull() + + private fun networkChanged(context: Context): Boolean { + val now = activeNetwork(context) + return now != null && connectedNetwork != null && now != connectedNetwork + } + + // Reconnect as soon as the default network changes (e.g. from cellular to Wi-Fi) while the + // process is alive, instead of waiting for the next run to notice. + private fun registerNetworkCallback(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + return + } + synchronized(lock) { + if (networkCallback != null) { + return + } + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + worker.execute { + if (mqtt != null && network != connectedNetwork) { + converge(context, heartbeat = false) + } + } + } + } + try { + context.getSystemService(ConnectivityManager::class.java)?.registerDefaultNetworkCallback(callback) + networkCallback = callback + } catch (e: Exception) { + report(e) + } + } + } + + private fun unregisterNetworkCallback(context: Context) { + val callback = synchronized(lock) { networkCallback.also { networkCallback = null } } ?: return + runCatching { context.getSystemService(ConnectivityManager::class.java)?.unregisterNetworkCallback(callback) } + } + + private fun acquireWakeLock(context: Context): PowerManager.WakeLock? = runCatching { + context.getSystemService(PowerManager::class.java) + ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Appwrite:push") + ?.apply { + setReferenceCounted(false) + acquire(WAKE_LOCK_MS) + } + }.getOrNull() + + private fun releaseWakeLock(wakeLock: PowerManager.WakeLock?) { + runCatching { + if (wakeLock?.isHeld == true) { + wakeLock.release() + } + } + } +} + +/** + * Background push state in the app's no-backup directory, so a restored backup on another + * device never carries this install's id or credential: the saved subscriptions with their + * connection config (cleared when background delivery stops), and the settings that outlive + * it (the install id, the foreground-mode choice, a refusal waiting for onError). + */ +internal object PushStore { + private const val STATE_FILE = "appwrite_push_state.json" + private const val SETTINGS_FILE = "appwrite_push_settings.json" + + fun loadState(context: Context): Pair>? = synchronized(this) { + val json = read(context, STATE_FILE) ?: return null + runCatching { + val config = json.getJSONObject("config").let { + PushConfig( + host = it.getString("host"), + port = it.getInt("port"), + tls = it.getBoolean("tls"), + tlsInsecure = it.getBoolean("tlsInsecure"), + clientId = it.getString("clientId"), + keepAlive = it.getInt("keepAlive"), + authMethod = it.getString("authMethod"), + credential = it.getString("credential"), + project = it.getString("project"), + ) + } + val list = json.getJSONArray("entries") + val entries = (0 until list.length()).map { index -> + val entry = list.getJSONObject(index) + PushEntry( + filter = entry.getString("filter"), + retry = entry.getBoolean("retry"), + title = if (entry.isNull("title")) null else entry.getString("title"), + ) + } + config to entries + }.getOrNull() + } + + fun saveState(context: Context, config: PushConfig, entries: List) = synchronized(this) { + val json = JSONObject() + .put( + "config", + JSONObject() + .put("host", config.host) + .put("port", config.port) + .put("tls", config.tls) + .put("tlsInsecure", config.tlsInsecure) + .put("clientId", config.clientId) + .put("keepAlive", config.keepAlive) + .put("authMethod", config.authMethod) + .put("credential", config.credential) + .put("project", config.project), + ) + .put( + "entries", + JSONArray(entries.map { JSONObject().put("filter", it.filter).put("retry", it.retry).put("title", it.title ?: JSONObject.NULL) }), + ) + write(context, STATE_FILE, json) + } + + fun clearState(context: Context) = synchronized(this) { + file(context, STATE_FILE).delete() + } + + /** A random id for this install, created once, which keeps the broker's replay position. */ + fun installId(context: Context): String = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: JSONObject() + settings.optString("installId").ifEmpty { + val id = UUID.randomUUID().toString() + write(context, SETTINGS_FILE, settings.put("installId", id)) + id + } + } + + fun foreground(context: Context): Boolean = synchronized(this) { + read(context, SETTINGS_FILE)?.optBoolean("foreground", false) ?: false + } + + fun setForeground(context: Context, enabled: Boolean) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("foreground", enabled)) + } + + /** The saved adaptive heartbeat; the default interval until one was saved. */ + fun heartbeat(context: Context): PushHeartbeat = synchronized(this) { + val json = read(context, SETTINGS_FILE)?.optJSONObject("heartbeat") ?: return PushHeartbeat(PushBackground.HEARTBEAT_MS) + PushHeartbeat( + intervalMs = json.optLong("intervalMs", PushBackground.HEARTBEAT_MS), + failures = json.optInt("failures", 0), + shrunkAt = json.optLong("shrunkAt", 0L), + ) + } + + fun setHeartbeat(context: Context, state: PushHeartbeat) = synchronized(this) { + val heartbeat = JSONObject() + .put("intervalMs", state.intervalMs) + .put("failures", state.failures) + .put("shrunkAt", state.shrunkAt) + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("heartbeat", heartbeat)) + } + + fun setStoppedError(context: Context, message: String) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("stoppedError", message)) + } + + /** The refusal that stopped background delivery while no onError was registered, once. */ + fun takeStoppedError(context: Context): String? = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: return null + val message = settings.optString("stoppedError").ifEmpty { return null } + settings.remove("stoppedError") + write(context, SETTINGS_FILE, settings) + message + } + + private fun file(context: Context, name: String) = AtomicFile(File(context.noBackupFilesDir, name)) + + private fun read(context: Context, name: String): JSONObject? = + runCatching { JSONObject(String(file(context, name).readFully(), Charsets.UTF_8)) }.getOrNull() + + private fun write(context: Context, name: String, json: JSONObject) { + val file = file(context, name) + val out = try { + file.startWrite() + } catch (e: IOException) { + Log.e(LOG_TAG, "Could not save push state", e) + return + } + try { + out.write(json.toString().toByteArray(Charsets.UTF_8)) + file.finishWrite(out) + } catch (e: IOException) { + file.failWrite(out) + Log.e(LOG_TAG, "Could not save push state", e) + } + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBridge.kt b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt new file mode 100644 index 00000000..d7b79b5d --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt @@ -0,0 +1,135 @@ +package io.appwrite.services + +import android.content.Context +import android.os.SystemClock +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** + * The contract the React Native and Flutter SDKs use to host their background push + * subscriptions on this Android core, so they get the same delivery as the Android SDK: saved + * subscriptions, scheduled wake-ups after the process dies, notifications, and foreground mode. + * + * Both SDKs pass the same JSON: [host] takes the connection config and every live subscription, + * and each message for a live subscription comes back through [Events.onMessage] with its id and + * an acknowledgement token, which the SDK passes to [ack] once its callback has run (the broker's + * PUBACK waits for it, at most ten seconds). One bridge per process; hosting again replaces the + * live subscriptions. + */ +class PushBridge(context: Context, private val events: Events) { + /** Where messages and errors go; called on a background thread. */ + interface Events { + fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) + + fun onError(message: String) + } + + private val appContext = context.applicationContext + // Acknowledgement token -> (when it was handed out, the acknowledgement). A token the SDK never + // acknowledges (its JS or Dart side was gone) is dropped once the core has acknowledged the + // message anyway, so the map stays bounded. + private val acks = ConcurrentHashMap Unit>>() + + // Whether the app registered onError; without one, errors are logged and a refused + // credential is kept for the next registration. + @Volatile + private var errorCallback = false + + /** + * Host the subscriptions in [subscriptionsJson] on the background connection described by + * [configJson]. + * + * Config: `{"host", "port", "tls", "tlsInsecure", "clientId" (optional; per user and install + * when empty), "authMethod", "credential", "project"}`. Subscriptions: an array of + * `{"id", "topic", "background", "title" (optional), "retry"}`. + * + * [done] is called once the connection is up and every filter is subscribed, or with the + * failure's message; the SDK rejects its subscribe with it and reports it itself. + */ + fun host(configJson: String, subscriptionsJson: String, done: (String?) -> Unit) { + val json = JSONObject(configJson) + val authMethod = json.getString("authMethod") + val credential = json.getString("credential") + val config = PushConfig( + host = json.getString("host"), + port = json.getInt("port"), + tls = json.optBoolean("tls", false), + tlsInsecure = json.optBoolean("tlsInsecure", false), + clientId = json.optString("clientId").ifEmpty { defaultPushClientId(appContext, authMethod, credential) }, + keepAlive = KEEP_ALIVE_SECONDS, + authMethod = authMethod, + credential = credential, + project = json.optString("project"), + ) + val list = JSONArray(subscriptionsJson) + val listeners = (0 until list.length()).map { index -> + val subscription = list.getJSONObject(index) + val id = subscription.getString("id") + PushListener( + topics = setOf(subscription.getString("topic")), + callback = {}, + acknowledgingCallback = { message, ack -> + val token = UUID.randomUUID().toString() + val now = SystemClock.elapsedRealtime() + acks.entries.removeIf { now - it.value.first > STALE_ACK_MS } + acks[token] = now to ack + events.onMessage(id, message, token) + }, + background = subscription.optBoolean("background", false), + title = if (subscription.isNull("title")) null else subscription.optString("title").ifEmpty { null }, + retry = subscription.optBoolean("retry", true), + ) + } + PushBackground.errorHandler = { error -> + if (errorCallback) { + events.onError(error.message ?: error.toString()) + } + errorCallback + } + PushBackground.host(appContext, config, listeners) { error -> + done(error?.let { it.message ?: it.toString() }) + } + } + + /** Acknowledge a message once the SDK's callback for it has run. */ + fun ack(token: String) { + acks.remove(token)?.second?.invoke() + } + + /** Stop hosting the live subscriptions, keeping the ones saved by an earlier run. */ + fun release() = PushBackground.release(appContext) + + /** Stop background delivery and forget every saved subscription (sign-out). */ + fun stop() = PushBackground.stop(appContext) + + /** Run background delivery in a foreground service; saved across restarts. */ + fun setForeground(enabled: Boolean) = PushBackground.setForeground(appContext, enabled) + + /** Whether an earlier run saved background subscriptions that are still delivered. */ + fun hasSaved(): Boolean = PushBackground.hasSaved(appContext) + + /** Resume saved background delivery now instead of at the next scheduled run. */ + fun resume() = PushBackground.resume(appContext) + + /** + * Record whether the app has an onError callback. Returns the refusal that stopped background + * delivery while it had none, once, so the app can deliver it now. + */ + fun setErrorCallback(registered: Boolean): String? { + errorCallback = registered + return if (registered) PushStore.takeStoppedError(appContext) else null + } + + /** The default client id for a credential, so a foreground connection shares its session. */ + fun defaultClientId(authMethod: String, credential: String): String = + defaultPushClientId(appContext, authMethod, credential) + + private companion object { + const val KEEP_ALIVE_SECONDS = 60 + + // Past the core's ten-second acknowledgement cap, after which the message was acknowledged. + const val STALE_ACK_MS = 30_000L + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushCore.kt b/android/src/main/kotlin/io/appwrite/services/PushCore.kt new file mode 100644 index 00000000..20c56242 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushCore.kt @@ -0,0 +1,374 @@ +package io.appwrite.services + +import android.content.Context +import android.os.Build +import android.util.Base64 +import com.hivemq.client.mqtt.MqttClient +import com.hivemq.client.mqtt.datatypes.MqttUtf8String +import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext +import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientConfig +import com.hivemq.client.mqtt.mqtt5.auth.Mqtt5EnhancedAuthMechanism +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5DisconnectException +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5Auth +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5AuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5EnhancedAuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAckReasonCode +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5DisconnectReasonCode +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONObject +import java.security.KeyStore +import java.security.Provider +import java.security.cert.X509Certificate +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ExecutionException +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import javax.net.ssl.ManagerFactoryParameters +import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.TrustManagerFactorySpi +import javax.net.ssl.X509TrustManager + +/** + * A message delivered on a subscribed topic — the MQTT push analog of a realtime event. + */ +data class PushMessage( + val topic: String, + val payload: ByteArray, + val qos: Int, +) { + /** The payload decoded as UTF-8 text, as it was sent. */ + val data: String + get() = String(payload, Charsets.UTF_8) +} + +/** Connection parameters shared between the in-process client and the foreground service. */ +internal data class PushConfig( + val host: String, + val port: Int, + val tls: Boolean, + val tlsInsecure: Boolean, + val clientId: String, + val keepAlive: Int, + val authMethod: String, + val credential: String, + val project: String, +) + +/** + * The userId claim from an Appwrite JWT, used as the default MQTT client id so the + * broker's replay cursor is stable per user. Returns "" when the token is not a decodable JWT + * (e.g. a session secret), so the caller can fall back to the raw credential. + */ +internal fun userIdFromJwt(jwt: String): String { + val parts = jwt.split('.') + if (parts.size < 2) { + return "" + } + return runCatching { + val json = String( + Base64.decode(parts[1], Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING), + Charsets.UTF_8, + ) + JSONObject(json).optString("userId", "") + }.getOrDefault("") +} + +/** The user `id` from an Appwrite session secret, or "" when it is not decodable. */ +internal fun userIdFromSession(session: String): String = runCatching { + val json = String(Base64.decode(session, Base64.DEFAULT), Charsets.UTF_8) + JSONObject(json).optString("id", "") +}.getOrDefault("") + +/** + * The default MQTT client id: one per user and install (`-`, or the install id + * alone when the credential names no user). The broker keeps the replay position per user and + * client id, so each device resumes its own backlog across restarts, and two devices of one user + * do not take over each other's session. + */ +internal fun defaultPushClientId(context: Context, authMethod: String, credential: String): String { + val userId = if (authMethod == "appwrite-session") userIdFromSession(credential) else userIdFromJwt(credential) + val installId = PushStore.installId(context) + return if (userId.isEmpty()) installId else "$userId-$installId" +} + +/** + * Build (but do not connect) an MQTT 5 client from [config]. [onError] receives every connection + * error (a lost connection, a failed automatic reconnect, a broker DISCONNECT) except a refused + * initial CONNECT, which [pushConnect] throws instead. + */ +internal fun buildPushClient( + config: PushConfig, + onConnected: (() -> Unit)? = null, + onDisconnected: (() -> Unit)? = null, + onError: ((Throwable) -> Unit)? = null, + onAuthRefused: ((Throwable) -> Unit)? = null, +): Mqtt5AsyncClient { + // config.clientId is stable per user (see buildConfig), so a reconnect rebuild reuses it + // and resumes the same session. + var builder = MqttClient.builder() + .useMqttVersion5() + .serverHost(config.host) + .serverPort(config.port) + // Recover from an unexpected disconnect (network drop, broker restart) with HiveMQ's + // exponential backoff. A user-initiated disconnect() (see close()) does not trigger it. + // Because clean start is off and the broker resumes the same session, subscriptions and + // the QoS-1 replay cursor persist, so delivery continues without resubscribing (which + // would stack a second per-subscription callback). + .automaticReconnectWithDefaultConfig() + + if (config.clientId.isNotEmpty()) { + builder = builder.identifier(config.clientId) + } + + // Whether this client has connected yet: until it has, a refused CONNECT is final. + val connected = AtomicBoolean(false) + builder = builder.addConnectedListener { + connected.set(true) + onConnected?.invoke() + } + builder = builder.addDisconnectedListener { context -> + // A refused first CONNECT (bad credential, rate limit) is final: stop the automatic + // reconnect so pushConnect fails with the broker's reason instead of retrying forever. + val refused = !connected.get() && context.cause is Mqtt5ConnAckException + // With [onAuthRefused], a credential refused later (a failed automatic reconnect or + // re-auth) is final too, instead of being retried with the same credential forever. + val authRefused = onAuthRefused != null && connected.get() && + context.source != MqttDisconnectSource.USER && isAuthRefusal(context.cause) + if (refused || authRefused) { + context.reconnector.reconnect(false) + } + onDisconnected?.invoke() + if (!refused) { + val error = pushDisconnectError(context) + if (authRefused && error != null) { + // Reported by onAuthRefused, which also stops for good. + onAuthRefused?.invoke(error) + } else { + error?.let { onError?.invoke(it) } + } + } + } + + if (config.tls) { + builder = if (config.tlsInsecure) { + builder.sslConfig() + .trustManagerFactory(PushInsecureTrustManagerFactory) + .hostnameVerifier { _, _ -> true } + .applySslConfig() + } else { + builder.sslWithDefaultConfig() + } + } + + return builder.buildAsync() +} + +/** + * Connect with Appwrite enhanced auth; blocks until CONNACK. Throws an + * [AppwriteException] on failure, whose message is the broker's MQTT 5 + * Reason String when it refused the CONNECT with one. + */ +internal fun Mqtt5AsyncClient.pushConnect(config: PushConfig) { + try { + sendPushConnect(config) + } catch (e: Exception) { + throw connectError((e as? ExecutionException)?.cause ?: e) + } +} + +/** The error a failed CONNECT reports: the broker's Reason String when it refused one. */ +internal fun connectError(cause: Throwable): AppwriteException = + if (cause is Mqtt5ConnAckException) { + connAckError(cause) + } else { + AppwriteException(cause.message ?: "MQTT connection failed") + } + +/** + * Whether [error] is the broker refusing the credential (a CONNECT or re-auth), which retrying + * with the same credential cannot fix, unlike a rate limit or a network failure. + */ +internal fun isAuthRefusal(error: Throwable?): Boolean = when (error) { + is Mqtt5ConnAckException -> error.mqttMessage.reasonCode in setOf( + Mqtt5ConnAckReasonCode.NOT_AUTHORIZED, + Mqtt5ConnAckReasonCode.BAD_USER_NAME_OR_PASSWORD, + Mqtt5ConnAckReasonCode.BAD_AUTHENTICATION_METHOD, + Mqtt5ConnAckReasonCode.BANNED, + ) + is Mqtt5DisconnectException -> error.mqttMessage.reasonCode == Mqtt5DisconnectReasonCode.NOT_AUTHORIZED + else -> false +} + +/** Send the CONNECT and wait for the CONNACK, at most [timeoutSeconds] when given. */ +internal fun Mqtt5AsyncClient.sendPushConnect(config: PushConfig, timeoutSeconds: Long? = null) { + val connAck = connectWith() + .enhancedAuth(PushAuthMechanism(config.authMethod, config.credential)) + // Clean start is always off, so the broker keeps this client's session and can + // redeliver missed messages to QoS-1 subscriptions on reconnect. + .cleanStart(false) + .keepAlive(config.keepAlive) + .userProperties() + .add("projectId", config.project) + .applyUserProperties() + .send() + if (timeoutSeconds == null) { + connAck.get() + } else { + connAck.get(timeoutSeconds, TimeUnit.SECONDS) + } +} + +/** + * The error a lost connection reports, or null when it is not an error (a disconnect the app + * asked for, or a broker DISCONNECT with a success reason code). The broker explains a refused + * CONNECT or a DISCONNECT it sends with an MQTT 5 Reason String, which becomes the message. + */ +internal fun pushDisconnectError(context: MqttClientDisconnectedContext): Throwable? { + val cause = context.cause + return when { + context.source == MqttDisconnectSource.USER -> null + cause is Mqtt5ConnAckException -> connAckError(cause) + cause is Mqtt5DisconnectException && context.source == MqttDisconnectSource.SERVER -> { + val disconnect = cause.mqttMessage + if (disconnect.reasonCode.isError) { + AppwriteException( + disconnect.reasonString.map { it.toString() } + .orElse("Disconnected by the broker (reason ${disconnect.reasonCode})"), + ) + } else { + null + } + } + else -> cause + } +} + +/** A refused CONNECT, with the CONNACK Reason String as its message when the broker sent one. */ +internal fun connAckError(e: Mqtt5ConnAckException): AppwriteException = + AppwriteException( + e.mqttMessage.reasonString.map { it.toString() }.orElse(e.message ?: "MQTT connection refused"), + ) + +internal fun Mqtt5Publish.toPushMessage(): PushMessage = + PushMessage( + topic = topic.toString(), + payload = payloadAsBytes, + qos = qos.code, + ) + +/** + * Single-step MQTT 5 enhanced auth: the method and credential are placed in the CONNECT + * packet and the broker accepts them in the CONNACK, with no AUTH round-trip. + */ +internal class PushAuthMechanism( + private val method: String, + private val credential: String, +) : Mqtt5EnhancedAuthMechanism { + + override fun getMethod(): MqttUtf8String = MqttUtf8String.of(method) + + override fun getTimeout(): Int = 30 + + override fun onAuth( + clientConfig: Mqtt5ClientConfig, + connect: Mqtt5Connect, + authBuilder: Mqtt5EnhancedAuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onReAuth( + clientConfig: Mqtt5ClientConfig, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onContinue( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthSuccess( + clientConfig: Mqtt5ClientConfig, + connAck: Mqtt5ConnAck, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onReAuthSuccess( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthRejected(clientConfig: Mqtt5ClientConfig, connAck: Mqtt5ConnAck) = Unit + + override fun onReAuthRejected(clientConfig: Mqtt5ClientConfig, disconnect: Mqtt5Disconnect) = Unit + + override fun onAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit + + override fun onReAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit +} + +/** + * A [TrustManagerFactory] that accepts any certificate — used when `tlsInsecure` is set + * (for a broker whose certificate does not chain to a public root). + */ +internal object PushInsecureTrustManagerFactory : TrustManagerFactory( + object : TrustManagerFactorySpi() { + override fun engineInit(keyStore: KeyStore?) = Unit + + override fun engineInit(parameters: ManagerFactoryParameters?) = Unit + + override fun engineGetTrustManagers(): Array = arrayOf( + object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + + override fun getAcceptedIssuers(): Array = emptyArray() + }, + ) + }, + @Suppress("DEPRECATION") object : Provider("AppwriteInsecure", 1.0, "insecure trust-all") {}, + "AppwriteInsecure", +) + +/** A live in-app subscription hosted in the background: its topics, callback, notification opt-in and QoS. */ +internal class PushListener( + val topics: Set, + val callback: (PushMessage) -> Unit, + val background: Boolean, + val title: String?, + val retry: Boolean, + // Called instead of [callback] when set, with the acknowledgement to run once the message was + // handled: the React Native and Flutter bridges acknowledge after their callback has run. + val acknowledgingCallback: ((PushMessage, () -> Unit) -> Unit)? = null, +) + +/** MQTT topic-filter match with '+' (single level) and '#' (multi level). */ +internal fun matchesTopic(filter: String, topic: String): Boolean { + val filterParts = filter.split('/') + val topicParts = topic.split('/') + for (i in filterParts.indices) { + if (filterParts[i] == "#") { + return true + } + if (i >= topicParts.size) { + return false + } + if (filterParts[i] != "+" && filterParts[i] != topicParts[i]) { + return false + } + } + return filterParts.size == topicParts.size +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt new file mode 100644 index 00000000..92d04727 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt @@ -0,0 +1,33 @@ +package io.appwrite.services + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * Handles background push messages in code when no in-app callback is listening, e.g. after + * the process was started in the background to reconnect. Subclass it and declare it in your + * manifest with the push message action: + * + * ```xml + * + * + * + * + * + * ``` + * + * The SDK calls [onMessage] directly on a background thread, under a wakelock of about ten + * seconds, so hand longer work to WorkManager. Messages a live callback receives do not + * reach it. + */ +abstract class PushReceiver : BroadcastReceiver() { + /** + * Handle [message]. Return true when you handled it yourself, so the SDK does not post its + * default notification; return false to have it posted as well. + */ + abstract fun onMessage(context: Context, message: PushMessage): Boolean + + // Messages arrive through onMessage, never as a broadcast. + final override fun onReceive(context: Context, intent: Intent) = Unit +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushService.kt b/android/src/main/kotlin/io/appwrite/services/PushService.kt new file mode 100644 index 00000000..e2a05f89 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushService.kt @@ -0,0 +1,67 @@ +package io.appwrite.services + +import android.app.Service +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.ServiceCompat + +/** + * The foreground mode of background push delivery ([Push.setForeground]): a foreground service + * that keeps the process at foreground priority, so the connection held by the process stays + * up and delivers immediately, also during Doze. The system restarts it after a kill, and it + * restores the saved subscriptions. Started by the SDK; not meant to be started directly. + */ +class PushService : Service() { + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + PushBackground.serviceRunning = true + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (!PushBackground.wantsService(this)) { + stopSelf() + return START_NOT_STICKY + } + try { + startForegroundCompat() + } catch (e: Exception) { + // E.g. a background start refused on Android 12+; the scheduled runs keep delivering. + stopSelf() + PushBackground.report(e) + return START_NOT_STICKY + } + PushBackground.tick(this) {} + // Recreated after a kill with a null intent; the saved subscriptions are restored then. + return START_STICKY + } + + private fun startForegroundCompat() { + val notification = PushBackground.ongoingNotification(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceCompat.startForeground( + this, + PushBackground.NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING, + ) + } else { + startForeground(PushBackground.NOTIFICATION_ID, notification) + } + } + + // Some devices kill the process shortly after its task is swiped away; a run a few seconds + // later restarts the service. + override fun onTaskRemoved(rootIntent: Intent?) { + PushBackground.scheduleRestart(this) + super.onTaskRemoved(rootIntent) + } + + override fun onDestroy() { + PushBackground.serviceRunning = false + super.onDestroy() + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt new file mode 100644 index 00000000..091fd528 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt @@ -0,0 +1,46 @@ +package io.appwrite.services + +import android.app.job.JobParameters +import android.app.job.JobService +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * The scheduled run of background push delivery: reconnects and re-arms itself. Scheduled + * by the SDK; not meant to be started directly. + */ +class PushJobService : JobService() { + override fun onStartJob(params: JobParameters): Boolean { + PushBackground.tick(this) { jobFinished(params, false) } + return true + } + + // The run re-arms the next one itself, so a stopped run needs no retry. + override fun onStopJob(params: JobParameters): Boolean = false +} + +/** + * The alarm that backs up the scheduled job when it runs late. Scheduled by the SDK; not meant + * to be sent directly. + */ +class PushAlarmReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != PushBackground.ACTION_TICK) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} + +/** Resumes background push delivery after a reboot or an app update. */ +class PushBootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} diff --git a/docs/examples/account/create-anonymous-session.md b/docs/examples/account/create-anonymous-session.md index 0cdedf8f..5fa3803b 100644 --- a/docs/examples/account/create-anonymous-session.md +++ b/docs/examples/account/create-anonymous-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Session result = await account.createAnonymousSession(); +models.Session result = await account.createAnonymousSession(); ``` diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index d444996d..e40921bd 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,8 +8,9 @@ Client client = Client() Account account = Account(client); -Session result = await account.createEmailPasswordSession( +models.Session result = await account.createEmailPasswordSession( email: 'email@example.com', password: 'password', + duration: 60, // optional ); ``` diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index 73890581..a2b3d4cc 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailToken( +models.Token result = await account.createEmailToken( userId: '', email: 'email@example.com', phrase: false, // optional diff --git a/docs/examples/account/create-email-verification-otp.md b/docs/examples/account/create-email-verification-otp.md index 941db965..0e7cc23c 100644 --- a/docs/examples/account/create-email-verification-otp.md +++ b/docs/examples/account/create-email-verification-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailVerificationOTP( +models.Token result = await account.createEmailVerificationOTP( phrase: false, // optional ); ``` diff --git a/docs/examples/account/create-email-verification.md b/docs/examples/account/create-email-verification.md index d88979c8..48011dba 100644 --- a/docs/examples/account/create-email-verification.md +++ b/docs/examples/account/create-email-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailVerification( +models.Token result = await account.createEmailVerification( url: 'https://example.com', ); ``` diff --git a/docs/examples/account/create-id-token-session.md b/docs/examples/account/create-id-token-session.md index 61f84065..f667ea96 100644 --- a/docs/examples/account/create-id-token-session.md +++ b/docs/examples/account/create-id-token-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.createIdTokenSession( +models.Session result = await account.createIdTokenSession( provider: enums.IdTokenProvider.apple, idToken: '', nonce: '', // optional diff --git a/docs/examples/account/create-jwt.md b/docs/examples/account/create-jwt.md index 72ff1180..dee4f4d9 100644 --- a/docs/examples/account/create-jwt.md +++ b/docs/examples/account/create-jwt.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Jwt result = await account.createJWT( +models.Jwt result = await account.createJWT( duration: 0, // optional ); ``` diff --git a/docs/examples/account/create-magic-url-token.md b/docs/examples/account/create-magic-url-token.md index 59d1cc24..fc04f508 100644 --- a/docs/examples/account/create-magic-url-token.md +++ b/docs/examples/account/create-magic-url-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createMagicURLToken( +models.Token result = await account.createMagicURLToken( userId: '', email: 'email@example.com', url: 'https://example.com', // optional diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index c86de3ba..7dc8321c 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -MfaType result = await account.createMFAAuthenticator( +models.MfaType result = await account.createMFAAuthenticator( type: enums.AuthenticatorType.totp, ); ``` diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index c7007d32..f5f71618 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -MfaChallenge result = await account.createMFAChallenge( +models.MfaChallenge result = await account.createMFAChallenge( factor: enums.AuthenticationFactor.email, ); ``` diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index 252dec7a..d39925f4 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.createMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.createMFARecoveryCodes(); ``` diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index 95799d62..907f85bd 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createPhoneToken( +models.Token result = await account.createPhoneToken( userId: '', phone: '+12065550100', ); diff --git a/docs/examples/account/create-phone-verification.md b/docs/examples/account/create-phone-verification.md index 9fc84dfc..0fd3951a 100644 --- a/docs/examples/account/create-phone-verification.md +++ b/docs/examples/account/create-phone-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Token result = await account.createPhoneVerification(); +models.Token result = await account.createPhoneVerification(); ``` diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index d493b2a0..250cd4db 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Target result = await account.createPushTarget( +models.Target result = await account.createPushTarget( targetId: '', identifier: '', providerId: '', // optional diff --git a/docs/examples/account/create-recovery-otp.md b/docs/examples/account/create-recovery-otp.md index 366469f3..a081194e 100644 --- a/docs/examples/account/create-recovery-otp.md +++ b/docs/examples/account/create-recovery-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createRecoveryOTP( +models.Token result = await account.createRecoveryOTP( email: 'email@example.com', phrase: false, // optional ); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index fe5ecfa0..d59589fe 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createRecovery( +models.Token result = await account.createRecovery( email: 'email@example.com', url: 'https://example.com', ); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index ebac1f93..3cf9382f 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.createSession( +models.Session result = await account.createSession( userId: '', secret: '', ); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index c36cb8f3..08896cbc 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createVerification( +models.Token result = await account.createVerification( url: 'https://example.com', ); ``` diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index 8343f628..6f1350aa 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.create( +models.User result = await account.create( userId: '', email: 'email@example.com', password: 'password', diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index e8e8ba1a..388661a9 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -7,5 +7,7 @@ Client client = Client() Account account = Account(client); -await account.deleteSessions(); +await account.deleteSessions( + current: false, // optional +); ``` diff --git a/docs/examples/account/get-consent-token.md b/docs/examples/account/get-consent-token.md index 67a0d842..4454000a 100644 --- a/docs/examples/account/get-consent-token.md +++ b/docs/examples/account/get-consent-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentToken result = await account.getConsentToken( +models.Oauth2ConsentToken result = await account.getConsentToken( consentId: '', tokenId: '', ); diff --git a/docs/examples/account/get-consent.md b/docs/examples/account/get-consent.md index aff62725..5fcf846e 100644 --- a/docs/examples/account/get-consent.md +++ b/docs/examples/account/get-consent.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2Consent result = await account.getConsent( +models.Oauth2Consent result = await account.getConsent( consentId: '', ); ``` diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index ed5531a3..889252fd 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.getMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.getMFARecoveryCodes(); ``` diff --git a/docs/examples/account/get-prefs.md b/docs/examples/account/get-prefs.md index dc359f9c..a2407a58 100644 --- a/docs/examples/account/get-prefs.md +++ b/docs/examples/account/get-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Preferences result = await account.getPrefs(); +models.Preferences result = await account.getPrefs(); ``` diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index c27058a8..10ca295e 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.getSession( +models.Session result = await account.getSession( sessionId: '', ); ``` diff --git a/docs/examples/account/get.md b/docs/examples/account/get.md index 1bd67c6a..52c6dbb6 100644 --- a/docs/examples/account/get.md +++ b/docs/examples/account/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -User result = await account.get(); +models.User result = await account.get(); ``` diff --git a/docs/examples/account/list-consent-tokens.md b/docs/examples/account/list-consent-tokens.md index 835c7775..58f12a41 100644 --- a/docs/examples/account/list-consent-tokens.md +++ b/docs/examples/account/list-consent-tokens.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentTokenList result = await account.listConsentTokens( +models.Oauth2ConsentTokenList result = await account.listConsentTokens( consentId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/account/list-consents.md b/docs/examples/account/list-consents.md index d39f0547..cae45ca3 100644 --- a/docs/examples/account/list-consents.md +++ b/docs/examples/account/list-consents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentList result = await account.listConsents( +models.Oauth2ConsentList result = await account.listConsents( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index d0c0e5b6..73c900ec 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -IdentityList result = await account.listIdentities( +models.IdentityList result = await account.listIdentities( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index 4cfcf88b..98e1815e 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaFactors result = await account.listMFAFactors(); +models.MfaFactors result = await account.listMFAFactors(); ``` diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 18db93bb..21bdd898 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Account account = Account(client); -SessionList result = await account.listSessions(); +models.SessionList result = await account.listSessions( + total: false, // optional +); ``` diff --git a/docs/examples/account/update-email-verification-otp.md b/docs/examples/account/update-email-verification-otp.md index 52ff4c11..f4572d83 100644 --- a/docs/examples/account/update-email-verification-otp.md +++ b/docs/examples/account/update-email-verification-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateEmailVerificationOTP( +models.Token result = await account.updateEmailVerificationOTP( userId: '', secret: '', ); diff --git a/docs/examples/account/update-email-verification.md b/docs/examples/account/update-email-verification.md index 7e3975e9..828013f1 100644 --- a/docs/examples/account/update-email-verification.md +++ b/docs/examples/account/update-email-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateEmailVerification( +models.Token result = await account.updateEmailVerification( userId: '', secret: '', ); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index e5e1a169..13cc2d7c 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateEmail( +models.User result = await account.updateEmail( email: 'email@example.com', password: 'password', ); diff --git a/docs/examples/account/update-magic-url-session.md b/docs/examples/account/update-magic-url-session.md index c45dcf1e..590d6f9e 100644 --- a/docs/examples/account/update-magic-url-session.md +++ b/docs/examples/account/update-magic-url-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateMagicURLSession( +models.Session result = await account.updateMagicURLSession( userId: '', secret: '', ); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 539c5e28..bb946951 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateMFAAuthenticator( +models.User result = await account.updateMFAAuthenticator( type: enums.AuthenticatorType.totp, otp: '', ); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index 55f4ebee..8e1ee662 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateMFAChallenge( +models.Session result = await account.updateMFAChallenge( challengeId: '', otp: '', ); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 7a188d40..88e5284e 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.updateMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.updateMFARecoveryCodes(); ``` diff --git a/docs/examples/account/update-mfa.md b/docs/examples/account/update-mfa.md index db9addd6..fd5826bc 100644 --- a/docs/examples/account/update-mfa.md +++ b/docs/examples/account/update-mfa.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateMFA( +models.User result = await account.updateMFA( mfa: false, ); ``` diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index 8ab71223..cf9064db 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateName( +models.User result = await account.updateName( name: '', ); ``` diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index c2604a9c..e5e5495f 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePassword( +models.User result = await account.updatePassword( password: 'password', oldPassword: 'password', // optional ); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index f538680a..4137cece 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updatePhoneSession( +models.Session result = await account.updatePhoneSession( userId: '', secret: '', ); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index de226a7c..dc2afd5c 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updatePhoneVerification( +models.Token result = await account.updatePhoneVerification( userId: '', secret: '', ); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index f631c5df..914b64d2 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePhone( +models.User result = await account.updatePhone( phone: '+12065550100', password: 'password', ); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index 6f9863d3..2ae515f6 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePrefs( +models.User result = await account.updatePrefs( prefs: { "language": "en", "timezone": "UTC", diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index 601f3aec..49429983 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Target result = await account.updatePushTarget( +models.Target result = await account.updatePushTarget( targetId: '', identifier: '', ); diff --git a/docs/examples/account/update-recovery-otp.md b/docs/examples/account/update-recovery-otp.md index f7b4a2ef..0103c951 100644 --- a/docs/examples/account/update-recovery-otp.md +++ b/docs/examples/account/update-recovery-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateRecoveryOTP( +models.Token result = await account.updateRecoveryOTP( userId: '', secret: '', password: 'password', diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index 809aa044..8d85a1fa 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateRecovery( +models.Token result = await account.updateRecovery( userId: '', secret: '', password: 'password', diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index 7fb334aa..18fe1ede 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateSession( +models.Session result = await account.updateSession( sessionId: '', ); ``` diff --git a/docs/examples/account/update-status.md b/docs/examples/account/update-status.md index d7b0d0dc..88c9ecff 100644 --- a/docs/examples/account/update-status.md +++ b/docs/examples/account/update-status.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -User result = await account.updateStatus(); +models.User result = await account.updateStatus(); ``` diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index 339b4b91..433677aa 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateVerification( +models.Token result = await account.updateVerification( userId: '', secret: '', ); diff --git a/docs/examples/apps/create-installation-token.md b/docs/examples/apps/create-installation-token.md new file mode 100644 index 00000000..32b738ae --- /dev/null +++ b/docs/examples/apps/create-installation-token.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.Oauth2Token result = await apps.createInstallationToken( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/create-key.md b/docs/examples/apps/create-key.md new file mode 100644 index 00000000..6e8974b7 --- /dev/null +++ b/docs/examples/apps/create-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKey result = await apps.createKey( + appId: '', +); +``` diff --git a/docs/examples/apps/create-secret.md b/docs/examples/apps/create-secret.md new file mode 100644 index 00000000..c7c46ea0 --- /dev/null +++ b/docs/examples/apps/create-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecretPlaintext result = await apps.createSecret( + appId: '', +); +``` diff --git a/docs/examples/apps/create.md b/docs/examples/apps/create.md new file mode 100644 index 00000000..0613f535 --- /dev/null +++ b/docs/examples/apps/create.md @@ -0,0 +1,32 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.create( + appId: '', + name: '', + redirectUris: [], + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + postLogoutRedirectUris: [], // optional + enabled: false, // optional + type: 'public', // optional + deviceFlow: false, // optional + teamId: '', // optional +); +``` diff --git a/docs/examples/apps/delete-installation.md b/docs/examples/apps/delete-installation.md new file mode 100644 index 00000000..55707ce0 --- /dev/null +++ b/docs/examples/apps/delete-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/delete-key.md b/docs/examples/apps/delete-key.md new file mode 100644 index 00000000..e6bd4065 --- /dev/null +++ b/docs/examples/apps/delete-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/delete-secret.md b/docs/examples/apps/delete-secret.md new file mode 100644 index 00000000..0e7a1506 --- /dev/null +++ b/docs/examples/apps/delete-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/delete-tokens.md b/docs/examples/apps/delete-tokens.md new file mode 100644 index 00000000..cdba07ee --- /dev/null +++ b/docs/examples/apps/delete-tokens.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteTokens( + appId: '', +); +``` diff --git a/docs/examples/apps/delete.md b/docs/examples/apps/delete.md new file mode 100644 index 00000000..e56502a6 --- /dev/null +++ b/docs/examples/apps/delete.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.delete( + appId: '', +); +``` diff --git a/docs/examples/apps/get-installation.md b/docs/examples/apps/get-installation.md new file mode 100644 index 00000000..0d31b69a --- /dev/null +++ b/docs/examples/apps/get-installation.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppInstallation result = await apps.getInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/get-key.md b/docs/examples/apps/get-key.md new file mode 100644 index 00000000..29cb78f4 --- /dev/null +++ b/docs/examples/apps/get-key.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKey result = await apps.getKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/get-secret.md b/docs/examples/apps/get-secret.md new file mode 100644 index 00000000..d6c39ca9 --- /dev/null +++ b/docs/examples/apps/get-secret.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecret result = await apps.getSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/get.md b/docs/examples/apps/get.md new file mode 100644 index 00000000..a70e4c91 --- /dev/null +++ b/docs/examples/apps/get.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.get( + appId: '', +); +``` diff --git a/docs/examples/apps/list-installation-scopes.md b/docs/examples/apps/list-installation-scopes.md new file mode 100644 index 00000000..2bd15fe2 --- /dev/null +++ b/docs/examples/apps/list-installation-scopes.md @@ -0,0 +1,12 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppScopeList result = await apps.listInstallationScopes(); +``` diff --git a/docs/examples/apps/list-installations.md b/docs/examples/apps/list-installations.md new file mode 100644 index 00000000..1463bc7f --- /dev/null +++ b/docs/examples/apps/list-installations.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppInstallationList result = await apps.listInstallations( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-keys.md b/docs/examples/apps/list-keys.md new file mode 100644 index 00000000..f52f2754 --- /dev/null +++ b/docs/examples/apps/list-keys.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKeyList result = await apps.listKeys( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-o-auth-2-scopes.md b/docs/examples/apps/list-o-auth-2-scopes.md new file mode 100644 index 00000000..08755449 --- /dev/null +++ b/docs/examples/apps/list-o-auth-2-scopes.md @@ -0,0 +1,12 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppScopeList result = await apps.listOAuth2Scopes(); +``` diff --git a/docs/examples/apps/list-secrets.md b/docs/examples/apps/list-secrets.md new file mode 100644 index 00000000..51998b3c --- /dev/null +++ b/docs/examples/apps/list-secrets.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecretList result = await apps.listSecrets( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list.md b/docs/examples/apps/list.md new file mode 100644 index 00000000..e7868580 --- /dev/null +++ b/docs/examples/apps/list.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppsList result = await apps.list( + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/update-team.md b/docs/examples/apps/update-team.md new file mode 100644 index 00000000..adcd2361 --- /dev/null +++ b/docs/examples/apps/update-team.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.updateTeam( + appId: '', + teamId: '', +); +``` diff --git a/docs/examples/apps/update.md b/docs/examples/apps/update.md new file mode 100644 index 00000000..38ceb19a --- /dev/null +++ b/docs/examples/apps/update.md @@ -0,0 +1,33 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.update( + appId: '', + name: '', + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + enabled: false, // optional + redirectUris: [], // optional + postLogoutRedirectUris: [], // optional + type: 'public', // optional + deviceFlow: false, // optional + installationScopes: [], // optional + installationRedirectUrl: 'https://example.com', // optional +); +``` diff --git a/docs/examples/avatars/delete-photo.md b/docs/examples/avatars/delete-photo.md new file mode 100644 index 00000000..390a3192 --- /dev/null +++ b/docs/examples/avatars/delete-photo.md @@ -0,0 +1,11 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +await avatars.deletePhoto(); +``` diff --git a/docs/examples/avatars/get-screenshot.md b/docs/examples/avatars/get-screenshot.md index daa38d17..1a22a692 100644 --- a/docs/examples/avatars/get-screenshot.md +++ b/docs/examples/avatars/get-screenshot.md @@ -15,8 +15,7 @@ Avatars avatars = Avatars(client); Uint8List bytes = await avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional @@ -46,8 +45,7 @@ FutureBuilder( future: avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional diff --git a/docs/examples/avatars/update-photo.md b/docs/examples/avatars/update-photo.md new file mode 100644 index 00000000..e667a94a --- /dev/null +++ b/docs/examples/avatars/update-photo.md @@ -0,0 +1,15 @@ +```dart +import 'dart:io'; +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +models.Account result = await avatars.updatePhoto( + file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), +); +``` diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index a4df848f..ade4f576 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.createDocument( +models.Document result = await databases.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/create-operations.md b/docs/examples/databases/create-operations.md index 0551c28b..e3528d32 100644 --- a/docs/examples/databases/create-operations.md +++ b/docs/examples/databases/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.createOperations( +models.Transaction result = await databases.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/databases/create-transaction.md b/docs/examples/databases/create-transaction.md index 14ea5563..b7ccbf21 100644 --- a/docs/examples/databases/create-transaction.md +++ b/docs/examples/databases/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.createTransaction( +models.Transaction result = await databases.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/databases/decrement-document-attribute.md b/docs/examples/databases/decrement-document-attribute.md index 0d178cff..6780426c 100644 --- a/docs/examples/databases/decrement-document-attribute.md +++ b/docs/examples/databases/decrement-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.decrementDocumentAttribute( +models.Document result = await databases.decrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index 1f384afd..fabd67df 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.getDocument( +models.Document result = await databases.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/get-transaction.md b/docs/examples/databases/get-transaction.md index 142b8bfa..012e2e27 100644 --- a/docs/examples/databases/get-transaction.md +++ b/docs/examples/databases/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.getTransaction( +models.Transaction result = await databases.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/databases/increment-document-attribute.md b/docs/examples/databases/increment-document-attribute.md index 05b3690e..dce65a73 100644 --- a/docs/examples/databases/increment-document-attribute.md +++ b/docs/examples/databases/increment-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.incrementDocumentAttribute( +models.Document result = await databases.incrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index 531be6ad..090e731a 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -DocumentList result = await databases.listDocuments( +models.DocumentList result = await databases.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/databases/list-transactions.md b/docs/examples/databases/list-transactions.md index ca9ff6fb..d090af1e 100644 --- a/docs/examples/databases/list-transactions.md +++ b/docs/examples/databases/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() Databases databases = Databases(client); -TransactionList result = await databases.listTransactions( +models.TransactionList result = await databases.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index 52557334..cf6d599c 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.updateDocument( +models.Document result = await databases.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/update-transaction.md b/docs/examples/databases/update-transaction.md index a882eb92..1695fe8c 100644 --- a/docs/examples/databases/update-transaction.md +++ b/docs/examples/databases/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.updateTransaction( +models.Transaction result = await databases.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/databases/upsert-document.md b/docs/examples/databases/upsert-document.md index 6678a0dc..1cd30f25 100644 --- a/docs/examples/databases/upsert-document.md +++ b/docs/examples/databases/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.upsertDocument( +models.Document result = await databases.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/create-document.md b/docs/examples/documentsdb/create-document.md index d4b564e2..5ed989ad 100644 --- a/docs/examples/documentsdb/create-document.md +++ b/docs/examples/documentsdb/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.createDocument( +models.Document result = await documentsDB.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/create-documents.md b/docs/examples/documentsdb/create-documents.md index 6a508373..b3f24c51 100644 --- a/docs/examples/documentsdb/create-documents.md +++ b/docs/examples/documentsdb/create-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,10 +8,19 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -DocumentList result = await documentsDB.createDocuments( +models.DocumentList result = await documentsDB.createDocuments( databaseId: '', collectionId: '', - documents: [], + documents: [ + { + "\$id": "example1", + "username": "walter.obrien", + "email": "walter.obrien@example.com", + "fullName": "Walter O'Brien", + "age": 30, + "isAdmin": false + } + ], transactionId: '', // optional ); ``` diff --git a/docs/examples/documentsdb/create-operations.md b/docs/examples/documentsdb/create-operations.md index a4d1ecdd..5e5799d8 100644 --- a/docs/examples/documentsdb/create-operations.md +++ b/docs/examples/documentsdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.createOperations( +models.Transaction result = await documentsDB.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/documentsdb/create-transaction.md b/docs/examples/documentsdb/create-transaction.md index 2d9cb9f7..bd287408 100644 --- a/docs/examples/documentsdb/create-transaction.md +++ b/docs/examples/documentsdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.createTransaction( +models.Transaction result = await documentsDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/documentsdb/decrement-document-attribute.md b/docs/examples/documentsdb/decrement-document-attribute.md index dcdac3aa..fbf0a5a7 100644 --- a/docs/examples/documentsdb/decrement-document-attribute.md +++ b/docs/examples/documentsdb/decrement-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.decrementDocumentAttribute( +models.Document result = await documentsDB.decrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/get-document.md b/docs/examples/documentsdb/get-document.md index 45db46e6..f37160a1 100644 --- a/docs/examples/documentsdb/get-document.md +++ b/docs/examples/documentsdb/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.getDocument( +models.Document result = await documentsDB.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/get-transaction.md b/docs/examples/documentsdb/get-transaction.md index 4b1a5f1f..77885681 100644 --- a/docs/examples/documentsdb/get-transaction.md +++ b/docs/examples/documentsdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.getTransaction( +models.Transaction result = await documentsDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/documentsdb/increment-document-attribute.md b/docs/examples/documentsdb/increment-document-attribute.md index c2c6e95c..5df158fc 100644 --- a/docs/examples/documentsdb/increment-document-attribute.md +++ b/docs/examples/documentsdb/increment-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.incrementDocumentAttribute( +models.Document result = await documentsDB.incrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/list-documents.md b/docs/examples/documentsdb/list-documents.md index 92d2651c..bd5f04b7 100644 --- a/docs/examples/documentsdb/list-documents.md +++ b/docs/examples/documentsdb/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -DocumentList result = await documentsDB.listDocuments( +models.DocumentList result = await documentsDB.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md index d2c09525..73e59ee4 100644 --- a/docs/examples/documentsdb/list-transactions.md +++ b/docs/examples/documentsdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -TransactionList result = await documentsDB.listTransactions( +models.TransactionList result = await documentsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/documentsdb/update-document.md b/docs/examples/documentsdb/update-document.md index 1b9fba9a..ec752959 100644 --- a/docs/examples/documentsdb/update-document.md +++ b/docs/examples/documentsdb/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.updateDocument( +models.Document result = await documentsDB.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/update-transaction.md b/docs/examples/documentsdb/update-transaction.md index ebcf17be..049ed68c 100644 --- a/docs/examples/documentsdb/update-transaction.md +++ b/docs/examples/documentsdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.updateTransaction( +models.Transaction result = await documentsDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/documentsdb/upsert-document.md b/docs/examples/documentsdb/upsert-document.md index bdf3844b..61baa69d 100644 --- a/docs/examples/documentsdb/upsert-document.md +++ b/docs/examples/documentsdb/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.upsertDocument( +models.Document result = await documentsDB.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 0e219748..d8970844 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Functions functions = Functions(client); -Execution result = await functions.createExecution( +models.Execution result = await functions.createExecution( functionId: '', body: '', // optional xasync: false, // optional diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index f17e10c1..7ad87740 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Functions functions = Functions(client); -Execution result = await functions.getExecution( +models.Execution result = await functions.getExecution( functionId: '', executionId: '', ); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index ae31ffcc..df498257 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Functions functions = Functions(client); -ExecutionList result = await functions.listExecutions( +models.ExecutionList result = await functions.listExecutions( functionId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index 7ec3ba75..e9632b86 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,9 @@ Client client = Client() Graphql graphql = Graphql(client); -Any result = await graphql.mutation( - query: {}, +models.Any result = await graphql.mutation( + query: { + "query": "mutation { accountUpdateName(name: \"Walter\") { name } }" + }, ); ``` diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index cac705e5..de938d4a 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,9 @@ Client client = Client() Graphql graphql = Graphql(client); -Any result = await graphql.query( - query: {}, +models.Any result = await graphql.query( + query: { + "query": "query { localeGet { ip } }" + }, ); ``` diff --git a/docs/examples/locale/get.md b/docs/examples/locale/get.md index 63021144..633588f3 100644 --- a/docs/examples/locale/get.md +++ b/docs/examples/locale/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Locale locale = Locale(client); -Locale result = await locale.get(); +models.Locale result = await locale.get(); ``` diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index 23c375ba..e706e517 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -LocaleCodeList result = await locale.listCodes(); +models.LocaleCodeList result = await locale.listCodes( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index 349be795..fb4ae372 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -ContinentList result = await locale.listContinents(); +models.ContinentList result = await locale.listContinents( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-eu.md b/docs/examples/locale/list-countries-eu.md index f775aa2e..0f734c5f 100644 --- a/docs/examples/locale/list-countries-eu.md +++ b/docs/examples/locale/list-countries-eu.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountriesEU(); +models.CountryList result = await locale.listCountriesEU( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index ee368e29..1a29575a 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -PhoneList result = await locale.listCountriesPhones(); +models.PhoneList result = await locale.listCountriesPhones( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 17e0814f..e1059d44 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountries(); +models.CountryList result = await locale.listCountries( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 751de786..276264ce 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CurrencyList result = await locale.listCurrencies(); +models.CurrencyList result = await locale.listCurrencies( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index 28b46a0a..4b8763f8 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -LanguageList result = await locale.listLanguages(); +models.LanguageList result = await locale.listLanguages( + total: false, // optional +); ``` diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index e28a1ab6..6b4bb2ee 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Messaging messaging = Messaging(client); -Subscriber result = await messaging.createSubscriber( +models.Subscriber result = await messaging.createSubscriber( topicId: '', subscriberId: '', targetId: '', diff --git a/docs/examples/oauth2/approve.md b/docs/examples/oauth2/approve.md new file mode 100644 index 00000000..02117db4 --- /dev/null +++ b/docs/examples/oauth2/approve.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Approve result = await oauth2.approve( + grantId: '', + authorizationDetails: '', // optional + scope: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize-post.md b/docs/examples/oauth2/authorize-post.md new file mode 100644 index 00000000..cc16efa2 --- /dev/null +++ b/docs/examples/oauth2/authorize-post.md @@ -0,0 +1,27 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Authorize result = await oauth2.authorizePost( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize.md b/docs/examples/oauth2/authorize.md new file mode 100644 index 00000000..d7c6889a --- /dev/null +++ b/docs/examples/oauth2/authorize.md @@ -0,0 +1,27 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Authorize result = await oauth2.authorize( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-device-authorization.md b/docs/examples/oauth2/create-device-authorization.md new file mode 100644 index 00000000..dcd41d61 --- /dev/null +++ b/docs/examples/oauth2/create-device-authorization.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2DeviceAuthorization result = await oauth2.createDeviceAuthorization( + clientId: '', // optional + scope: '', // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-grant.md b/docs/examples/oauth2/create-grant.md new file mode 100644 index 00000000..f1f5a5c1 --- /dev/null +++ b/docs/examples/oauth2/create-grant.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Grant result = await oauth2.createGrant( + userCode: '', +); +``` diff --git a/docs/examples/oauth2/create-par.md b/docs/examples/oauth2/create-par.md new file mode 100644 index 00000000..4034af4c --- /dev/null +++ b/docs/examples/oauth2/create-par.md @@ -0,0 +1,26 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2PAR result = await oauth2.createPAR( + clientId: '', + redirectUri: 'https://example.com', + responseType: 'code', + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-token.md b/docs/examples/oauth2/create-token.md new file mode 100644 index 00000000..2037d4cd --- /dev/null +++ b/docs/examples/oauth2/create-token.md @@ -0,0 +1,23 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Token result = await oauth2.createToken( + grantType: '', + code: '', // optional + refreshToken: '', // optional + deviceCode: '', // optional + clientId: '', // optional + clientSecret: '', // optional + codeVerifier: '', // optional + redirectUri: 'https://example.com', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/get-grant.md b/docs/examples/oauth2/get-grant.md new file mode 100644 index 00000000..fbb461d2 --- /dev/null +++ b/docs/examples/oauth2/get-grant.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Grant result = await oauth2.getGrant( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/list-organizations.md b/docs/examples/oauth2/list-organizations.md new file mode 100644 index 00000000..37376b57 --- /dev/null +++ b/docs/examples/oauth2/list-organizations.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2OrganizationList result = await oauth2.listOrganizations( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/list-projects.md b/docs/examples/oauth2/list-projects.md new file mode 100644 index 00000000..0a2924ed --- /dev/null +++ b/docs/examples/oauth2/list-projects.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2ProjectList result = await oauth2.listProjects( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout-post.md b/docs/examples/oauth2/logout-post.md new file mode 100644 index 00000000..3d163784 --- /dev/null +++ b/docs/examples/oauth2/logout-post.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.logoutPost( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout.md b/docs/examples/oauth2/logout.md new file mode 100644 index 00000000..3892325e --- /dev/null +++ b/docs/examples/oauth2/logout.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.logout( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/reject.md b/docs/examples/oauth2/reject.md new file mode 100644 index 00000000..20f5cb22 --- /dev/null +++ b/docs/examples/oauth2/reject.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Reject result = await oauth2.reject( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/revoke.md b/docs/examples/oauth2/revoke.md new file mode 100644 index 00000000..777340f7 --- /dev/null +++ b/docs/examples/oauth2/revoke.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.revoke( + token: '', + tokenTypeHint: 'access_token', // optional + clientId: '', // optional + clientSecret: '', // optional +); +``` diff --git a/docs/examples/organization/create-installation.md b/docs/examples/organization/create-installation.md index d28dacfc..520c4e41 100644 --- a/docs/examples/organization/create-installation.md +++ b/docs/examples/organization/create-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.createInstallation( +models.AppInstallation result = await organization.createInstallation( appId: '', authorizationDetails: '', // optional ); diff --git a/docs/examples/organization/get-installation.md b/docs/examples/organization/get-installation.md index dd2d7ac7..f6a1ef77 100644 --- a/docs/examples/organization/get-installation.md +++ b/docs/examples/organization/get-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.getInstallation( +models.AppInstallation result = await organization.getInstallation( installationId: '', ); ``` diff --git a/docs/examples/organization/list-installations.md b/docs/examples/organization/list-installations.md index bdecb108..58350547 100644 --- a/docs/examples/organization/list-installations.md +++ b/docs/examples/organization/list-installations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallationList result = await organization.listInstallations( +models.AppInstallationList result = await organization.listInstallations( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/organization/update-installation.md b/docs/examples/organization/update-installation.md index fa834d49..8d2fddf4 100644 --- a/docs/examples/organization/update-installation.md +++ b/docs/examples/organization/update-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.updateInstallation( +models.AppInstallation result = await organization.updateInstallation( installationId: '', authorizationDetails: '', // optional ); diff --git a/docs/examples/presences/get.md b/docs/examples/presences/get.md index 9fad57c6..fd10e547 100644 --- a/docs/examples/presences/get.md +++ b/docs/examples/presences/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.get( +models.Presence result = await presences.get( presenceId: '', ); ``` diff --git a/docs/examples/presences/list.md b/docs/examples/presences/list.md index 5810a298..cfd67ab0 100644 --- a/docs/examples/presences/list.md +++ b/docs/examples/presences/list.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Presences presences = Presences(client); -PresenceList result = await presences.list( +models.PresenceList result = await presences.list( queries: [], // optional total: false, // optional ttl: 0, // optional diff --git a/docs/examples/presences/update.md b/docs/examples/presences/update.md index 84a64be0..ed52a7b0 100644 --- a/docs/examples/presences/update.md +++ b/docs/examples/presences/update.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.update( +models.Presence result = await presences.update( presenceId: '', status: '', // optional expiresAt: '2020-10-15T06:38:00.000+00:00', // optional diff --git a/docs/examples/presences/upsert.md b/docs/examples/presences/upsert.md index 32acc92f..1620ff55 100644 --- a/docs/examples/presences/upsert.md +++ b/docs/examples/presences/upsert.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.upsert( +models.Presence result = await presences.upsert( presenceId: '', status: '', permissions: [Permission.read(Role.any())], // optional diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 7d8fbd13..f7267340 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -1,6 +1,7 @@ ```dart import 'dart:io'; import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -10,7 +11,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.createFile( +models.File result = await storage.createFile( bucketId: '', fileId: '', file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index 9f1adb6e..8cd043ca 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.getFile( +models.File result = await storage.getFile( bucketId: '', fileId: '', ); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index 0decd695..41f947a5 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Storage storage = Storage(client); -FileList result = await storage.listFiles( +models.FileList result = await storage.listFiles( bucketId: '', queries: [], // optional search: '', // optional diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index 90814329..fe33f0bf 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.updateFile( +models.File result = await storage.updateFile( bucketId: '', fileId: '', name: '', // optional diff --git a/docs/examples/tablesdb/create-operations.md b/docs/examples/tablesdb/create-operations.md index bc779b6b..8cdbeb48 100644 --- a/docs/examples/tablesdb/create-operations.md +++ b/docs/examples/tablesdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.createOperations( +models.Transaction result = await tablesDB.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/tablesdb/create-row.md b/docs/examples/tablesdb/create-row.md index cb5d8578..e3b639c7 100644 --- a/docs/examples/tablesdb/create-row.md +++ b/docs/examples/tablesdb/create-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.createRow( +models.Row result = await tablesDB.createRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/create-transaction.md b/docs/examples/tablesdb/create-transaction.md index 527dde39..c27b2c3f 100644 --- a/docs/examples/tablesdb/create-transaction.md +++ b/docs/examples/tablesdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.createTransaction( +models.Transaction result = await tablesDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/tablesdb/decrement-row-column.md b/docs/examples/tablesdb/decrement-row-column.md index bee4987f..c6582bb7 100644 --- a/docs/examples/tablesdb/decrement-row-column.md +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.decrementRowColumn( +models.Row result = await tablesDB.decrementRowColumn( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/get-row.md b/docs/examples/tablesdb/get-row.md index 6e385a84..560c6ad3 100644 --- a/docs/examples/tablesdb/get-row.md +++ b/docs/examples/tablesdb/get-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.getRow( +models.Row result = await tablesDB.getRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/get-transaction.md b/docs/examples/tablesdb/get-transaction.md index 39b02a77..7137420b 100644 --- a/docs/examples/tablesdb/get-transaction.md +++ b/docs/examples/tablesdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.getTransaction( +models.Transaction result = await tablesDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/tablesdb/increment-row-column.md b/docs/examples/tablesdb/increment-row-column.md index 9b0e4769..8123160c 100644 --- a/docs/examples/tablesdb/increment-row-column.md +++ b/docs/examples/tablesdb/increment-row-column.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.incrementRowColumn( +models.Row result = await tablesDB.incrementRowColumn( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/list-rows.md b/docs/examples/tablesdb/list-rows.md index a2637a93..f681a236 100644 --- a/docs/examples/tablesdb/list-rows.md +++ b/docs/examples/tablesdb/list-rows.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -RowList result = await tablesDB.listRows( +models.RowList result = await tablesDB.listRows( databaseId: '', tableId: '', queries: [], // optional diff --git a/docs/examples/tablesdb/list-transactions.md b/docs/examples/tablesdb/list-transactions.md index d95e5198..a863deab 100644 --- a/docs/examples/tablesdb/list-transactions.md +++ b/docs/examples/tablesdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -TransactionList result = await tablesDB.listTransactions( +models.TransactionList result = await tablesDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/tablesdb/update-row.md b/docs/examples/tablesdb/update-row.md index 3cf3c955..1d42d637 100644 --- a/docs/examples/tablesdb/update-row.md +++ b/docs/examples/tablesdb/update-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.updateRow( +models.Row result = await tablesDB.updateRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/update-transaction.md b/docs/examples/tablesdb/update-transaction.md index d5a8e082..cfc7f99e 100644 --- a/docs/examples/tablesdb/update-transaction.md +++ b/docs/examples/tablesdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.updateTransaction( +models.Transaction result = await tablesDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/tablesdb/upsert-row.md b/docs/examples/tablesdb/upsert-row.md index 74c7d2c5..a9df95fb 100644 --- a/docs/examples/tablesdb/upsert-row.md +++ b/docs/examples/tablesdb/upsert-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.upsertRow( +models.Row result = await tablesDB.upsertRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/teams/create-installation.md b/docs/examples/teams/create-installation.md index 4ad63b8d..26732254 100644 --- a/docs/examples/teams/create-installation.md +++ b/docs/examples/teams/create-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.createInstallation( +models.AppInstallation result = await teams.createInstallation( teamId: '', appId: '', authorizationDetails: '', // optional diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index caab7926..48940095 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,9 +8,9 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.createMembership( +models.Membership result = await teams.createMembership( teamId: '', - roles: [], + roles: ["editor"], email: 'email@example.com', // optional userId: '', // optional phone: '+12065550100', // optional diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 7a4af366..4bc35166 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.create( +models.Team result = await teams.create( teamId: '', name: '', roles: [], // optional diff --git a/docs/examples/teams/get-installation.md b/docs/examples/teams/get-installation.md index eec87662..10f3f096 100644 --- a/docs/examples/teams/get-installation.md +++ b/docs/examples/teams/get-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.getInstallation( +models.AppInstallation result = await teams.getInstallation( teamId: '', installationId: '', ); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 3a2906b9..798aa48f 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.getMembership( +models.Membership result = await teams.getMembership( teamId: '', membershipId: '', ); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index e35006fa..6b9805b0 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Preferences result = await teams.getPrefs( +models.Preferences result = await teams.getPrefs( teamId: '', ); ``` diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index 2a71db42..df4f911f 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.get( +models.Team result = await teams.get( teamId: '', ); ``` diff --git a/docs/examples/teams/list-installations.md b/docs/examples/teams/list-installations.md index 9c3aa852..73818abd 100644 --- a/docs/examples/teams/list-installations.md +++ b/docs/examples/teams/list-installations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallationList result = await teams.listInstallations( +models.AppInstallationList result = await teams.listInstallations( teamId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index bf643511..b3a0ceef 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -MembershipList result = await teams.listMemberships( +models.MembershipList result = await teams.listMemberships( teamId: '', queries: [], // optional search: '', // optional diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 2de4ebfe..9df25089 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -TeamList result = await teams.list( +models.TeamList result = await teams.list( queries: [], // optional search: '', // optional total: false, // optional diff --git a/docs/examples/teams/update-installation.md b/docs/examples/teams/update-installation.md index e9e8ba4b..5b66afa4 100644 --- a/docs/examples/teams/update-installation.md +++ b/docs/examples/teams/update-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.updateInstallation( +models.AppInstallation result = await teams.updateInstallation( teamId: '', installationId: '', authorizationDetails: '', // optional diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index ebb924b0..7968476c 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.updateMembershipStatus( +models.Membership result = await teams.updateMembershipStatus( teamId: '', membershipId: '', userId: '', diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 2d7c25c8..a86fa3f1 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,9 +8,9 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.updateMembership( +models.Membership result = await teams.updateMembership( teamId: '', membershipId: '', - roles: [], + roles: ["editor"], ); ``` diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index 629e7608..1c9d6502 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.updateName( +models.Team result = await teams.updateName( teamId: '', name: '', ); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index 1a53c498..9d652cb9 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Preferences result = await teams.updatePrefs( +models.Preferences result = await teams.updatePrefs( teamId: '', prefs: {}, ); diff --git a/docs/examples/vectorsdb/create-document.md b/docs/examples/vectorsdb/create-document.md index fc39a7c1..ecc02176 100644 --- a/docs/examples/vectorsdb/create-document.md +++ b/docs/examples/vectorsdb/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.createDocument( +models.Document result = await vectorsDB.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/create-operations.md b/docs/examples/vectorsdb/create-operations.md index a994693e..0604ef6b 100644 --- a/docs/examples/vectorsdb/create-operations.md +++ b/docs/examples/vectorsdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.createOperations( +models.Transaction result = await vectorsDB.createOperations( transactionId: '', operations: [ { @@ -16,7 +17,15 @@ Transaction result = await vectorsDB.createOperations( "collectionId": "", "documentId": "", "data": { - "name": "Walter O'Brien" + "embeddings": [ + 0.12, + -0.55, + 0.88, + 1.02 + ], + "metadata": { + "name": "First document" + } } } ], // optional diff --git a/docs/examples/vectorsdb/create-query.md b/docs/examples/vectorsdb/create-query.md index fa41ee5c..3b72a0c4 100644 --- a/docs/examples/vectorsdb/create-query.md +++ b/docs/examples/vectorsdb/create-query.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -DocumentList result = await vectorsDB.createQuery( +models.DocumentList result = await vectorsDB.createQuery( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/vectorsdb/create-transaction.md b/docs/examples/vectorsdb/create-transaction.md index 9c8c96d3..d197ad2a 100644 --- a/docs/examples/vectorsdb/create-transaction.md +++ b/docs/examples/vectorsdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.createTransaction( +models.Transaction result = await vectorsDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/vectorsdb/get-document.md b/docs/examples/vectorsdb/get-document.md index 28e544b3..42a2a2b8 100644 --- a/docs/examples/vectorsdb/get-document.md +++ b/docs/examples/vectorsdb/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.getDocument( +models.Document result = await vectorsDB.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/get-transaction.md b/docs/examples/vectorsdb/get-transaction.md index 1d191d09..68023e00 100644 --- a/docs/examples/vectorsdb/get-transaction.md +++ b/docs/examples/vectorsdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.getTransaction( +models.Transaction result = await vectorsDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/vectorsdb/list-documents.md b/docs/examples/vectorsdb/list-documents.md index 03b4931d..26793163 100644 --- a/docs/examples/vectorsdb/list-documents.md +++ b/docs/examples/vectorsdb/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -DocumentList result = await vectorsDB.listDocuments( +models.DocumentList result = await vectorsDB.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md index fb7f83db..befe5379 100644 --- a/docs/examples/vectorsdb/list-transactions.md +++ b/docs/examples/vectorsdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -TransactionList result = await vectorsDB.listTransactions( +models.TransactionList result = await vectorsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/vectorsdb/update-document.md b/docs/examples/vectorsdb/update-document.md index 8c2a9091..0457e855 100644 --- a/docs/examples/vectorsdb/update-document.md +++ b/docs/examples/vectorsdb/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.updateDocument( +models.Document result = await vectorsDB.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/update-transaction.md b/docs/examples/vectorsdb/update-transaction.md index 1abd8b02..6915d144 100644 --- a/docs/examples/vectorsdb/update-transaction.md +++ b/docs/examples/vectorsdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.updateTransaction( +models.Transaction result = await vectorsDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/vectorsdb/upsert-document.md b/docs/examples/vectorsdb/upsert-document.md index 1367bba4..de7503fb 100644 --- a/docs/examples/vectorsdb/upsert-document.md +++ b/docs/examples/vectorsdb/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.upsertDocument( +models.Document result = await vectorsDB.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c80609e3..c2083c8a 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -24,6 +24,8 @@ export 'src/response.dart'; export 'src/client.dart'; export 'src/exception.dart'; export 'src/realtime.dart'; +export 'src/mqtt.dart'; +export 'src/mqtt_message.dart'; export 'src/upload_progress.dart'; export 'src/realtime_subscription.dart'; export 'src/realtime_message.dart'; @@ -33,9 +35,11 @@ part 'query.dart'; part 'permission.dart'; part 'role.dart'; part 'id.dart'; +part 'topic.dart'; part 'channel.dart'; part 'operator.dart'; part 'services/account.dart'; +part 'services/apps.dart'; part 'services/avatars.dart'; part 'services/databases.dart'; part 'services/documents_db.dart'; @@ -43,6 +47,7 @@ part 'services/functions.dart'; part 'services/graphql.dart'; part 'services/locale.dart'; part 'services/messaging.dart'; +part 'services/oauth2.dart'; part 'services/organization.dart'; part 'services/presences.dart'; part 'services/storage.dart'; diff --git a/lib/models.dart b/lib/models.dart index f1fca69d..ce40157d 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -31,6 +31,7 @@ part 'src/models/algo_bcrypt.dart'; part 'src/models/algo_scrypt.dart'; part 'src/models/algo_scrypt_modified.dart'; part 'src/models/algo_argon2.dart'; +part 'src/models/account.dart'; part 'src/models/preferences.dart'; part 'src/models/session.dart'; part 'src/models/identity.dart'; @@ -55,9 +56,29 @@ part 'src/models/mfa_factors.dart'; part 'src/models/transaction.dart'; part 'src/models/subscriber.dart'; part 'src/models/target.dart'; +part 'src/models/app.dart'; +part 'src/models/app_secret.dart'; +part 'src/models/app_secret_plaintext.dart'; +part 'src/models/app_scope.dart'; part 'src/models/app_installation.dart'; +part 'src/models/app_key.dart'; +part 'src/models/oauth2_authorize.dart'; +part 'src/models/oauth2_approve.dart'; +part 'src/models/oauth2_reject.dart'; +part 'src/models/oauth2_grant.dart'; +part 'src/models/oauth2_device_authorization.dart'; +part 'src/models/oauth2_par.dart'; +part 'src/models/oauth2_token.dart'; part 'src/models/oauth2_consent.dart'; part 'src/models/oauth2_consent_token.dart'; +part 'src/models/oauth2_project.dart'; +part 'src/models/oauth2_organization.dart'; +part 'src/models/oauth2_project_list.dart'; +part 'src/models/oauth2_organization_list.dart'; part 'src/models/oauth2_consent_list.dart'; part 'src/models/oauth2_consent_token_list.dart'; +part 'src/models/apps_list.dart'; +part 'src/models/app_secret_list.dart'; +part 'src/models/app_scope_list.dart'; part 'src/models/app_installation_list.dart'; +part 'src/models/app_key_list.dart'; diff --git a/lib/query.dart b/lib/query.dart index 1ad97bdc..aeb93797 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,27 +159,33 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => 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(); + static String or(List queries) { + return Query._( + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } + + static String and(List queries) { + return Query._( + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + static String elemMatch(String attribute, List queries) { + return Query._( + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Specify which attributes should be returned by the API call. static String select(List attributes) => diff --git a/lib/services/account.dart b/lib/services/account.dart index 48492bdb..9eda7926 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1246,10 +1246,14 @@ class Account extends Service { /// Get the list of active sessions across different devices for the currently /// logged in user. - Future listSessions() async { + Future listSessions({ + bool? total, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1267,11 +1271,16 @@ class Account extends Service { } /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { + /// from the end client. Pass `current` as false to keep the session making the + /// request and sign out of every other session. + Future deleteSessions({ + bool? current, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (current != null) 'current': current, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1319,6 +1328,9 @@ class Account extends Service { /// 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. + /// Use the optional `duration` parameter to create a shorter session, for + /// example when the user doesn't choose "remember me". It must be at least 60 + /// seconds and cannot exceed the project maximum session length. /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session @@ -1326,12 +1338,14 @@ class Account extends Service { Future createEmailPasswordSession({ required String email, required String password, + int? duration, }) async { final String apiPath = '/account/sessions/email'; final Map apiParams = { 'email': email, 'password': password, + if (duration != null) 'duration': duration, }; final Map apiHeaders = { diff --git a/lib/services/apps.dart b/lib/services/apps.dart new file mode 100644 index 00000000..1026e7ea --- /dev/null +++ b/lib/services/apps.dart @@ -0,0 +1,852 @@ +part of '../appwrite.dart'; + +/// The Apps service allows you to manage OAuth2 applications, their keys, +/// secrets, scopes, and installations. +class Apps extends Service { + /// Initializes a [Apps] service + Apps(super.client); + + /// List applications. + Future list({ + List? queries, + bool? total, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppsList.fromMap(res.data); + } + + /// Create a new application. + Future create({ + required String appId, + required String name, + required List redirectUris, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + List? postLogoutRedirectUris, + bool? enabled, + String? type, + bool? deviceFlow, + String? teamId, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + 'appId': appId, + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (enabled != null) 'enabled': enabled, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (teamId != null) 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// List scopes an application can request when installed on a team. + Future listInstallationScopes() async { + final String apiPath = '/apps/scopes/installations'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// List scopes an application can request during the OAuth2 flow. + Future listOAuth2Scopes() async { + final String apiPath = '/apps/scopes/oauth2'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// Get an application by its unique ID. + Future get({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Update an application by its unique ID. + Future update({ + required String appId, + required String name, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + bool? enabled, + List? redirectUris, + List? postLogoutRedirectUris, + String? type, + bool? deviceFlow, + List? installationScopes, + String? installationRedirectUrl, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + if (enabled != null) 'enabled': enabled, + if (redirectUris != null) 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (installationScopes != null) 'installationScopes': installationScopes, + if (installationRedirectUrl != null) + 'installationRedirectUrl': installationRedirectUrl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Delete an application by its unique ID. + Future delete({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List installations of an application. Requires an app key sent in the + /// `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, or a caller + /// with update access to the app. + Future listInstallations({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/installations'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallationList.fromMap(res.data); + } + + /// Get an installation of an application by its unique ID. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. + Future getInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallation.fromMap(res.data); + } + + /// Delete an installation of an application by its unique ID. Requires a + /// caller with update access to the app. Previously issued installation access + /// tokens are revoked. + Future deleteInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Create a token for an installation of an application. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. The returned token carries the + /// scopes and authorization details granted to the installation, and can be + /// used as an `Authorization: Bearer` header everywhere OAuth2 access tokens + /// are accepted. Multiple tokens can be active for the same installation at + /// once; each token stays valid until it expires or the installation is + /// updated or deleted. + Future createInstallationToken({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}/tokens' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } + + /// List app keys for an application. + Future listKeys({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKeyList.fromMap(res.data); + } + + /// Create a new app key for an application. App keys carry no scopes; send one + /// in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header to + /// list the application's installations and create installation access tokens. + Future createKey({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Get an app key by its unique ID. + Future getKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Delete an app key by its unique ID. + Future deleteKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List client secrets for an application. + Future listSecrets({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretList.fromMap(res.data); + } + + /// Create a new client secret for an application. + Future createSecret({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretPlaintext.fromMap(res.data); + } + + /// Get an application client secret by its unique ID. + Future getSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecret.fromMap(res.data); + } + + /// Delete an application client secret by its unique ID. + Future deleteSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Transfer an application to another team by its unique ID. + Future updateTeam({ + required String appId, + required String teamId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/team'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Revoke all tokens for an application by its unique ID. + Future deleteTokens({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/tokens'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index c57fb66e..f9b4cbd5 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -242,9 +242,9 @@ class Avatars extends Service { } /// Returns the best available profile photo for a user. The endpoint tries - /// each source in priority order and returns the first successful result: - /// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in - /// static fallback. + /// each source in priority order and returns the first successful result: a + /// custom uploaded photo (see avatars.updatePhoto), OAuth2 identity photo, + /// Gravatar, Libravatar, Appwrite Initials, built-in static fallback. /// /// Passing `userId` — `current()` for the authenticated user — resolves /// the photo from everything known about that user: identity photos, email, @@ -294,6 +294,68 @@ class Avatars extends Service { return res.data; } + /// Update the profile photo of the currently authenticated user. The uploaded + /// image takes priority over every other photo source, including OAuth2 + /// identity photos, Gravatar, and Libravatar. Updating an already customized + /// photo replaces it. The image must be at most 5MB and is sent in a single + /// request. + Future updatePhoto({ + required InputFile file, + Function(UploadProgress)? onProgress, + }) async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = { + 'file': file, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + String idParamName = ''; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + method: HttpMethod.put, + ); + + return models.Account.fromMap(res.data); + } + + /// Delete the profile photo of the currently authenticated user and store the + /// built-in static placeholder in its place. The placeholder is the user's + /// photo from then on, so it takes priority over every other photo source — + /// OAuth2 identity photos, Gravatar, Libravatar, and initials — until a new + /// photo is uploaded with avatars.updatePhoto. + Future deletePhoto() async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + /// 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({ diff --git a/lib/services/databases.dart b/lib/services/databases.dart index f1bb2510..96fed789 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -12,11 +12,13 @@ class Databases extends Service { ) Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/databases/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -189,11 +191,11 @@ class Databases extends Service { ); } - final String apiPath = - '/databases/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/documents_db.dart b/lib/services/documents_db.dart index 3ca77cdb..1d04aa9c 100644 --- a/lib/services/documents_db.dart +++ b/lib/services/documents_db.dart @@ -7,11 +7,13 @@ class DocumentsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/documentsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -65,11 +67,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -100,11 +102,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (commit != null) 'commit': commit, @@ -137,11 +139,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; diff --git a/lib/services/locale.dart b/lib/services/locale.dart index d4831b74..227f1a9b 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -34,10 +34,14 @@ class Locale extends Service { /// List of all locale codes in [ISO /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { + Future listCodes({ + bool? total, + }) async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -56,10 +60,14 @@ class Locale extends Service { /// List of all continents. You can use the locale header to get the data in a /// supported language. - Future listContinents() async { + Future listContinents({ + bool? total, + }) async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -78,10 +86,14 @@ class Locale extends Service { /// List of all countries. You can use the locale header to get the data in a /// supported language. - Future listCountries() async { + Future listCountries({ + bool? total, + }) async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -100,10 +112,14 @@ class Locale extends Service { /// 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 { + Future listCountriesEU({ + bool? total, + }) async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -122,10 +138,14 @@ class Locale extends Service { /// List of all countries phone codes. You can use the locale header to get the /// data in a supported language. - Future listCountriesPhones() async { + Future listCountriesPhones({ + bool? total, + }) async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -145,10 +165,14 @@ class Locale extends Service { /// 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 { + Future listCurrencies({ + bool? total, + }) async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -167,10 +191,14 @@ class Locale extends Service { /// 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 { + Future listLanguages({ + bool? total, + }) async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', diff --git a/lib/services/oauth2.dart b/lib/services/oauth2.dart new file mode 100644 index 00000000..1950338a --- /dev/null +++ b/lib/services/oauth2.dart @@ -0,0 +1,588 @@ +part of '../appwrite.dart'; + +/// The OAuth2 service allows you to authorize apps and issue standards-based +/// OAuth2 and OpenID Connect tokens. +class Oauth2 extends Service { + /// Initializes a [Oauth2] service + Oauth2(super.client); + + /// Approve an OAuth2 grant after the user gives consent. Returns the + /// `redirectUrl` the end user should be sent to. The consent screen may + /// optionally pass enriched `authorization_details` to record the concrete + /// resources the user selected. You can pass Accept header of + /// `application/json` to receive a JSON response instead of a redirect. + Future approve({ + required String grantId, + String? authorizationDetails, + String? scope, + }) async { + final String apiPath = '/oauth2/{project_id}/approve'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (scope != null) 'scope': scope, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Approve.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorize({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorizePost({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Start the OAuth2 Device Authorization Grant. Returns the device code, user + /// code, verification URL, expiration, and polling interval. + Future createDeviceAuthorization({ + String? clientId, + String? scope, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/device_authorization' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (scope != null) 'scope': scope, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2DeviceAuthorization.fromMap(res.data); + } + + /// Exchange a device flow user code for an OAuth2 grant. The authenticated + /// user is bound to the pending grant. Pass the returned grant ID to the get + /// grant endpoint to render the consent screen, then to the approve or reject + /// endpoint to complete the flow. + Future createGrant({ + required String userCode, + }) async { + final String apiPath = '/oauth2/{project_id}/grants'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'user_code': userCode, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// Get an OAuth2 grant by its ID. Used by the consent screen to display the + /// details of the authorization the user is being asked to approve. A grant + /// can only be read by the user it belongs to, or by server SDK. + Future getGrant({ + required String grantId, + }) async { + if (grantId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "grantId"', + ); + } + + final String apiPath = '/oauth2/{project_id}/grants/{grant_id}' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ) + .replaceAll( + '{grant_id}', + grantId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logout({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logoutPost({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List the organizations the OAuth2 access token can access. Resolves the + /// token's `organization` authorization details, expanding the `*` wildcard + /// into the concrete set of organizations the user can see. + Future listOrganizations({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/organizations'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2OrganizationList.fromMap(res.data); + } + + /// Store an OAuth2 authorization request server-side and receive a short-lived + /// request_uri handle for the authorize endpoint. + Future createPAR({ + required String clientId, + required String redirectUri, + required String responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/par'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'client_id': clientId, + 'redirect_uri': redirectUri, + 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2PAR.fromMap(res.data); + } + + /// List the projects the OAuth2 access token can access. Resolves the token's + /// `project` authorization details, expanding the `*` wildcard into the + /// concrete set of projects the user can see. + Future listProjects({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/projects'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2ProjectList.fromMap(res.data); + } + + /// Reject an OAuth2 grant when the user denies consent. Returns the + /// `redirectUrl` the end user should be sent to with an `access_denied` error. + /// You can pass Accept header of `application/json` to receive a JSON response + /// instead of a redirect. + Future reject({ + required String grantId, + }) async { + final String apiPath = '/oauth2/{project_id}/reject'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Reject.fromMap(res.data); + } + + /// Revoke an OAuth2 access token or refresh token. + Future revoke({ + required String token, + String? tokenTypeHint, + String? clientId, + String? clientSecret, + }) async { + final String apiPath = '/oauth2/{project_id}/revoke'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'token': token, + if (tokenTypeHint != null) 'token_type_hint': tokenTypeHint, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Exchange an OAuth2 authorization code, refresh token, or device code for + /// access and refresh tokens. + Future createToken({ + required String grantType, + String? code, + String? refreshToken, + String? deviceCode, + String? clientId, + String? clientSecret, + String? codeVerifier, + String? redirectUri, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/token'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_type': grantType, + if (code != null) 'code': code, + if (refreshToken != null) 'refresh_token': refreshToken, + if (deviceCode != null) 'device_code': deviceCode, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + if (codeVerifier != null) 'code_verifier': codeVerifier, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } +} diff --git a/lib/services/organization.dart b/lib/services/organization.dart index bbda874a..68b762c9 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -75,11 +75,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -112,11 +112,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -151,11 +151,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/storage.dart b/lib/services/storage.dart index 52a129a8..ec4522fe 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -104,6 +104,7 @@ class Storage extends Service { idParamName: idParamName, headers: apiHeaders, onProgress: onProgress, + method: HttpMethod.post, ); return models.File.fromMap(res.data); diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 4fdbb987..e7a5d4a3 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -9,11 +9,13 @@ class TablesDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/tablesdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -171,11 +173,11 @@ class TablesDB extends Service { ); } - final String apiPath = - '/tablesdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/vectors_db.dart b/lib/services/vectors_db.dart index e257b38c..fddd1087 100644 --- a/lib/services/vectors_db.dart +++ b/lib/services/vectors_db.dart @@ -7,11 +7,13 @@ class VectorsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/vectorsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -169,11 +171,11 @@ class VectorsDB extends Service { ); } - final String apiPath = - '/vectorsdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/vectorsdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/src/client.dart b/lib/src/client.dart index fedec03c..f456f011 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -41,6 +40,8 @@ abstract class Client { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }); /// Set self signed to [status]. @@ -56,6 +57,14 @@ abstract class Client { /// Set the Appwrite realtime endpoint. Client setEndPointRealtime(String endPoint); + /// Set the Appwrite push (MQTT broker) endpoint, e.g. + /// `mqtt://host:1883` or `mqtts://host:8883`. + Client setPushEndpoint(String endPoint); + + /// Set a stable push client id, so the broker resumes this client's offline-replay + /// cursor across restarts. Defaults to a per-connection id when unset. + Client setPushClientId(String pushClientId); + /// Set Project. /// /// Your project ID. diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 36e4bbc9..9897e898 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -47,6 +47,12 @@ abstract class ClientBase implements Client { @override Client setEndPointRealtime(String endPoint); + @override + Client setPushEndpoint(String endPoint); + + @override + Client setPushClientId(String pushClientId); + @override ClientBase addHeader(String key, String value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index d04f9bc6..182870c7 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -155,6 +155,18 @@ class ClientBrowser extends ClientBase with ClientMixin { return this; } + @override + ClientBrowser setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientBrowser setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientBrowser addHeader(String key, String value) { _headers![key] = value; @@ -182,7 +194,19 @@ class ClientBrowser extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.bytes == null) { throw AppwriteException("File bytes must be provided for Flutter web"); @@ -191,17 +215,18 @@ class ClientBrowser extends ClientBase with ClientMixin { int size = file.bytes!.length; late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { params[paramName] = http.MultipartFile.fromBytes( paramName, file.bytes!, filename: file.filename, ); return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -249,7 +274,7 @@ class ClientBrowser extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f228d17f..00e8954f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,9 +47,10 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = + HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -59,7 +60,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -185,6 +186,18 @@ class ClientIO extends ClientBase with ClientMixin { return this; } + @override + ClientIO setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientIO setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientIO addHeader(String key, String value) { _headers![key] = value; @@ -286,7 +299,19 @@ class ClientIO extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.path == null && file.bytes == null) { throw AppwriteException("File path or bytes must be provided"); @@ -305,7 +330,7 @@ class ClientIO extends ClientBase with ClientMixin { } late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { if (file.path != null) { params[paramName] = await http.MultipartFile.fromPath( paramName, @@ -320,10 +345,11 @@ class ClientIO extends ClientBase with ClientMixin { ); } return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -349,8 +375,13 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id, - [RandomAccessFile? raf]) async { + Future uploadChunk( + int index, + int start, + int end, + String? id, [ + RandomAccessFile? raf, + ]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -382,7 +413,7 @@ class ClientIO extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, @@ -474,9 +505,10 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: + callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -491,9 +523,10 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = + codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 952d7114..55a75c2c 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -31,6 +31,10 @@ mixin ClientMixin { }); } }); + } else if (value is Map) { + (request as http.MultipartRequest).fields.addAll({ + key: jsonEncode(value), + }); } else { (request as http.MultipartRequest).fields.addAll({ key: value.toString(), @@ -91,9 +95,10 @@ mixin ClientMixin { warnings.split(';').forEach((warning) => log('Warning: $warning')); } + final isJson = (res.headers['content-type'] ?? '').contains( + 'application/json', + ); if (res.statusCode >= 400) { - final isJson = - (res.headers['content-type'] ?? '').contains('application/json'); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -116,20 +121,16 @@ mixin ClientMixin { } } dynamic data; - if ((res.headers['content-type'] ?? '').contains('application/json')) { - if (responseType == ResponseType.json) { - data = json.decode(res.body); - } else if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + if (responseType == ResponseType.bytes) { + data = res.bodyBytes; + } else if (responseType == ResponseType.plain) { + // Decode as UTF-8 whatever the charset, since package:http falls back + // to latin1 when the content-type does not name one. + data = utf8.decode(res.bodyBytes); + } else if (isJson) { + data = json.decode(res.body); } else { - if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + data = res.body; } return Response(data: data); } @@ -141,10 +142,12 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + 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, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 6b1e67cd..05253273 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,14 +17,15 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }).catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }) + .catchError((e, stackTrace) { + return request; + }); return request; } @@ -43,8 +44,9 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host), + scheme: response.request!.url.scheme, + host: response.request!.url.host, + ), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 595afdc2..0f250ea3 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes + bytes, } diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 02b85c7f..ab1b5668 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -43,6 +43,7 @@ enum OAuthProvider { tradeshift(value: "tradeshift"), tradeshiftBox(value: "tradeshiftBox"), twitch(value: "twitch"), + webflow(value: "webflow"), wordpress(value: "wordpress"), x(value: "x"), yahoo(value: "yahoo"), diff --git a/lib/src/input_file.dart b/lib/src/input_file.dart index c0be7c04..f1022c22 100644 --- a/lib/src/input_file.dart +++ b/lib/src/input_file.dart @@ -8,16 +8,38 @@ class InputFile { final String? contentType; @Deprecated('Use `InputFile.fromPath` or `InputFile.fromBytes` instead.') - InputFile({this.path, this.filename, this.contentType, this.bytes}) { + InputFile({ + String? path, + String? filename, + String? contentType, + List? bytes, + }) : this._( + path: path, + filename: filename, + contentType: contentType, + bytes: bytes, + ); + + InputFile._({this.path, String? filename, this.contentType, this.bytes}) + : filename = filename ?? _filenameFromPath(path) { if (path == null && bytes == null) { throw AppwriteException('One of `path` or `bytes` is required'); } } - InputFile._({this.path, this.filename, this.contentType, this.bytes}) { - if (path == null && bytes == null) { - throw AppwriteException('One of `path` or `bytes` is required'); + /// Mirrors how `package:http` derives a filename in `MultipartFile.fromPath`, + /// so a chunked upload sends the same `filename` as a single-request one. + /// Without it the chunk parts carry no `filename` and the server rejects them + /// as an empty file. + static String? _filenameFromPath(String? path) { + if (path == null) { + return null; } + + final segments = Uri.file(path).pathSegments; + final filename = segments.isEmpty ? '' : segments.last; + + return filename.isEmpty ? null : filename; } /// Provide a file using `path` diff --git a/lib/src/models/account.dart b/lib/src/models/account.dart new file mode 100644 index 00000000..31e79064 --- /dev/null +++ b/lib/src/models/account.dart @@ -0,0 +1,167 @@ +part of '../../models.dart'; + +/// Account +class Account 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; + + /// 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; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked. + final bool? passwordPwned; + + /// 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; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + Account({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + this.passwordPwned, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + factory Account.fromMap( + Map map, + ) { + return Account( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + registration: map['registration'].toString(), + status: map['status'], + labels: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + passwordPwned: map['passwordPwned'], + 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(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "passwordPwned": passwordPwned, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } +} diff --git a/lib/src/models/app.dart b/lib/src/models/app.dart new file mode 100644 index 00000000..7f2a93cf --- /dev/null +++ b/lib/src/models/app.dart @@ -0,0 +1,177 @@ +part of '../../models.dart'; + +/// App +class App implements Model { + /// App ID. + final String $id; + + /// App creation time in ISO 8601 format. + final String $createdAt; + + /// App update date in ISO 8601 format. + final String $updatedAt; + + /// Application name. + final String name; + + /// Application description shown to users during OAuth2 consent. + final String description; + + /// Application homepage URL shown to users during OAuth2 consent. + final String clientUri; + + /// Application logo URL shown to users during OAuth2 consent. + final String logoUri; + + /// Application privacy policy URL shown to users during OAuth2 consent. + final String privacyPolicyUrl; + + /// Application terms of service URL shown to users during OAuth2 consent. + final String termsUrl; + + /// Application support or security contact emails. + final List contacts; + + /// Application tagline shown to users during OAuth2 consent. + final String tagline; + + /// Application tags shown to users during OAuth2 consent. + final List tags; + + /// Application labels. Read-only for clients; only a server SDK using a project API key can update them. + final List labels; + + /// Application image URLs shown to users during OAuth2 consent. + final List images; + + /// Application support URL shown to users during OAuth2 consent. + final String supportUrl; + + /// Application data deletion URL shown to users during OAuth2 consent. + final String dataDeletionUrl; + + /// List of authorized redirect URIs. These URIs can be used to redirect users after they authenticate. + final List redirectUris; + + /// List of authorized post-logout redirect URIs for OpenID Connect RP-Initiated Logout. The logout endpoint only redirects users to URIs in this list after ending their session. + final List postLogoutRedirectUris; + + /// Whether the app is enabled or not. + final bool enabled; + + /// OAuth2 client type. `public` for SPAs, mobile, and native apps that cannot keep a client secret (PKCE required); `confidential` for server-side clients that authenticate with a client secret. + final String type; + + /// Whether this client may use the OAuth2 Device Authorization Grant (RFC 8628). + final bool deviceFlow; + + /// ID of team that owns the application, if owned by team. Otherwise, user ID will be used. + final String teamId; + + /// ID of user who owns the application, if owned by user. Otherwise, team ID will be used. + final String userId; + + /// Scopes the application requests when installed on a team. Organization-level and project-level scopes only. + final List installationScopes; + + /// URL users are redirected to after creating or updating an installation of this application. Empty for no redirect. + final String installationRedirectUrl; + + /// List of application secrets. + final List secrets; + + App({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.description, + required this.clientUri, + required this.logoUri, + required this.privacyPolicyUrl, + required this.termsUrl, + required this.contacts, + required this.tagline, + required this.tags, + required this.labels, + required this.images, + required this.supportUrl, + required this.dataDeletionUrl, + required this.redirectUris, + required this.postLogoutRedirectUris, + required this.enabled, + required this.type, + required this.deviceFlow, + required this.teamId, + required this.userId, + required this.installationScopes, + required this.installationRedirectUrl, + required this.secrets, + }); + factory App.fromMap( + Map map, + ) { + return App( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + description: map['description'].toString(), + clientUri: map['clientUri'].toString(), + logoUri: map['logoUri'].toString(), + privacyPolicyUrl: map['privacyPolicyUrl'].toString(), + termsUrl: map['termsUrl'].toString(), + contacts: List.from(map['contacts'] ?? []), + tagline: map['tagline'].toString(), + tags: List.from(map['tags'] ?? []), + labels: List.from(map['labels'] ?? []), + images: List.from(map['images'] ?? []), + supportUrl: map['supportUrl'].toString(), + dataDeletionUrl: map['dataDeletionUrl'].toString(), + redirectUris: List.from(map['redirectUris'] ?? []), + postLogoutRedirectUris: List.from(map['postLogoutRedirectUris'] ?? []), + enabled: map['enabled'], + type: map['type'].toString(), + deviceFlow: map['deviceFlow'], + teamId: map['teamId'].toString(), + userId: map['userId'].toString(), + installationScopes: List.from(map['installationScopes'] ?? []), + installationRedirectUrl: map['installationRedirectUrl'].toString(), + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "description": description, + "clientUri": clientUri, + "logoUri": logoUri, + "privacyPolicyUrl": privacyPolicyUrl, + "termsUrl": termsUrl, + "contacts": contacts, + "tagline": tagline, + "tags": tags, + "labels": labels, + "images": images, + "supportUrl": supportUrl, + "dataDeletionUrl": dataDeletionUrl, + "redirectUris": redirectUris, + "postLogoutRedirectUris": postLogoutRedirectUris, + "enabled": enabled, + "type": type, + "deviceFlow": deviceFlow, + "teamId": teamId, + "userId": userId, + "installationScopes": installationScopes, + "installationRedirectUrl": installationRedirectUrl, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_key.dart b/lib/src/models/app_key.dart new file mode 100644 index 00000000..5834ee2d --- /dev/null +++ b/lib/src/models/app_key.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppKey +class AppKey implements Model { + /// App key ID. + final String $id; + + /// App key creation time in ISO 8601 format. + final String $createdAt; + + /// App key update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this app key belongs to. + final String appId; + + /// App key secret. + final String secret; + + /// Last few characters of the app key secret, used to help identify it. + final String hint; + + /// ID of the user who created the app key. + final String createdById; + + /// Name of the user who created the app key. + final String createdByName; + + /// Time the app key was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppKey({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppKey.fromMap( + Map map, + ) { + return AppKey( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_key_list.dart b/lib/src/models/app_key_list.dart new file mode 100644 index 00000000..f4175972 --- /dev/null +++ b/lib/src/models/app_key_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App keys list +class AppKeyList implements Model { + /// Total number of keys that matched your query. + final int total; + + /// List of keys. + final List keys; + + AppKeyList({ + required this.total, + required this.keys, + }); + factory AppKeyList.fromMap( + Map map, + ) { + return AppKeyList( + total: map['total'], + keys: List.from( + map['keys'].map((p) => AppKey.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "keys": keys.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_scope.dart b/lib/src/models/app_scope.dart new file mode 100644 index 00000000..456b614b --- /dev/null +++ b/lib/src/models/app_scope.dart @@ -0,0 +1,49 @@ +part of '../../models.dart'; + +/// AppScope +class AppScope implements Model { + /// Scope value as requested by apps. + final String value; + + /// Human-readable description of what the scope grants. + final String description; + + /// What the scope grants access to. One of `account`, `project`, or `organization`. Only `project` and `organization` scopes are installable. + final String type; + + /// Scope category, used to group scopes on consent and installation screens. + final String category; + + /// Whether the scope is deprecated. Deprecated scopes can still be requested but should not be offered for new grants. + final bool deprecated; + + AppScope({ + required this.value, + required this.description, + required this.type, + required this.category, + required this.deprecated, + }); + factory AppScope.fromMap( + Map map, + ) { + return AppScope( + value: map['value'].toString(), + description: map['description'].toString(), + type: map['type'].toString(), + category: map['category'].toString(), + deprecated: map['deprecated'], + ); + } + + @override + Map toMap() { + return { + "value": value, + "description": description, + "type": type, + "category": category, + "deprecated": deprecated, + }; + } +} diff --git a/lib/src/models/app_scope_list.dart b/lib/src/models/app_scope_list.dart new file mode 100644 index 00000000..b59e3e64 --- /dev/null +++ b/lib/src/models/app_scope_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App scopes list +class AppScopeList implements Model { + /// Total number of scopes that matched your query. + final int total; + + /// List of scopes. + final List scopes; + + AppScopeList({ + required this.total, + required this.scopes, + }); + factory AppScopeList.fromMap( + Map map, + ) { + return AppScopeList( + total: map['total'], + scopes: List.from( + map['scopes'].map((p) => AppScope.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "scopes": scopes.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret.dart b/lib/src/models/app_secret.dart new file mode 100644 index 00000000..b16b102b --- /dev/null +++ b/lib/src/models/app_secret.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecret +class AppSecret implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Always empty. The application client secret is returned only once, in the response of the createSecret method. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecret({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecret.fromMap( + Map map, + ) { + return AppSecret( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_secret_list.dart b/lib/src/models/app_secret_list.dart new file mode 100644 index 00000000..7eb90b7a --- /dev/null +++ b/lib/src/models/app_secret_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App secrets list +class AppSecretList implements Model { + /// Total number of secrets that matched your query. + final int total; + + /// List of secrets. + final List secrets; + + AppSecretList({ + required this.total, + required this.secrets, + }); + factory AppSecretList.fromMap( + Map map, + ) { + return AppSecretList( + total: map['total'], + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret_plaintext.dart b/lib/src/models/app_secret_plaintext.dart new file mode 100644 index 00000000..b70d06e1 --- /dev/null +++ b/lib/src/models/app_secret_plaintext.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecretPlaintext +class AppSecretPlaintext implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Application client secret. Returned only when the secret is created; subsequent reads always return an empty value. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecretPlaintext({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecretPlaintext.fromMap( + Map map, + ) { + return AppSecretPlaintext( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/apps_list.dart b/lib/src/models/apps_list.dart new file mode 100644 index 00000000..0492e9f4 --- /dev/null +++ b/lib/src/models/apps_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// Apps list +class AppsList implements Model { + /// Total number of apps that matched your query. + final int total; + + /// List of apps. + final List apps; + + AppsList({ + required this.total, + required this.apps, + }); + factory AppsList.fromMap( + Map map, + ) { + return AppsList( + total: map['total'], + apps: List.from( + map['apps'].map((p) => App.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "apps": apps.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_approve.dart b/lib/src/models/oauth2_approve.dart new file mode 100644 index 00000000..e4db0be4 --- /dev/null +++ b/lib/src/models/oauth2_approve.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Approve +class Oauth2Approve implements Model { + /// URL the end user should be redirected to after the grant is approved, carrying the authorization `code` and/or `id_token` along with the original `state`. + final String redirectUrl; + + Oauth2Approve({ + required this.redirectUrl, + }); + factory Oauth2Approve.fromMap( + Map map, + ) { + return Oauth2Approve( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_authorize.dart b/lib/src/models/oauth2_authorize.dart new file mode 100644 index 00000000..0e820c68 --- /dev/null +++ b/lib/src/models/oauth2_authorize.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 Authorize +class Oauth2Authorize implements Model { + /// OAuth2 grant ID. Set when the user must give explicit consent; pass it to the approve or reject endpoint. Empty when a redirect URL is returned instead. + final String grantId; + + /// URL the end user should be redirected to when the flow can complete without consent. Empty when consent is still required. + final String redirectUrl; + + Oauth2Authorize({ + required this.grantId, + required this.redirectUrl, + }); + factory Oauth2Authorize.fromMap( + Map map, + ) { + return Oauth2Authorize( + grantId: map['grantId'].toString(), + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "grantId": grantId, + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_device_authorization.dart b/lib/src/models/oauth2_device_authorization.dart new file mode 100644 index 00000000..010af212 --- /dev/null +++ b/lib/src/models/oauth2_device_authorization.dart @@ -0,0 +1,55 @@ +part of '../../models.dart'; + +/// OAuth2 Device Authorization +class Oauth2DeviceAuthorization implements Model { + /// Device verification code used by the client to poll the token endpoint. + final String device_code; + + /// Short code the end user enters on the verification page. + final String user_code; + + /// URL where the end user enters the user code. + final String verification_uri; + + /// Verification URL with the user code prefilled as a query parameter. + final String verification_uri_complete; + + /// Lifetime of the device code and user code in seconds. + final int expires_in; + + /// Minimum polling interval for the token endpoint in seconds. + final int interval; + + Oauth2DeviceAuthorization({ + required this.device_code, + required this.user_code, + required this.verification_uri, + required this.verification_uri_complete, + required this.expires_in, + required this.interval, + }); + factory Oauth2DeviceAuthorization.fromMap( + Map map, + ) { + return Oauth2DeviceAuthorization( + device_code: map['device_code'].toString(), + user_code: map['user_code'].toString(), + verification_uri: map['verification_uri'].toString(), + verification_uri_complete: map['verification_uri_complete'].toString(), + expires_in: map['expires_in'], + interval: map['interval'], + ); + } + + @override + Map toMap() { + return { + "device_code": device_code, + "user_code": user_code, + "verification_uri": verification_uri, + "verification_uri_complete": verification_uri_complete, + "expires_in": expires_in, + "interval": interval, + }; + } +} diff --git a/lib/src/models/oauth2_grant.dart b/lib/src/models/oauth2_grant.dart new file mode 100644 index 00000000..32f22b8f --- /dev/null +++ b/lib/src/models/oauth2_grant.dart @@ -0,0 +1,91 @@ +part of '../../models.dart'; + +/// OAuth2 Grant +class Oauth2Grant implements Model { + /// Grant ID. + final String $id; + + /// Grant creation time in ISO 8601 format. + final String $createdAt; + + /// Grant update date in ISO 8601 format. + final String $updatedAt; + + /// ID of the user the grant belongs to. + final String userId; + + /// ID of the OAuth2 client (app) the grant was requested for. + final String appId; + + /// Requested OAuth2 scopes the user is being asked to consent to. + final List scopes; + + /// Requested RFC 8707 resource indicators the user is being asked to consent to. + final List resources; + + /// Requested authorization_details the user is being asked to consent to, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; + + /// OIDC prompt directive the consent screen should honor. Space-separated list of: login, consent, select_account. + final String prompt; + + /// Redirect URI the user will be sent to after the flow completes. + final String redirectUri; + + /// Unix timestamp of when the user last authenticated. + final int authTime; + + /// Grant expiration time in ISO 8601 format. + final String expire; + + Oauth2Grant({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.appId, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.prompt, + required this.redirectUri, + required this.authTime, + required this.expire, + }); + factory Oauth2Grant.fromMap( + Map map, + ) { + return Oauth2Grant( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + prompt: map['prompt'].toString(), + redirectUri: map['redirectUri'].toString(), + authTime: map['authTime'], + expire: map['expire'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "appId": appId, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "prompt": prompt, + "redirectUri": redirectUri, + "authTime": authTime, + "expire": expire, + }; + } +} diff --git a/lib/src/models/oauth2_organization.dart b/lib/src/models/oauth2_organization.dart new file mode 100644 index 00000000..bef13975 --- /dev/null +++ b/lib/src/models/oauth2_organization.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Organization +class Oauth2Organization implements Model { + /// Organization ID. + final String $id; + + Oauth2Organization({ + required this.$id, + }); + factory Oauth2Organization.fromMap( + Map map, + ) { + return Oauth2Organization( + $id: map['\$id'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + }; + } +} diff --git a/lib/src/models/oauth2_organization_list.dart b/lib/src/models/oauth2_organization_list.dart new file mode 100644 index 00000000..e9136230 --- /dev/null +++ b/lib/src/models/oauth2_organization_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible organizations list +class Oauth2OrganizationList implements Model { + /// Total number of organizations that matched your query. + final int total; + + /// List of organizations. + final List organizations; + + Oauth2OrganizationList({ + required this.total, + required this.organizations, + }); + factory Oauth2OrganizationList.fromMap( + Map map, + ) { + return Oauth2OrganizationList( + total: map['total'], + organizations: List.from( + map['organizations'].map((p) => Oauth2Organization.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "organizations": organizations.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_par.dart b/lib/src/models/oauth2_par.dart new file mode 100644 index 00000000..24c14ec5 --- /dev/null +++ b/lib/src/models/oauth2_par.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 PAR +class Oauth2PAR implements Model { + /// Authorization request handle to pass to the authorize endpoint. + final String request_uri; + + /// Lifetime of the authorization request handle in seconds. + final int expires_in; + + Oauth2PAR({ + required this.request_uri, + required this.expires_in, + }); + factory Oauth2PAR.fromMap( + Map map, + ) { + return Oauth2PAR( + request_uri: map['request_uri'].toString(), + expires_in: map['expires_in'], + ); + } + + @override + Map toMap() { + return { + "request_uri": request_uri, + "expires_in": expires_in, + }; + } +} diff --git a/lib/src/models/oauth2_project.dart b/lib/src/models/oauth2_project.dart new file mode 100644 index 00000000..306faf36 --- /dev/null +++ b/lib/src/models/oauth2_project.dart @@ -0,0 +1,37 @@ +part of '../../models.dart'; + +/// OAuth2 Project +class Oauth2Project implements Model { + /// Project ID. + final String $id; + + /// Region ID the project is deployed in. + final String region; + + /// API endpoint of the region the project is deployed in. Empty when the region has no public hostname configured. + final String endpoint; + + Oauth2Project({ + required this.$id, + required this.region, + required this.endpoint, + }); + factory Oauth2Project.fromMap( + Map map, + ) { + return Oauth2Project( + $id: map['\$id'].toString(), + region: map['region'].toString(), + endpoint: map['endpoint'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "region": region, + "endpoint": endpoint, + }; + } +} diff --git a/lib/src/models/oauth2_project_list.dart b/lib/src/models/oauth2_project_list.dart new file mode 100644 index 00000000..6eef6c21 --- /dev/null +++ b/lib/src/models/oauth2_project_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible projects list +class Oauth2ProjectList implements Model { + /// Total number of projects that matched your query. + final int total; + + /// List of projects. + final List projects; + + Oauth2ProjectList({ + required this.total, + required this.projects, + }); + factory Oauth2ProjectList.fromMap( + Map map, + ) { + return Oauth2ProjectList( + total: map['total'], + projects: List.from( + map['projects'].map((p) => Oauth2Project.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "projects": projects.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_reject.dart b/lib/src/models/oauth2_reject.dart new file mode 100644 index 00000000..26b94257 --- /dev/null +++ b/lib/src/models/oauth2_reject.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Reject +class Oauth2Reject implements Model { + /// URL the end user should be redirected to after the grant is rejected, carrying an `access_denied` error. + final String redirectUrl; + + Oauth2Reject({ + required this.redirectUrl, + }); + factory Oauth2Reject.fromMap( + Map map, + ) { + return Oauth2Reject( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_token.dart b/lib/src/models/oauth2_token.dart new file mode 100644 index 00000000..590264b2 --- /dev/null +++ b/lib/src/models/oauth2_token.dart @@ -0,0 +1,61 @@ +part of '../../models.dart'; + +/// OAuth2 Token +class Oauth2Token implements Model { + /// OAuth2 access token. + final String access_token; + + /// OAuth2 token type. + final String token_type; + + /// Access token lifetime in seconds. + final int expires_in; + + /// OAuth2 refresh token. + final String refresh_token; + + /// Space-separated scopes granted to the access token. + final String scope; + + /// Granted RFC 9396 authorization details as a JSON string. + final String? authorization_details; + + /// OpenID Connect ID token. Returned when the `openid` scope is granted. + final String? id_token; + + Oauth2Token({ + required this.access_token, + required this.token_type, + required this.expires_in, + required this.refresh_token, + required this.scope, + this.authorization_details, + this.id_token, + }); + factory Oauth2Token.fromMap( + Map map, + ) { + return Oauth2Token( + access_token: map['access_token'].toString(), + token_type: map['token_type'].toString(), + expires_in: map['expires_in'], + refresh_token: map['refresh_token'].toString(), + scope: map['scope'].toString(), + authorization_details: map['authorization_details']?.toString(), + id_token: map['id_token']?.toString(), + ); + } + + @override + Map toMap() { + return { + "access_token": access_token, + "token_type": token_type, + "expires_in": expires_in, + "refresh_token": refresh_token, + "scope": scope, + "authorization_details": authorization_details, + "id_token": id_token, + }; + } +} diff --git a/lib/src/mqtt.dart b/lib/src/mqtt.dart new file mode 100644 index 00000000..d55f1e8e --- /dev/null +++ b/lib/src/mqtt.dart @@ -0,0 +1,129 @@ +import 'mqtt_browser.dart' if (dart.library.io) 'mqtt_io.dart'; +import 'service.dart'; +import 'client.dart'; +import 'mqtt_message.dart'; + +/// A callback invoked for every message delivered on a subscribed topic. +typedef PushCallback = void Function(PushMessage message); + +/// Handle for a live subscription created with [Push.subscribe]. +/// +/// Unlike the realtime service's bare unsubscribe callable, a push subscription carries +/// per-subscription state (background delivery, notification title), so [subscribe] +/// returns this handle instead: [unsubscribe] drops it (and closes the connection once +/// the last one is gone) and [update] toggles its options live without resubscribing. +abstract class PushSubscription { + /// Drop this subscription. Closes the connection once the last one is gone. + void unsubscribe(); + + /// Live-update this subscription's [background] delivery, notification [title] and/or + /// [retry] (QoS). Only the arguments you pass change; the rest stay as they + /// were. Changing [retry] re-subscribes this subscription's topics at the + /// new QoS. + void update({bool? background, String? title, bool? retry}); +} + +/// Appwrite native push service — the realtime analog delivered over an MQTT +/// broker, without FCM or APNS. While the app is alive the connection stays open and each +/// message is handed to your callback; a subscription can also opt into background +/// delivery (a notification per message, and on mobile continued delivery while the app is +/// backgrounded or closed). +/// +/// The connection has no tunables — it always keeps its session (clean start off) so the +/// broker can redeliver missed messages, and reliability is chosen per subscription via +/// [subscribe]'s `retry`. TLS (and skipping cert verification via a +/// `?tlsInsecure=true` query flag) is derived from the endpoint, so the whole connection +/// is described in one place. `subscribe` opens the connection lazily and returns a +/// [PushSubscription] handle. The credential is read off the client — set a JWT or session +/// on it (`Client.setJWT` / `Client.setSession`), the same way every other service reads +/// auth. The broker location comes from `Client.setPushEndpoint()` (or the client +/// endpoint) and a stable id from `Client.setPushClientId()`. +/// +/// ```dart +/// final client = Client().setEndpoint('...').setProject('...').setJWT(jwt); +/// final push = Push(client); +/// final sub = await push.subscribe('user/123/#', (message) { +/// print('${message.topic}: ${message.data}'); +/// }); +/// +/// // sub.update(background: true, title: 'Messages'); +/// sub.unsubscribe(); +/// ``` +abstract class Push extends Service { + /// Initializes a [Push] service. + factory Push(Client client) => createPush(client); + + /// Register a callback invoked when the connection opens (CONNACK success). + Push onOpen(void Function() callback); + + /// Register a callback invoked when the connection closes. + Push onClose(void Function() callback); + + /// Register a callback invoked with every error the service hits: a failed or refused + /// connect or reconnect (carrying the broker's reason string when it sent one), a + /// DISCONNECT from the broker, a rejected SUBSCRIBE and background delivery failures. + /// Errors a call also throws (such as [subscribe]'s) are reported here as well. Errors that + /// no call throws are never thrown, so they cannot crash the app: with no callback + /// registered they are logged. + Push onError(void Function(Object error) callback); + + /// Subscribe to one or more topics, resolving to a [PushSubscription] handle. + /// + /// [topics] is a single topic or a list of them, each a string or a `Topic` builder + /// (e.g. `Topic.path(['user', userId]).all()`). Pass `null` to subscribe to the + /// signed-in user's own `users/` topic ("messages for me") without knowing any + /// topic: the user id is read off the client's JWT (or, without one, its session) with + /// no network call, and `AppwriteException` is thrown when neither is set. + /// Like FCM/APNs delivery, the `null` form defaults to [background] `true` (topics default to + /// `false`) and, as always, [retry] `true` (QoS 1); pass either to override. + /// + /// ```dart + /// final sub = await push.subscribe(null, (message) { + /// print(message.data); + /// }); + /// ``` + /// + /// The future resolves only once every subscription has been acknowledged (SUBACK), so a + /// subscribe-then-publish is reliable, and [onOpen]/[onClose]/[onError] observe the + /// in-process connection. On Android a [background] subscription moves the connection to the + /// SDK's native plugin, which also resolves after SUBACK and forwards messages and errors (to + /// [onError]) but not its connection lifecycle, so [onOpen]/[onClose] do not fire for it. On + /// iOS it hands the connection to a background isolate, which subscribes asynchronously and + /// retries failures internally, so it resolves once the isolate has the subscription. + /// + /// [retry] chooses this subscription's delivery guarantee: `true` (the + /// default) subscribes at QoS 1 so the broker holds this topic's messages and redelivers + /// them on reconnect; `false` uses QoS 0 (at-most-once, may be lost). The connection + /// always keeps its session, so replay is a purely per-subscription choice. + /// + /// Set [background] to also keep receiving while the app is backgrounded or closed and post a + /// notification per message with [title] (defaulting to the message topic). Toggle these + /// later with [PushSubscription.update]. + /// + /// On Android the SDK's native plugin saves the subscription and keeps delivering after the + /// app is killed, the device restarts or the app updates, until it is unsubscribed or [close] + /// is called: a scheduled job and alarm wake the app every 15 to 60 seconds to reconnect, and + /// the broker replays what was sent in between ([retry]). [setForeground] adds a foreground + /// service for immediate delivery. It reconnects with the credential saved at subscribe time, + /// so use a session rather than a short-lived JWT. On iOS it runs the connection in a + /// background isolate via `flutter_background_service`; on the web it posts a browser + /// notification while the tab is open. + Future subscribe( + Object? topics, // String, Topic, ResolvedTopic, a List, or null (own user) + PushCallback callback, { + bool? background, + String? title, + bool retry, + }); + + /// Android: run background delivery in a foreground service (with a quiet ongoing + /// notification), for immediate delivery even after the app is killed and during Doze, + /// instead of only the scheduled wake-ups. Saved, so it applies after restarts too. Call it + /// while the app is in the foreground: Android 12+ refuses to start the service from the + /// background. It only affects [background] subscriptions. A no-op elsewhere. + Future setForeground(bool enabled); + + /// Tear down the connection and drop all subscriptions. On Android this also stops + /// background delivery, including subscriptions saved by an earlier run: call it on sign-out. + void close(); +} diff --git a/lib/src/mqtt_browser.dart b/lib/src/mqtt_browser.dart new file mode 100644 index 00000000..4e291b43 --- /dev/null +++ b/lib/src/mqtt_browser.dart @@ -0,0 +1,904 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +// ignore: avoid_web_libraries_in_flutter, deprecated_member_use +import 'dart:html' as html; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_browser_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_message.dart'; + +Push createPush(Client client) => PushWeb(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +/// Web push transport. A browser cannot open a raw TCP socket, so the connection is +/// MQTT over WebSocket (`ws://` / `wss://`) via [MqttBrowserClient]; the native +/// (`dart:io`) build in `mqtt_io.dart` uses a TCP socket instead. The API is identical. +class PushWeb implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final String _path; + + MqttBrowserClient? _mqtt; + Future? _connecting; + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across reloads; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushWeb(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "wss://host"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: WSS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = _pushEndpointPort(client) ?? (resolvedTls ? 443 : 80); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushWeb._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + path: _pushPath(client), + ); + } + + PushWeb._( + this.client, { + required String host, + required int port, + required bool tls, + required String path, + }) : _host = host, + _port = port, + _tls = tls, + _path = path; + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across reloads. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // The WebSocket path from an explicitly-set push endpoint, or the root path by + // default (the broker serves MQTT-over-WebSocket at the root; no "/mqtt" is appended). + static String _pushPath(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint != null) { + try { + final path = Uri.parse(endpoint).path; + if (path.isNotEmpty && path != '/') { + return path; + } + } catch (_) {} + } + return ''; + } + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + return this; + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + final MqttBrowserClient mqtt; + try { + topicList = _topicList(client, topics); + mqtt = await _connect(); + } catch (e) { + if (e is _Superseded) { + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + _notify(e); + rethrow; + } + final epoch = _connectionEpoch; + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + + if (wantsBackground) { + _requestNotificationPermission(); + } + + final ids = []; + final acks = >[]; + + void unsubscribe() { + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + // A filter that lost its last QoS-1 sub but still has QoS-0 subs must be re-subscribed + // lower, or the broker keeps replaying to at-most-once subs. + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + close(); + } + } + + // The broker only starts routing a topic once its subscription is registered, + // so publishing before the SUBACK races the message ahead of the subscription + // and it is dropped (no retained replay on MQTT). Awaiting makes it reliable. + // If any topic's SUBACK fails, roll this call's registrations back (and drop any + // now-unused broker filter) so a failed subscribe leaks no callback, then rethrow. + try { + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + + final completer = Completer(); + (_subAcks[topic] ??= >[]).add(completer); + acks.add(completer.future); + + final subscription = MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(topic), + _effectiveQos(topic), + ); + mqtt.subscribeWithSubscriptionList([subscription]); + } + await Future.wait(acks); + } catch (e) { + if (epoch != _connectionEpoch) { + for (final id in ids) { + _subscriptions.remove(id); + } + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + unsubscribe(); + _notify(e); + rethrow; + } + + void update({bool? background, String? title, bool? retry}) { + final changedFilters = {}; + for (final id in ids) { + final entry = _subscriptions[id]; + if (entry == null) { + continue; + } + if (background != null) { + entry.background = background; + } + if (title != null) { + entry.title = title; + } + if (retry != null && retry != entry.retry) { + entry.retry = retry; + changedFilters.add(entry.filter); + } + } + if (background == true) { + _requestNotificationPermission(); + } + // Re-subscribe affected filters at their new effective QoS. + // A rejected SUBACK reaches onError through [_onSubscribeFail]. + for (final filter in changedFilters) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } catch (e) { + _report(e); + } + } + } + + return _SubscriptionHandle(unsubscribe, update); + } + + void _requestNotificationPermission() { + if (html.Notification.permission != 'granted') { + unawaited( + html.Notification.requestPermission().then( + (_) {}, + onError: _report, + ), + ); + } + } + + // Background delivery on the web is a notification while the tab is open; there is no + // foreground service. + @override + Future setForeground(bool enabled) async {} + + @override + void close() { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _subscriptions.clear(); + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + _mqtt?.disconnect(); + _mqtt = null; + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + _path, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + final clientId = _resolvedClientId; + + final scheme = _tls ? 'wss' : 'ws'; + final mqtt = MqttBrowserClient.withPort( + '$scheme://$_host$_path', + clientId, + _port, + ); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // The broker negotiates the "mqtt" WebSocket subprotocol; offer exactly that so the + // handshake succeeds (a browser rejects the socket when the subprotocol is not echoed). + mqtt.websocketProtocols = MqttConstants.protocolsSingleDefault; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + final filters = _subscriptions.values.map((s) => s.filter).toSet(); + for (final filter in filters) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + // Notification is per-subscription: only subs that opted in show one, each + // with its own title. + if (subscription.background && + html.Notification.permission == 'granted') { + html.Notification(subscription.title ?? topic, body: message.data); + } + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect or a QoS change), so + // onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_foreground.dart b/lib/src/mqtt_foreground.dart new file mode 100644 index 00000000..8636f355 --- /dev/null +++ b/lib/src/mqtt_foreground.dart @@ -0,0 +1,322 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' show DartPluginRegistrant; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; + +/// Android/iOS background delivery for the native (dart:io) push service. +/// +/// Flutter cannot keep the app's own isolate running once the app is closed, so a +/// subscription with `background: true` runs the push connection inside a background isolate +/// held alive by an Android foreground service ([FlutterBackgroundService]). That isolate +/// owns the single MQTT connection, posts a local notification per message +/// ([FlutterLocalNotificationsPlugin]) for the filters that opted into background, and +/// forwards every message back to the app (when it is alive) over a service event so in-app +/// callbacks still fire — mirroring the Android/React Native SDKs' foreground mode. +/// +/// Config is handed to the isolate through a small JSON file in the app documents +/// directory (the isolate does not share the app's memory), and the running isolate is kept +/// in sync via service events. The config file (which holds the credential) is deleted when +/// background delivery stops. + +const String _channelId = 'appwrite-push'; +const String _channelName = 'Notifications'; +const String _messageEvent = 'appwrite.push.message'; +const String _topicsEvent = 'appwrite.push.topics'; +const String _stopEvent = 'appwrite.push.stop'; +const String _errorEvent = 'appwrite.push.error'; + +// How long to wait before retrying a background subscription that failed (SUBACK/connect), +// so delivery converges instead of silently missing messages. +const Duration _retryDelay = Duration(seconds: 2); + +/// The service event the app listens on to forward background messages to callbacks. +String get pushForegroundMessageEvent => _messageEvent; + +/// The service event the isolate relays its errors on, so the app's onError sees them. +String get pushForegroundErrorEvent => _errorEvent; + +// Relay an isolate error to the app (if alive) as its message. +void _relayError(ServiceInstance service, Object error) { + service.invoke(_errorEvent, { + 'message': + error is AppwriteException + ? (error.message ?? error.toString()) + : error.toString(), + }); +} + +Future _configFile() async { + final dir = await getApplicationDocumentsDirectory(); + return File('${dir.path}/appwrite_push_foreground.json'); +} + +Future _writeConfig( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + final config = { + 'endpoint': client.endPoint, + 'endpointPush': client.config['endpointPush'], + 'project': client.config['project'] ?? '', + 'jwt': client.config['jwt'] ?? client.config['jWT'], + 'session': client.config['session'], + 'pushClientId': client.config['pushClientId'], + 'title': serviceTitle, + 'topics': topics, + 'notify': notify, + 'qos': qos, + }; + (await _configFile()).writeAsStringSync(jsonEncode(config)); +} + +// Delete the config file (which holds the credential) so it does not linger on disk after +// background delivery ends. +Future _deleteConfig() async { + try { + final file = await _configFile(); + if (file.existsSync()) { + file.deleteSync(); + } + } catch (_) {} +} + +/// Start the background service (or, if already running, update its topics/notify config +/// live). Called on the app isolate whenever the set of background subscriptions changes. +/// [topics] is the full union the single connection subscribes to; [notify] maps the filters +/// that opted into background to their notification titles. +Future syncPushForeground( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + await _writeConfig( + client, + serviceTitle: serviceTitle, + topics: topics, + notify: notify, + qos: qos, + ); + + final service = FlutterBackgroundService(); + if (await service.isRunning()) { + // The isolate is already up: hand it the new topic/notify/qos set so a later + // subscribe/unsubscribe/update takes effect without a restart. + service.invoke(_topicsEvent, { + 'topics': topics, + 'notify': notify, + 'qos': qos, + }); + return; + } + + await service.configure( + androidConfiguration: AndroidConfiguration( + onStart: pushForegroundEntry, + isForegroundMode: true, + autoStart: false, + notificationChannelId: _channelId, + initialNotificationTitle: serviceTitle, + initialNotificationContent: 'Listening for messages', + ), + iosConfiguration: IosConfiguration( + onForeground: pushForegroundEntry, + autoStart: false, + ), + ); + await service.startService(); +} + +/// Ask the background service to disconnect and stop, and delete the config file. +Future stopPushForeground() async { + FlutterBackgroundService().invoke(_stopEvent); + await _deleteConfig(); +} + +Map _notifyOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', '$value')); + } + return {}; +} + +Map _qosOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', (value as num).toInt())); + } + return {}; +} + +/// Background isolate entry point: opens the connection, subscribes to the persisted +/// topics (kept in sync via [_topicsEvent]), posts a notification per message for the +/// filters that opted into background and forwards every message to the app. +@pragma('vm:entry-point') +Future pushForegroundEntry(ServiceInstance service) async { + WidgetsFlutterBinding.ensureInitialized(); + DartPluginRegistrant.ensureInitialized(); + + final notifications = FlutterLocalNotificationsPlugin(); + final Map config; + try { + await notifications.initialize( + const InitializationSettings( + android: AndroidInitializationSettings('@mipmap/ic_launcher'), + iOS: DarwinInitializationSettings(), + ), + ); + config = + jsonDecode((await _configFile()).readAsStringSync()) + as Map; + } catch (e) { + _relayError( + service, + AppwriteException('Background push failed to start: $e'), + ); + await _deleteConfig(); + service.stopSelf(); + return; + } + + final client = Client() + .setEndpoint(config['endpoint'] as String) + .setProject(config['project'] as String); + final jwt = config['jwt'] as String?; + final session = config['session'] as String?; + if (jwt != null && jwt.isNotEmpty) { + client.setJWT(jwt); + } else if (session != null && session.isNotEmpty) { + client.setSession(session); + } + final endpointPush = config['endpointPush'] as String?; + if (endpointPush != null && endpointPush.isNotEmpty) { + client.setPushEndpoint(endpointPush); + } + final pushClientId = config['pushClientId'] as String?; + if (pushClientId != null && pushClientId.isNotEmpty) { + client.setPushClientId(pushClientId); + } + + // Connection, subscribe and broker errors go to the app's onError. A failed subscribe + // reaches it through here and is then retried below. + final push = Push(client).onError((error) => _relayError(service, error)); + + // filter -> notification title, for the filters that opted into background. Reassigned on + // each [_topicsEvent]; the subscribe closures read the current map, so title/opt-in changes + // take effect without resubscribing. + var notify = _notifyOf(config['notify']); + // filter -> QoS (1 reliable / 0 not) requested by the app for each topic. + var qos = _qosOf(config['qos']); + + // One broker subscription per topic so topics can be added/removed independently as the + // app's subscriptions change, plus the QoS each is currently subscribed at (so a QoS + // change resubscribes rather than being skipped as "already subscribed"). + final subscriptions = {}; + final subscribedQos = {}; + + Future applyTopics(List topics) async { + final wanted = topics.toSet(); + for (final topic in subscriptions.keys.toList()) { + if (!wanted.contains(topic)) { + subscriptions.remove(topic)?.unsubscribe(); + subscribedQos.remove(topic); + } + } + for (final topic in wanted) { + final desiredQos = qos[topic] ?? 1; + if (subscriptions.containsKey(topic)) { + if (subscribedQos[topic] == desiredQos) { + continue; + } + // QoS changed for this topic: drop and resubscribe at the new level. + subscriptions.remove(topic)?.unsubscribe(); + } + final filter = topic; + subscribedQos[topic] = desiredQos; + subscriptions[topic] = await push.subscribe(topic, (message) { + // Notify only for filters that opted into background, each with its own title. + final title = notify[filter]; + if (title != null) { + notifications.show( + message.topic.hashCode, + title, + message.data, + const NotificationDetails( + android: AndroidNotificationDetails( + _channelId, + _channelName, + importance: Importance.high, + ), + iOS: DarwinNotificationDetails(), + ), + ); + } + // Forward to the app isolate (if alive) so in-app callbacks still fire. + service.invoke(_messageEvent, { + 'topic': message.topic, + 'payload': message.data, + 'qos': message.qos, + }); + }, retry: desiredQos == 1); + } + } + + // Serialize topic updates: applyTopics awaits push.subscribe, so overlapping runs could + // otherwise subscribe a topic twice (losing an unsubscribe handle) or apply out of order. + // Chaining runs them one at a time, in arrival order. + var topicQueue = Future.value(); + // The last requested topic set, so a failed subscribe can be retried against what is + // currently wanted (topics may have changed again by the time the retry fires). + var wantedTopics = []; + var retryScheduled = false; + + void queueTopics(List topics) { + wantedTopics = topics; + // A subscribe can fail (SUBACK refused, connection dropped mid-CONNECT); applyTopics + // skips already-subscribed topics, so retrying the current wanted set converges on the + // missing ones instead of silently dropping them. + topicQueue = topicQueue.then((_) => applyTopics(topics)).catchError(( + Object _, + ) { + if (retryScheduled) { + return; + } + retryScheduled = true; + Timer(_retryDelay, () { + retryScheduled = false; + queueTopics(wantedTopics); + }); + }); + } + + service.on(_topicsEvent).listen((data) { + notify = _notifyOf(data?['notify']); + qos = _qosOf(data?['qos']); + final topics = + ((data?['topics'] as List?) ?? const []).cast(); + queueTopics(topics); + }); + + service.on(_stopEvent).listen((_) async { + for (final subscription in subscriptions.values) { + subscription.unsubscribe(); + } + push.close(); + await _deleteConfig(); + service.stopSelf(); + }); + + queueTopics((config['topics'] as List).cast()); +} diff --git a/lib/src/mqtt_io.dart b/lib/src/mqtt_io.dart new file mode 100644 index 00000000..de665f10 --- /dev/null +++ b/lib/src/mqtt_io.dart @@ -0,0 +1,1333 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_server_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_foreground.dart'; +import 'mqtt_message.dart'; +import 'mqtt_native.dart'; + +Push createPush(Client client) => PushIO(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +class PushIO implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final bool _tlsInsecure; + + MqttServerClient? _mqtt; + Future? _connecting; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across restarts; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Whether the connection currently lives in the background isolate (foreground service) + // rather than in-process. The connection relocates there while any subscription wants + // background delivery, and back in-process once none do — one connection either way, so + // the broker never sees two sessions with the same client id. + bool _isolateActive = false; + StreamSubscription?>? _serviceListener; + StreamSubscription?>? _serviceErrorListener; + + // On Android the native plugin hosts background delivery instead of the isolate, on the same + // core as the Android SDK. Null elsewhere. + final PushNative? _native = PushNative.instance; + // Whether the subscriptions currently live on the native plugin's connection. + bool _nativeActive = false; + // Bumped when the subscriptions move to the native host, or the credential changes, + // superseding an _open in flight. + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + StreamSubscription>? _nativeListener; + + // Every Push on Android shares the one native host (one connection per client id), which hosts + // the union of their subscriptions. Native calls run one at a time in call order, so a sign-out + // is never undone by a subscribe still on its way. + static final Set _nativeHosts = {}; + // Every Push with live subscriptions, so the native host can take over their connections. + static final Set _livePushes = {}; + static Future _nativeQueue = Future.value(); + + static Future _enqueueNative(Future Function() op) { + final result = _nativeQueue.then((_) => op()); + _nativeQueue = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Serializes background config writes (topic/notify syncs and stops). Each write is a + // file write plus a service event, so unserialized rapid calls could interleave and apply + // out of order. Chaining runs them in call order; each reads the current state when it + // runs, so the last requested value always wins. + Future _backgroundSync = Future.value(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushIO(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "mqtts://host:8883"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: TLS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = + _pushEndpointPort(client) ?? (resolvedTls ? 8883 : 1883); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushIO._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + tlsInsecure: _insecureFlag(client), + ); + } + + PushIO._( + this.client, { + required String host, + required int port, + required bool tls, + required bool tlsInsecure, + }) : _host = host, + _port = port, + _tls = tls, + _tlsInsecure = tlsInsecure { + // Resume background delivery saved by an earlier run now, instead of at its next + // scheduled wake-up. + unawaited(_native?.resume().catchError(_report)); + } + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across restarts. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // Skip TLS cert verification (self-signed brokers / testing) via a query flag on the push + // endpoint, e.g. "mqtts://host:8883?tlsInsecure=true" — so the whole connection is + // described by one URL, not a second config knob. + static bool _insecureFlag(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return false; + } + try { + final value = Uri.parse(endpoint).queryParameters['tlsInsecure']; + return value == 'true' || value == '1'; + } catch (_) { + return false; + } + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + // On Android, a refused credential that stopped background delivery while no callback + // was registered is delivered now. + final native = _native; + if (native != null) { + unawaited(() async { + try { + final stopped = await native.setErrorCallback(true); + if (stopped != null) { + _report(AppwriteException(stopped)); + } + } catch (e) { + _report(e); + } + }()); + } + return this; + } + + @override + Future setForeground(bool enabled) async { + await _native?.setForeground(enabled); + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + if (error is _Superseded) { + // Internal: a connection superseded by the native host, not a failure. + return; + } + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + try { + topicList = _topicList(client, topics); + } catch (e) { + _notify(e); + rethrow; + } + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + _livePushes.add(this); + + final ids = []; + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + } + + try { + final native = _native; + if (native != null && + (_backgroundWanted || + _nativeHosts.isNotEmpty || + await native.hasSaved())) { + // Android: the native plugin hosts the single connection while any subscription, live + // or saved by an earlier run, wants background. + await _hostNative(); + } else if (_backgroundWanted) { + // Any sub wants background: the isolate hosts the single connection (relocating + // off the in-process one if it was up) and covers the whole topic union. + await _hostInIsolate(); + } else { + while (true) { + try { + await _subscribeInProcess(ids); + break; + } on _Superseded { + // Another Push moved this one's subscriptions to the native host meanwhile: this + // subscribe goes there too. + if (_nativeActive) { + await _hostNative(); + break; + } + } + } + } + } catch (e) { + for (final id in ids) { + _subscriptions.remove(id); + } + // Return to a consistent host for whatever subscriptions remain. + _reconcile(); + _notify(e); + rethrow; + } + + return _SubscriptionHandle( + () => _unsubscribeIds(ids), + ({bool? background, String? title, bool? retry}) => + _updateIds(ids, background: background, title: title, retry: retry), + ); + } + + // In-process host: connect and register this call's new filters, awaiting each SUBACK. + Future _subscribeInProcess(List ids) async { + final mqtt = await _connect(); + final acks = >[]; + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + final completer = Completer(); + (_subAcks[sub.filter] ??= >[]).add(completer); + acks.add(completer.future); + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(sub.filter), + _effectiveQos(sub.filter), + ), + ]); + } + // The broker only starts routing a topic once its subscription is registered, so + // publishing before the SUBACK races the message ahead of it. Awaiting makes it reliable. + await Future.wait(acks); + } + + // Host every subscription of every Push on the native plugin's connection (Android), closing + // this one's in-process connection. Completes once the connection is up and every filter is + // subscribed (SUBACK), or throws why not. + Future _hostNative() { + final native = _native!; + final key = _credentialKey; + // The native host carries one connection, so it serves one credential: instances hosted for + // another move back to their own connection. Instances with this credential share its client + // id, so their in-process connections would take over the broker session: they move to the + // native host too. + for (final push in _nativeHosts.toList()) { + if (push._credentialKey != key) { + push._leaveToInProcess(); + if (push._backgroundWanted) { + push._report(AppwriteException(_backgroundDisplaced)); + } + } + } + // Once moved, they stay: if hosting fails, the native host keeps their subscriptions and + // retries on its scheduled runs, and a second connection with the same client id would take + // over its broker session. + for (final push in _livePushes.toList()) { + if (push._subscriptions.isNotEmpty && push._credentialKey == key) { + push._joinNative(native); + } + } + _joinNative(native); + return _enqueueNative(() => _sendToNative(native)); + } + + // Host every native host's subscriptions with this Push's credential. + Future _sendToNative(PushNative native) async { + // Host what is subscribed when this runs, so a close() or an unsubscribe queued meanwhile + // is not undone by an older request. + final subscriptions = [ + for (final push in _nativeHosts) ...push._nativeEntries, + ]; + if (subscriptions.isEmpty) { + return; + } + final (authMethod, credential) = _credential(); + final config = { + 'host': _host, + 'port': _port, + 'tls': _tls, + 'tlsInsecure': _tlsInsecure, + 'clientId': _resolvedClientId, + 'authMethod': authMethod, + 'credential': credential, + 'project': client.config['project'] ?? '', + }; + await native.setErrorCallback( + _nativeHosts.any((push) => push._onError != null), + ); + await native.host(jsonEncode(config), jsonEncode(subscriptions)); + } + + // Move this Push's subscriptions onto the native host, closing its own connection. + void _joinNative(PushNative native) { + // An _open still in flight sees this and closes what it opened, and a subscribe still waiting + // for its SUBACK continues on the native host. + _dropConnection(); + _nativeListener ??= native.listen( + onMessage: (message) { + final sub = _subscriptions[message.id]; + if (sub == null) { + return; + } + try { + sub.callback( + PushMessage( + topic: message.topic, + payload: message.payload, + qos: message.qos, + ), + ); + } catch (e) { + _report(e); + } + // Acknowledged once its callback has run, as on the in-process connection. + unawaited(native.ack(message.ackToken).catchError(_report)); + }, + onError: (message) => _report(AppwriteException(message)), + ); + _nativeHosts.add(this); + _nativeActive = true; + } + + void _dropConnection() { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + } + } + + // Move this Push's subscriptions back onto its own connection. + void _leaveToInProcess() { + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + + // Identifies the connection this Push authenticates: one native host serves one. + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + // This Push's subscriptions in the native plugin's format. + List> get _nativeEntries => [ + for (final entry in _subscriptions.entries) + { + 'id': entry.key, + 'topic': entry.value.filter, + 'background': entry.value.background, + 'title': entry.value.title, + 'retry': entry.value.retry, + }, + ]; + + // After an unsubscribe or update on Android: keep the native plugin hosting while any + // subscription, live (of any Push) or saved, wants background, else move the live ones back + // in-process. + Future _reconcileNative(PushNative native) async { + if (_subscriptions.isEmpty) { + // This Push has nothing left; saved subscriptions keep delivering in the background. + if (_nativeActive) { + await _leaveNative(native); + } + return; + } + final wanted = + {..._nativeHosts, this}.any((push) => push._backgroundWanted) || + await native.hasSaved(); + if (wanted) { + await _hostNative(); + return; + } + // Nothing wants background: every Push moves back to its own connection. + final hosts = _nativeHosts.toList(); + _nativeHosts.clear(); + for (final push in hosts) { + push._nativeActive = false; + } + await _enqueueNative(() => native.release()); + for (final push in {...hosts, this}) { + if (push._subscriptions.isNotEmpty) { + await push._ensureInProcessSubscribed(); + } + } + } + + // Stop hosting this Push natively; the others' subscriptions stay hosted. + Future _leaveNative(PushNative native) { + _nativeHosts.remove(this); + _nativeActive = false; + if (_nativeHosts.isNotEmpty) { + return _nativeHosts.first._hostNative(); + } + return _enqueueNative(() => native.release()); + } + + // Relocate the connection into the background isolate and sync it with the current topic + // union and per-subscription notification config. + Future _hostInIsolate() async { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + await _syncBackground(); + } + + // Listen for messages the background isolate relays back and forward them to every + // matching in-app callback (so callbacks still fire while the app is alive, background or + // not). Idempotent. + void _attachServiceListener() { + _serviceListener ??= FlutterBackgroundService() + .on(pushForegroundMessageEvent) + .listen((data) { + if (data == null) { + return; + } + final topic = data['topic'] as String? ?? ''; + final payload = Uint8List.fromList( + utf8.encode(data['payload'] as String? ?? ''), + ); + final message = PushMessage( + topic: topic, + payload: payload, + qos: data['qos'] as int? ?? 0, + ); + for (final sub in _subscriptions.values) { + if (_matches(sub.filter, topic)) { + sub.callback(message); + } + } + }); + // The isolate's own connection/subscribe errors, relayed as their message. + _serviceErrorListener ??= FlutterBackgroundService() + .on(pushForegroundErrorEvent) + .listen((data) { + _report( + AppwriteException( + data?['message'] as String? ?? 'Background push failed', + ), + ); + }); + } + + void _detachServiceListener() { + _serviceListener?.cancel(); + _serviceListener = null; + _serviceErrorListener?.cancel(); + _serviceErrorListener = null; + } + + bool get _backgroundWanted => _subscriptions.values.any((s) => s.background); + + // The union of every subscription's filter (the isolate hosts one connection for all). + List get _backgroundTopics => + _subscriptions.values.map((s) => s.filter).toSet().toList(); + + // filter -> notification title, for filters that have at least one background subscription + // (those are the only ones that post a notification, each with its own title). + Map get _notifyConfig { + final map = {}; + for (final sub in _subscriptions.values) { + if (sub.background) { + map[sub.filter] = sub.title ?? _defaultTitle; + } + } + return map; + } + + String get _defaultTitle => 'Appwrite'; + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + // filter -> QoS (1 reliable / 0 not), handed to the isolate so it subscribes each topic + // at the right level. + Map get _qosConfig { + final map = {}; + for (final filter in _backgroundTopics) { + map[filter] = _effectiveQos(filter) == MqttQos.atLeastOnce ? 1 : 0; + } + return map; + } + + // Run a background config write after any already-queued one, so writes never interleave + // or reorder. The returned future carries this write's own result to its caller, while the + // chain itself never rejects (a failed write must not stall later ones). + Future _enqueueBackground(Future Function() op) { + final result = _backgroundSync.then((_) => op()); + _backgroundSync = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Sync the running/started isolate with the current topic union and notify config. + Future _syncBackground() => _enqueueBackground(() async { + // Skip if background was turned off after this was queued, so a stale write can't + // recreate the credential file after shutdown deleted it. + if (!_backgroundWanted) { + return; + } + await syncPushForeground( + client, + serviceTitle: _defaultTitle, + topics: _backgroundTopics, + notify: _notifyConfig, + qos: _qosConfig, + ); + }); + + // Enqueue the background stop after any pending config write, so the credential file is + // always deleted last — a write queued just before shutdown cannot recreate it afterwards. + void _enqueueStop() { + unawaited( + _enqueueBackground(() async { + // Skip if background is wanted again by the time this runs, so a stale stop can't + // tear down a live connection or delete a credential config that is still in use. + if (_backgroundWanted) { + return; + } + await stopPushForeground(); + }).catchError(_report), + ); + } + + // Ensure the correct host (in-process vs isolate) for whatever subscriptions remain, and + // sync it. Called after an unsubscribe/update may have flipped whether background is wanted. + void _reconcile() { + final native = _native; + if (native != null) { + unawaited(_reconcileNative(native).catchError(_report)); + return; + } + if (_subscriptions.isEmpty) { + return; + } + if (_backgroundWanted) { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + unawaited(_syncBackground().catchError(_report)); + } else { + if (_isolateActive) { + _isolateActive = false; + _detachServiceListener(); + _enqueueStop(); + } + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + } + + // Bring up the in-process connection and (re)register every filter — used when the last + // background subscription goes away and the connection relocates back in-process. Nobody + // awaits it, so a rejected SUBACK reaches onError through [_onSubscribeFail]. + Future _ensureInProcessSubscribed() async { + final mqtt = await _connect(); + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + + void _unsubscribeIds(List ids) { + // Filters whose removed sub was QoS 1: their effective QoS may now drop. + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed && _mqtt != null) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + // The last live subscription is gone; on Android, saved ones keep delivering. + _teardown(); + _reconcile(); + return; + } + // A removed sub may have been the last background one (relocate in-process) or just + // change the isolate's topic/notify set (the isolate re-sync carries the new QoS map). + _reconcile(); + // In-process, a filter that lost its last QoS-1 sub but still has QoS-0 subs must be + // re-subscribed lower, or the broker keeps replaying to at-most-once subs. + if (!_backgroundWanted && !_nativeActive && _mqtt != null) { + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + } + } + + void _updateIds( + List ids, { + bool? background, + String? title, + bool? retry, + }) { + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + if (background != null) { + sub.background = background; + } + if (title != null) { + sub.title = title; + } + if (retry != null) { + sub.retry = retry; + } + } + // reconcile re-subscribes (in-process) / re-syncs the isolate at the new effective QoS. + _reconcile(); + } + + /// Tear down the connection and drop all subscriptions. On Android, closing the last Push that + /// uses background delivery also stops it, including subscriptions saved by an earlier run: + /// call it on sign-out. While other Push instances still use it, it keeps delivering their + /// subscriptions and the saved ones. + @override + void close() { + _teardown(); + final native = _native; + if (native == null) { + return; + } + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_nativeListener?.cancel()); + _nativeListener = null; + if (_nativeHosts.isNotEmpty) { + final other = _nativeHosts.first; + unawaited(other._hostNative().catchError(other._report)); + return; + } + unawaited(_enqueueNative(() => native.stop()).catchError(_report)); + } + + // Close the in-process connection (and the isolate host) and drop the live subscriptions. + void _teardown() { + _livePushes.remove(this); + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _detachServiceListener(); + _subscriptions.clear(); + if (_isolateActive) { + _isolateActive = false; + _enqueueStop(); + } + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _dropConnection(); + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + // On Android the native plugin's per-user-and-install id is used when none was set, so this + // connection and the background one share the broker session. + final native = _native; + final clientId = + _resolvedClientId.isEmpty && native != null + ? await native.defaultClientId(authMethod, credential) + : _resolvedClientId; + // The subscriptions moved to the native host while this was waiting: its connection would + // share the host's client id and take over the broker session. + if (epoch != _connectionEpoch) { + throw const _Superseded(); + } + + final mqtt = MqttServerClient.withPort(_host, clientId, _port); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + if (_tls) { + mqtt.secure = true; + if (_tlsInsecure) { + mqtt.onBadCertificate = (dynamic certificate) => true; + } + } + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + // Superseded by the native host, which closed this connection on purpose. + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect, a QoS change or a + // relocation back in-process), so onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +// Reported to a Push whose background delivery stopped because a Push with another credential +// took over the native host, which carries one connection and so serves one credential. +const String _backgroundDisplaced = + 'Background delivery stopped: a Push with another credential started background delivery, ' + 'and the device hosts one. These subscriptions still deliver while the app runs.'; + +// An in-process connect superseded by moving the subscriptions to the native host, or by a +// connect with another credential. +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_message.dart b/lib/src/mqtt_message.dart new file mode 100644 index 00000000..9faa825a --- /dev/null +++ b/lib/src/mqtt_message.dart @@ -0,0 +1,24 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// A message delivered on a subscribed topic — the MQTT push analog of a +/// realtime event. +class PushMessage { + /// The topic the message was published to. + final String topic; + + /// The raw message payload. + final Uint8List payload; + + /// The MQTT quality of service the message was delivered with. + final int qos; + + const PushMessage({ + required this.topic, + required this.payload, + required this.qos, + }); + + /// The payload decoded as UTF-8 text, as it was sent. + String get data => utf8.decode(payload); +} diff --git a/lib/src/mqtt_native.dart b/lib/src/mqtt_native.dart new file mode 100644 index 00000000..11509936 --- /dev/null +++ b/lib/src/mqtt_native.dart @@ -0,0 +1,128 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// A message the native Android plugin delivers for a hosted subscription. +class NativePushMessage { + final String id; + final String topic; + final Uint8List payload; + final int qos; + + /// Passed to [PushNative.ack] once the callback has run; the broker's PUBACK waits for it. + final String ackToken; + + NativePushMessage(this.id, this.topic, this.payload, this.qos, this.ackToken); +} + +/// The SDK's native Android plugin (see android/), which hosts background delivery on the same +/// core as the Appwrite Android SDK: saved subscriptions, scheduled wake-ups after +/// the app is killed, reboot resume, notifications and foreground mode. +class PushNative { + static const String _methodChannel = 'appwrite.push'; + static const String _eventChannel = 'appwrite.push/events'; + static final PushNative _plugin = PushNative._( + const MethodChannel(_methodChannel), + const EventChannel(_eventChannel), + ); + + final MethodChannel _methods; + final EventChannel _events; + Stream>? _stream; + + PushNative._(this._methods, this._events); + + /// The plugin's channels on [messenger] instead of the engine's, for tests that stand in for + /// the plugin. + @visibleForTesting + PushNative.forMessenger(BinaryMessenger messenger) + : _methods = MethodChannel( + _methodChannel, + const StandardMethodCodec(), + messenger, + ), + _events = EventChannel( + _eventChannel, + const StandardMethodCodec(), + messenger, + ); + + /// Used instead of the plugin by [Push] instances created while it is set, in tests. + @visibleForTesting + static PushNative? debugInstance; + + /// The plugin on Android, else null. + static PushNative? get instance => + debugInstance ?? (Platform.isAndroid ? _plugin : null); + + /// Host [subscriptionsJson] on the background connection described by [configJson]. Completes + /// once the connection is up and every filter is subscribed, or throws why not. + Future host(String configJson, String subscriptionsJson) => + _methods.invokeMethod('host', { + 'config': configJson, + 'subscriptions': subscriptionsJson, + }); + + /// Acknowledge a message once its callback has run. + Future ack(String token) => + _methods.invokeMethod('ack', {'token': token}); + + /// Stop hosting the live subscriptions, keeping the ones saved by an earlier run. + Future release() => _methods.invokeMethod('release'); + + /// Stop background delivery and forget every saved subscription. + Future stop() => _methods.invokeMethod('stop'); + + /// Run background delivery in a foreground service; saved across restarts. + Future setForeground(bool enabled) => + _methods.invokeMethod('setForeground', {'enabled': enabled}); + + /// Whether an earlier run saved background subscriptions that are still delivered. + Future hasSaved() async => + await _methods.invokeMethod('hasSaved') ?? false; + + /// Resume saved background delivery now instead of at the next scheduled run. + Future resume() => _methods.invokeMethod('resume'); + + /// Record whether onError is registered; returns a refusal kept while it was not, once. + Future setErrorCallback(bool registered) => _methods + .invokeMethod('setErrorCallback', {'registered': registered}); + + /// The default client id for a credential, so a foreground connection shares its session. + Future defaultClientId(String authMethod, String credential) async => + await _methods.invokeMethod('defaultClientId', { + 'authMethod': authMethod, + 'credential': credential, + }) ?? + ''; + + /// Listen to the plugin's messages and errors. + StreamSubscription> listen({ + required void Function(NativePushMessage message) onMessage, + required void Function(String message) onError, + }) { + final stream = + _stream ??= + _events + .receiveBroadcastStream() + .map((event) => event as Map) + .asBroadcastStream(); + return stream.listen((event) { + if (event['type'] == 'message') { + onMessage( + NativePushMessage( + event['id'] as String, + event['topic'] as String, + event['payload'] as Uint8List, + event['qos'] as int, + event['ackToken'] as String, + ), + ); + } else if (event['type'] == 'error') { + onError(event['message'] as String? ?? 'Background push failed'); + } + }); + } +} diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index a0f4193a..e56b7ddd 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,10 +25,12 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace(queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }); + uri = uri.replace( + queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }, + ); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..ab1c3b42 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,9 +37,11 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel((client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers)); + final websok = IOWebSocketChannel( + (client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers), + ); return websok; } @@ -73,13 +75,18 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, Map headers) async { + Uri uri, + Map headers, + ) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = - (X509Certificate cert, String host, int port) { + client.badCertificateCallback = ( + X509Certificate cert, + String host, + int port, + ) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index ee4c4c30..e1a32db8 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,74 +100,80 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen((response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add(jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - })); + _websocketSubscription = _websok?.stream.listen( + (response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add( + jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + }), + ); + } + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; - } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': - break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': break; - } + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { + break; + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); + } } - } - break; - } - }, onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }); + break; + } + }, + onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, + onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }, + ); } catch (e) { if (e is AppwriteException) { rethrow; @@ -197,27 +203,30 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server"); + "Please set endPointRealtime to connect to realtime server", + ); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = + (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", + ); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -227,10 +236,12 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add(jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + }), + ); } String _generateUniqueSubscriptionId() { @@ -292,10 +303,12 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add(jsonEncode({ - 'type': 'subscribe', - 'data': rows, - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'subscribe', + 'data': rows, + }), + ); } void _flushPendingPresence() { @@ -312,8 +325,10 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo( + List channels, [ + List queries = const [], + ]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); @@ -383,7 +398,9 @@ mixin RealtimeMixin { void handleError(RealtimeResponse response) { if (response.data['code'] == status.policyViolation) { final error = AppwriteException( - response.data["message"], response.data["code"]); + response.data["message"], + response.data["code"], + ); for (var subscription in _subscriptions.values) { subscription.controller.addError(error); } diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..631afe31 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,6 +2,7 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => throw UnsupportedError( +RealtimeBase createRealtime(Client client) => + throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index e572b519..6461e344 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/lib/topic.dart b/lib/topic.dart new file mode 100644 index 00000000..e3c43a55 --- /dev/null +++ b/lib/topic.dart @@ -0,0 +1,85 @@ +part of 'appwrite.dart'; + +/// Helper to build MQTT topics for `Push`, level by level. +/// +/// ```dart +/// Topic.path(['user', userId, 'notification']); // "user/123/notification" +/// Topic.path(['user']).any().path(['notification']); // "user/+/notification" +/// Topic.path(['org']).any().path(['logs']).all(); // "org/+/logs/#" +/// ``` +/// +/// `any()` matches exactly one level and `all()` everything below, at any depth +/// (including the parent itself). `all()` ends the topic, so it returns a +/// [ResolvedTopic]. +class Topic { + final List _levels; + + Topic._(this._levels); + + /// Start a topic with the given levels, e.g. `Topic.path(['user', userId])`. + static Topic path(List levels) => Topic._(_topicLevelsOf(levels)); + + /// Start a topic with a single-level wildcard (`+`). + static Topic any() => Topic._(const ['+']); + + /// The multi-level wildcard alone (`#`): matches every topic. + static ResolvedTopic all() => ResolvedTopic._(const ['#']); + + @override + String toString() => _levels.join('/'); +} + +/// Appends levels to a [Topic]: `Topic.path(['user']).any().path(['notification'])`. +extension TopicLevels on Topic { + /// Append the given levels. + Topic path(List levels) => + Topic._([..._levels, ..._topicLevelsOf(levels)]); + + /// Append a single-level wildcard (`+`): matches exactly one level. + Topic any() => Topic._([..._levels, '+']); + + /// Append the multi-level wildcard (`#`) and end the topic. + ResolvedTopic all() => ResolvedTopic._([..._levels, '#']); +} + +/// A topic ended by `all()`: nothing can be appended after the `#` wildcard. +class ResolvedTopic { + final List _levels; + + ResolvedTopic._(this._levels); + + @override + String toString() => _levels.join('/'); +} + +/// Validate the levels passed to `path()`: a non-empty list of non-empty +/// strings, none holding the level separator `/` or the wildcards `+` and `#` +/// (use `any()` and `all()` for those). +List _topicLevelsOf(List levels) { + if (levels.isEmpty) { + throw ArgumentError('path() needs at least one level'); + } + for (var index = 0; index < levels.length; index++) { + final level = levels[index]; + if (level.isEmpty) { + throw ArgumentError('empty level at index $index'); + } + if (level.contains('/')) { + final parts = level.split('/').map((part) => "'$part'").join(', '); + throw ArgumentError('"$level" contains "/", split it: path([$parts])'); + } + if (level == '+') { + throw ArgumentError('"+" is reserved, use any()'); + } + if (level.contains('+')) { + throw ArgumentError('"$level" contains "+", use any() for wildcards'); + } + if (level == '#') { + throw ArgumentError('"#" is reserved, use all()'); + } + if (level.contains('#')) { + throw ArgumentError('"$level" contains "#", use all() for wildcards'); + } + } + return List.unmodifiable(levels); +} diff --git a/pubspec.yaml b/pubspec.yaml index b04bee5a..21f452d7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 27.0.0 +version: 27.1.0-rc.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -23,8 +23,12 @@ dependencies: device_info_plus: '>=11.5.0 <14.0.0' flutter_web_auth_2: ^5.0.0 http: '>=0.13.6 <2.0.0' + mqtt5_client: ^4.12.0 + flutter_background_service: ^5.0.5 + flutter_local_notifications: ^18.0.1 package_info_plus: '>=8.0.2 <11.0.0' path_provider: ^2.1.4 + typed_data: ^1.3.2 web_socket_channel: ^3.0.1 web: ^1.0.0 @@ -34,3 +38,12 @@ dev_dependencies: flutter_test: sdk: flutter mockito: ^5.4.4 + +# Android: the native half of Push, which runs background delivery on the same core as the +# Appwrite Android SDK. Other platforms need no native code. +flutter: + plugin: + platforms: + android: + package: io.appwrite.flutter + pluginClass: AppwritePushPlugin diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..5ed52b81 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect(Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents'); + expect( + Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents', + ); }); test('returns database channel with action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), - 'databases.db1.collections.col1.documents.doc1.create'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').create().toString(), + 'databases.db1.collections.col1.documents.doc1.create', + ); }); test('returns database channel with upsert action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), - 'databases.db1.collections.col1.documents.doc1.upsert'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').upsert().toString(), + 'databases.db1.collections.col1.documents.doc1.upsert', + ); }); }); @@ -39,18 +39,17 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect(Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows'); + expect( + Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows', + ); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), - 'tablesdb.db1.tables.table1.rows.row1.update'); + Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + 'tablesdb.db1.tables.table1.rows.row1.update', + ); }); }); @@ -67,12 +66,16 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files', + ); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete'); + expect( + Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete', + ); }); }); @@ -116,13 +119,17 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect( + Channel.membership('membership1').toString(), + 'memberships.membership1', + ); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), - 'memberships.membership1.update'); + expect( + Channel.membership('membership1').update().toString(), + 'memberships.membership1.update', + ); }); }); @@ -140,23 +147,31 @@ void main() { }); test('returns presence channel with create action', () { - expect(Channel.presence('presence1').create().toString(), - 'presences.presence1.create'); + expect( + Channel.presence('presence1').create().toString(), + 'presences.presence1.create', + ); }); test('returns presence channel with upsert action', () { - expect(Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert'); + expect( + Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert', + ); }); test('returns presence channel with update action', () { - expect(Channel.presence('presence1').update().toString(), - 'presences.presence1.update'); + expect( + Channel.presence('presence1').update().toString(), + 'presences.presence1.update', + ); }); test('returns presence channel with delete action', () { - expect(Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete'); + expect( + Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete', + ); }); }); } diff --git a/test/services/account_test.dart b/test/services/account_test.dart index ef1bc31b..25047e20 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/apps_test.dart b/test/services/apps_test.dart new file mode 100644 index 00000000..a60f0d67 --- /dev/null +++ b/test/services/apps_test.dart @@ -0,0 +1,524 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Apps test', () { + late MockClient client; + late Apps apps; + + setUp(() { + client = MockClient(); + apps = Apps(client); + }); + + test('test method list()', () async { + final Map data = { + 'total': 5, + 'apps': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.list(); + expect(response, isA()); + }); + + test('test method create()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.create( + appId: "", + name: "", + redirectUris: [], + ); + expect(response, isA()); + }); + + test('test method listInstallationScopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallationScopes(); + expect(response, isA()); + }); + + test('test method listOAuth2Scopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listOAuth2Scopes(); + expect(response, isA()); + }); + + test('test method get()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.get( + appId: "", + ); + expect(response, isA()); + }); + + test('test method update()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.update( + appId: "", + name: "", + ); + expect(response, isA()); + }); + + test('test method delete()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.delete( + appId: "", + ); + }); + + test('test method listInstallations()', () async { + final Map data = { + 'total': 5, + 'installations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallations( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getInstallation()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", + 'scopes': [], + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getInstallation( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method deleteInstallation()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteInstallation( + appId: "", + installationId: "", + ); + }); + + test('test method createInstallationToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createInstallationToken( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method listKeys()', () async { + final Map data = { + 'total': 5, + 'keys': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listKeys( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createKey( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getKey( + appId: "", + keyId: "", + ); + expect(response, isA()); + }); + + test('test method deleteKey()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteKey( + appId: "", + keyId: "", + ); + }); + + test('test method listSecrets()', () async { + final Map data = { + 'total': 5, + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listSecrets( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createSecret( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': "", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getSecret( + appId: "", + secretId: "", + ); + expect(response, isA()); + }); + + test('test method deleteSecret()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteSecret( + appId: "", + secretId: "", + ); + }); + + test('test method updateTeam()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.updateTeam( + appId: "", + teamId: "", + ); + expect(response, isA()); + }); + + test('test method deleteTokens()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteTokens( + appId: "", + ); + }); + }); +} diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 835e2951..18c4d03d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ @@ -152,6 +154,52 @@ void main() { expect(response, isA()); }); + test('test method updatePhoto()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", + 'status': true, + 'labels': [], + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + ), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.updatePhoto( + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + + test('test method deletePhoto()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.deletePhoto(); + }); + test('test method getQR()', () async { final Uint8List data = Uint8List.fromList([]); diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index d92a7381..eb03954a 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/documents_db_test.dart b/test/services/documents_db_test.dart index 6e7d3a62..4312cced 100644 --- a/test/services/documents_db_test.dart +++ b/test/services/documents_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 75d34f13..93a7bc81 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 779767e3..3333a66e 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index c9bb5236..77ee7ddd 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 823af01e..5bf1cbd3 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/oauth2_test.dart b/test/services/oauth2_test.dart new file mode 100644 index 00000000..41976a32 --- /dev/null +++ b/test/services/oauth2_test.dart @@ -0,0 +1,300 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Oauth2 test', () { + late MockClient client; + late Oauth2 oauth2; + + setUp(() { + client = MockClient(); + oauth2 = Oauth2(client); + }); + + test('test method approve()', () async { + final Map data = { + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.approve( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method authorize()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorize(); + expect(response, isA()); + }); + + test('test method authorizePost()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorizePost(); + expect(response, isA()); + }); + + test('test method createDeviceAuthorization()', () async { + final Map data = { + 'device_code': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'user_code': "ABCD-EFGH", + 'verification_uri': "https://appwrite.io/oauth2/device", + 'verification_uri_complete': + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + 'expires_in': 900, + 'interval': 5, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createDeviceAuthorization(); + expect(response, isA()); + }); + + test('test method createGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createGrant( + userCode: "", + ); + expect(response, isA()); + }); + + test('test method getGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.getGrant( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method logout()', () async { + final data = ''; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logout(); + }); + + test('test method logoutPost()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logoutPost(); + }); + + test('test method listOrganizations()', () async { + final Map data = { + 'total': 5, + 'organizations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listOrganizations(); + expect(response, isA()); + }); + + test('test method createPAR()', () async { + final Map data = { + 'request_uri': "urn:appwrite:oauth2:request:5e5ea5c16897e", + 'expires_in': 600, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createPAR( + clientId: "", + redirectUri: "https://example.com", + responseType: "code", + ); + expect(response, isA()); + }); + + test('test method listProjects()', () async { + final Map data = { + 'total': 5, + 'projects': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listProjects(); + expect(response, isA()); + }); + + test('test method reject()', () async { + final Map data = { + 'redirectUrl': + "https://example.com/callback?error=access_denied&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.reject( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method revoke()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.revoke( + token: "", + ); + }); + + test('test method createToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createToken( + grantType: "", + ); + expect(response, isA()); + }); + }); +} diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart index a6ea2c70..7354def0 100644 --- a/test/services/organization_test.dart +++ b/test/services/organization_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 9de09725..9f160e79 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 92d858ee..d1e6f09b 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 47f0eee8..90a55af7 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index cafe8858..7c9f2faf 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/vectors_db_test.dart b/test/services/vectors_db_test.dart index 14660ed0..dc13e38d 100644 --- a/test/services/vectors_db_test.dart +++ b/test/services/vectors_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 3d301a85..bc1c08ae 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,22 +7,26 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); @@ -30,11 +34,40 @@ void main() { final inputFile = InputFile.fromPath(path: '/path/to/file'); expect(inputFile.path, '/path/to/file'); - expect(inputFile.filename, isNull); + expect(inputFile.filename, 'file'); expect(inputFile.contentType, isNull); expect(inputFile.bytes, isNull); }); + test('derives filename from path when none is given', () { + expect( + InputFile.fromPath(path: '/path/to/video.mp4').filename, + 'video.mp4', + reason: 'chunks of a file over 5MB are sent as bytes, and without a ' + 'filename the server rejects them as an empty file', + ); + expect(InputFile.fromPath(path: './relative/image.png').filename, + 'image.png'); + expect(InputFile.fromPath(path: 'video.mp4').filename, 'video.mp4'); + }); + + test('keeps an explicitly provided filename', () { + final inputFile = InputFile.fromPath( + path: '/path/to/video.mp4', + filename: 'renamed.mp4', + ); + + expect(inputFile.filename, 'renamed.mp4'); + }); + + test('derives filename from path on the deprecated constructor', () { + expect(InputFile(path: '/path/to/video.mp4').filename, 'video.mp4'); + }); + + test('leaves filename null when the path has no final segment', () { + expect(InputFile.fromPath(path: '/path/to/').filename, isNull); + }); + test('creates InputFile from bytes', () { final inputFile = InputFile.fromBytes( bytes: [1, 2, 3], diff --git a/test/src/models/account_test.dart b/test/src/models/account_test.dart new file mode 100644 index 00000000..9c4da2e1 --- /dev/null +++ b/test/src/models/account_test.dart @@ -0,0 +1,46 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Account', () { + test('model', () { + final model = Account( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "John Doe", + registration: "2020-10-15T06:38:00.000+00:00", + status: true, + labels: [], + passwordUpdate: "2020-10-15T06:38:00.000+00:00", + email: "john@appwrite.io", + phone: "+4930901820", + emailVerification: true, + phoneVerification: true, + mfa: true, + prefs: Preferences(data: {}), + targets: [], + accessedAt: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Account.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "John Doe"); + expect(result.registration, "2020-10-15T06:38:00.000+00:00"); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, "2020-10-15T06:38:00.000+00:00"); + expect(result.email, "john@appwrite.io"); + expect(result.phone, "+4930901820"); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/app_key_list_test.dart b/test/src/models/app_key_list_test.dart new file mode 100644 index 00000000..556e98a1 --- /dev/null +++ b/test/src/models/app_key_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKeyList', () { + test('model', () { + final model = AppKeyList( + total: 5, + keys: [], + ); + + final map = model.toMap(); + final result = AppKeyList.fromMap(map); + + expect(result.total, 5); + expect(result.keys, []); + }); + }); +} diff --git a/test/src/models/app_key_test.dart b/test/src/models/app_key_test.dart new file mode 100644 index 00000000..a4aedc6a --- /dev/null +++ b/test/src/models/app_key_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKey', () { + test('model', () { + final model = AppKey( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppKey.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_scope_list_test.dart b/test/src/models/app_scope_list_test.dart new file mode 100644 index 00000000..f14fe488 --- /dev/null +++ b/test/src/models/app_scope_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScopeList', () { + test('model', () { + final model = AppScopeList( + total: 5, + scopes: [], + ); + + final map = model.toMap(); + final result = AppScopeList.fromMap(map); + + expect(result.total, 5); + expect(result.scopes, []); + }); + }); +} diff --git a/test/src/models/app_scope_test.dart b/test/src/models/app_scope_test.dart new file mode 100644 index 00000000..edf43230 --- /dev/null +++ b/test/src/models/app_scope_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScope', () { + test('model', () { + final model = AppScope( + value: "organization:organization.read", + description: "Access to read the organization", + type: "organization", + category: "Organization", + deprecated: true, + ); + + final map = model.toMap(); + final result = AppScope.fromMap(map); + + expect(result.value, "organization:organization.read"); + expect(result.description, "Access to read the organization"); + expect(result.type, "organization"); + expect(result.category, "Organization"); + expect(result.deprecated, true); + }); + }); +} diff --git a/test/src/models/app_secret_list_test.dart b/test/src/models/app_secret_list_test.dart new file mode 100644 index 00000000..7e77552a --- /dev/null +++ b/test/src/models/app_secret_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretList', () { + test('model', () { + final model = AppSecretList( + total: 5, + secrets: [], + ); + + final map = model.toMap(); + final result = AppSecretList.fromMap(map); + + expect(result.total, 5); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/app_secret_plaintext_test.dart b/test/src/models/app_secret_plaintext_test.dart new file mode 100644 index 00000000..801dfc74 --- /dev/null +++ b/test/src/models/app_secret_plaintext_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretPlaintext', () { + test('model', () { + final model = AppSecretPlaintext( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecretPlaintext.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_secret_test.dart b/test/src/models/app_secret_test.dart new file mode 100644 index 00000000..856e8c33 --- /dev/null +++ b/test/src/models/app_secret_test.dart @@ -0,0 +1,31 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecret', () { + test('model', () { + final model = AppSecret( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: "", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecret.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.secret, ""); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_test.dart b/test/src/models/app_test.dart new file mode 100644 index 00000000..a1cf013a --- /dev/null +++ b/test/src/models/app_test.dart @@ -0,0 +1,67 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('App', () { + test('model', () { + final model = App( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "My Application", + description: "Connect your workspace to My Application.", + clientUri: "https://example.com", + logoUri: "https://example.com/logo.png", + privacyPolicyUrl: "https://example.com/privacy", + termsUrl: "https://example.com/terms", + contacts: [], + tagline: "Automate your workspace.", + tags: [], + labels: [], + images: [], + supportUrl: "https://example.com/support", + dataDeletionUrl: "https://example.com/data-deletion", + redirectUris: [], + postLogoutRedirectUris: [], + enabled: true, + type: "confidential", + deviceFlow: true, + teamId: "5e5ea5c16897e", + userId: "5e5ea5c16897e", + installationScopes: [], + installationRedirectUrl: "https://example.com/setup", + secrets: [], + ); + + final map = model.toMap(); + final result = App.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "My Application"); + expect(result.description, "Connect your workspace to My Application."); + expect(result.clientUri, "https://example.com"); + expect(result.logoUri, "https://example.com/logo.png"); + expect(result.privacyPolicyUrl, "https://example.com/privacy"); + expect(result.termsUrl, "https://example.com/terms"); + expect(result.contacts, []); + expect(result.tagline, "Automate your workspace."); + expect(result.tags, []); + expect(result.labels, []); + expect(result.images, []); + expect(result.supportUrl, "https://example.com/support"); + expect(result.dataDeletionUrl, "https://example.com/data-deletion"); + expect(result.redirectUris, []); + expect(result.postLogoutRedirectUris, []); + expect(result.enabled, true); + expect(result.type, "confidential"); + expect(result.deviceFlow, true); + expect(result.teamId, "5e5ea5c16897e"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.installationScopes, []); + expect(result.installationRedirectUrl, "https://example.com/setup"); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/apps_list_test.dart b/test/src/models/apps_list_test.dart new file mode 100644 index 00000000..19150689 --- /dev/null +++ b/test/src/models/apps_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppsList', () { + test('model', () { + final model = AppsList( + total: 5, + apps: [], + ); + + final map = model.toMap(); + final result = AppsList.fromMap(map); + + expect(result.total, 5); + expect(result.apps, []); + }); + }); +} diff --git a/test/src/models/oauth2_approve_test.dart b/test/src/models/oauth2_approve_test.dart new file mode 100644 index 00000000..a045bfcf --- /dev/null +++ b/test/src/models/oauth2_approve_test.dart @@ -0,0 +1,20 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Approve', () { + test('model', () { + final model = Oauth2Approve( + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Approve.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_authorize_test.dart b/test/src/models/oauth2_authorize_test.dart new file mode 100644 index 00000000..f1546316 --- /dev/null +++ b/test/src/models/oauth2_authorize_test.dart @@ -0,0 +1,22 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Authorize', () { + test('model', () { + final model = Oauth2Authorize( + grantId: "5e5ea5c16897e", + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Authorize.fromMap(map); + + expect(result.grantId, "5e5ea5c16897e"); + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_device_authorization_test.dart b/test/src/models/oauth2_device_authorization_test.dart new file mode 100644 index 00000000..d68181a5 --- /dev/null +++ b/test/src/models/oauth2_device_authorization_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2DeviceAuthorization', () { + test('model', () { + final model = Oauth2DeviceAuthorization( + device_code: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + user_code: "ABCD-EFGH", + verification_uri: "https://appwrite.io/oauth2/device", + verification_uri_complete: + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + expires_in: 900, + interval: 5, + ); + + final map = model.toMap(); + final result = Oauth2DeviceAuthorization.fromMap(map); + + expect( + result.device_code, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.user_code, "ABCD-EFGH"); + expect(result.verification_uri, "https://appwrite.io/oauth2/device"); + expect( + result.verification_uri_complete, + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + ); + expect(result.expires_in, 900); + expect(result.interval, 5); + }); + }); +} diff --git a/test/src/models/oauth2_grant_test.dart b/test/src/models/oauth2_grant_test.dart new file mode 100644 index 00000000..65a866a9 --- /dev/null +++ b/test/src/models/oauth2_grant_test.dart @@ -0,0 +1,43 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Grant', () { + test('model', () { + final model = Oauth2Grant( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c16897e", + appId: "5e5ea5c16897e", + scopes: [], + resources: [], + authorizationDetails: + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + prompt: "login", + redirectUri: "https://example.com/callback", + authTime: 1592981250, + expire: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Oauth2Grant.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.scopes, []); + expect(result.resources, []); + expect( + result.authorizationDetails, + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + ); + expect(result.prompt, "login"); + expect(result.redirectUri, "https://example.com/callback"); + expect(result.authTime, 1592981250); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/oauth2_organization_list_test.dart b/test/src/models/oauth2_organization_list_test.dart new file mode 100644 index 00000000..e55d8efd --- /dev/null +++ b/test/src/models/oauth2_organization_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2OrganizationList', () { + test('model', () { + final model = Oauth2OrganizationList( + total: 5, + organizations: [], + ); + + final map = model.toMap(); + final result = Oauth2OrganizationList.fromMap(map); + + expect(result.total, 5); + expect(result.organizations, []); + }); + }); +} diff --git a/test/src/models/oauth2_organization_test.dart b/test/src/models/oauth2_organization_test.dart new file mode 100644 index 00000000..7d56d71c --- /dev/null +++ b/test/src/models/oauth2_organization_test.dart @@ -0,0 +1,17 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Organization', () { + test('model', () { + final model = Oauth2Organization( + $id: "5e5ea5c16897e", + ); + + final map = model.toMap(); + final result = Oauth2Organization.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + }); + }); +} diff --git a/test/src/models/oauth2_par_test.dart b/test/src/models/oauth2_par_test.dart new file mode 100644 index 00000000..8ccc1d58 --- /dev/null +++ b/test/src/models/oauth2_par_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2PAR', () { + test('model', () { + final model = Oauth2PAR( + request_uri: "urn:appwrite:oauth2:request:5e5ea5c16897e", + expires_in: 600, + ); + + final map = model.toMap(); + final result = Oauth2PAR.fromMap(map); + + expect(result.request_uri, "urn:appwrite:oauth2:request:5e5ea5c16897e"); + expect(result.expires_in, 600); + }); + }); +} diff --git a/test/src/models/oauth2_project_list_test.dart b/test/src/models/oauth2_project_list_test.dart new file mode 100644 index 00000000..1f6cf6a6 --- /dev/null +++ b/test/src/models/oauth2_project_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ProjectList', () { + test('model', () { + final model = Oauth2ProjectList( + total: 5, + projects: [], + ); + + final map = model.toMap(); + final result = Oauth2ProjectList.fromMap(map); + + expect(result.total, 5); + expect(result.projects, []); + }); + }); +} diff --git a/test/src/models/oauth2_project_test.dart b/test/src/models/oauth2_project_test.dart new file mode 100644 index 00000000..9771b53f --- /dev/null +++ b/test/src/models/oauth2_project_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Project', () { + test('model', () { + final model = Oauth2Project( + $id: "5e5ea5c16897e", + region: "fra", + endpoint: "https://fra.cloud.appwrite.io/v1", + ); + + final map = model.toMap(); + final result = Oauth2Project.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.region, "fra"); + expect(result.endpoint, "https://fra.cloud.appwrite.io/v1"); + }); + }); +} diff --git a/test/src/models/oauth2_reject_test.dart b/test/src/models/oauth2_reject_test.dart new file mode 100644 index 00000000..79aacf6a --- /dev/null +++ b/test/src/models/oauth2_reject_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Reject', () { + test('model', () { + final model = Oauth2Reject( + redirectUrl: + "https://example.com/callback?error=access_denied&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Reject.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?error=access_denied&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_token_test.dart b/test/src/models/oauth2_token_test.dart new file mode 100644 index 00000000..5dafe749 --- /dev/null +++ b/test/src/models/oauth2_token_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Token', () { + test('model', () { + final model = Oauth2Token( + access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + scope: "openid email profile", + ); + + final map = model.toMap(); + final result = Oauth2Token.fromMap(map); + + expect(result.access_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."); + expect(result.token_type, "Bearer"); + expect(result.expires_in, 3600); + expect(result.refresh_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."); + expect(result.scope, "openid email profile"); + }); + }); +} diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 4435280a..029c35bf 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,7 +48,9 @@ void main() { final responseString = response1.toString(); expect( - responseString, equals('RealtimeResponse(type: $type, data: $data)')); + responseString, + equals('RealtimeResponse(type: $type, data: $data)'), + ); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index 1515f1a3..d19e6eac 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,15 +8,18 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction( - {List? channels, List? queries}) async {} + Future mockUpdateFunction({ + List? channels, + List? queries, + }) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const []); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const [], + ); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index d21607ec..3dce66c9 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded + "chunksUploaded": chunksUploaded, }; final uploadProgress = UploadProgress( $id: id, diff --git a/test/topic_test.dart b/test/topic_test.dart new file mode 100644 index 00000000..ba797dfa --- /dev/null +++ b/test/topic_test.dart @@ -0,0 +1,70 @@ +import 'package:appwrite/appwrite.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('path()', () { + test('joins levels', () { + expect(Topic.path(['user']).toString(), 'user'); + expect( + Topic.path(['user', 'notification']).toString(), + 'user/notification', + ); + }); + + test('appends levels', () { + expect( + Topic.path(['user']).path(['notification']).toString(), + 'user/notification', + ); + }); + }); + + group('any()', () { + test('appends a single-level wildcard', () { + expect( + Topic.path(['user']).any().path(['notification']).toString(), + 'user/+/notification', + ); + expect( + Topic.path(['chat']).any().any().path(['message']).toString(), + 'chat/+/+/message', + ); + }); + + test('starts a topic', () { + expect(Topic.any().path(['notification']).toString(), '+/notification'); + }); + }); + + group('all()', () { + test('ends a topic', () { + expect( + Topic.path(['org']).any().path(['logs']).all().toString(), + 'org/+/logs/#', + ); + }); + + test('matches every topic', () { + expect(Topic.all().toString(), '#'); + }); + }); + + group('errors', () { + final invalid = >{ + 'an empty path': [], + 'an empty level': ['user', ''], + 'a slash': ['user/123'], + 'a lone +': ['user', '+'], + 'an embedded +': ['user', 'a+b'], + 'a lone #': ['user', '#'], + 'an embedded #': ['user', 'a#b'], + }; + + invalid.forEach((name, levels) { + test('rejects $name', () { + expect(() => Topic.path(levels), throwsArgumentError); + expect(() => Topic.any().path(levels), throwsArgumentError); + }); + }); + }); +}