diff --git a/.github/workflows/autoclose.yml b/.github/workflows/autoclose.yml new file mode 100644 index 0000000..3e2b3cb --- /dev/null +++ b/.github/workflows/autoclose.yml @@ -0,0 +1,11 @@ +name: Auto-close External Pull Requests + +on: + pull_request_target: + types: [opened, reopened] + +jobs: + auto_close: + uses: appwrite/.github/.github/workflows/autoclose.yml@main + secrets: + GH_AUTO_CLOSE_PR_TOKEN: ${{ secrets.GH_AUTO_CLOSE_PR_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 20b880d..7145ba6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -12,11 +12,10 @@ jobs: steps: - name: Check out code uses: actions/checkout@v2 - - name: Set up JDK 1.8 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 1.8 - # Base64 decodes and pipes the GPG key content into the secret file + java-version: 17 - name: Prepare environment env: GPG_KEY_CONTENTS: ${{ secrets.GPG_KEY_CONTENTS }} @@ -28,7 +27,7 @@ jobs: # Builds the release artifacts of the library - name: Build Release Artifacts - run: ./gradlew --info library:assembleRelease + run: ./gradlew library:assembleRelease # Generates other artifacts (javadocJar is optional) - name: Generate Source jar @@ -37,12 +36,12 @@ jobs: # Runs upload, and then closes & releases the repository - name: Publish Release Version to MavenCentral run: | - if ${{ endswith(github.event.release.tag_name, '-SNAPSHOT') }}; then + if ${{ contains(github.event.release.tag_name, '-rc') }}; then echo "Publising Snapshot Version ${{ github.event.release.tag_name}} to Snapshot repository" - ./gradlew publishReleasePublicationToSonatypeRepository + ./gradlew publishToSonatype else echo "Publising Release Version ${{ github.event.release.tag_name}} to Staging repository" - ./gradlew publishReleasePublicationToSonatypeRepository --max-workers 1 closeAndReleaseSonatypeStagingRepository + ./gradlew publishToSonatype --max-workers 1 closeAndReleaseSonatypeStagingRepository fi env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} @@ -51,4 +50,4 @@ jobs: SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} SIGNING_SECRET_KEY_RING_FILE: ${{ secrets.SIGNING_SECRET_KEY_RING_FILE }} SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} - SDK_VERSION: ${{ github.event.release.tag_name }} \ No newline at end of file + SDK_VERSION: ${{ github.event.release.tag_name }} diff --git a/CHANGELOG.md b/CHANGELOG.md index fa4d35e..38d0c4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,23 @@ -# Change Log \ No newline at end of file +# Change Log + +## 8.2.0 + +* Add `incrementDocumentAttribute` and `decrementDocumentAttribute` support to `Databases` service +* Add `gif` support to `ImageFormat` enum +* Add `sequence` support to `Document` model + +## 8.1.0 + +* Add `devKeys` support to `Client` service +* Add `upsertDocument` support to `Databases` service + +## 8.0.0 + +* Add `token` param to `getFilePreview` and `getFileView` for File tokens usage +* Update default `quality` for `getFilePreview` from 0 to -1 +* Remove `Gif` from ImageFormat enum +* Remove `search` param from `listExecutions` method + +## 7.0.1 + +* Fix requests failing by removing `Content-Type` header from `GET` and `HEAD` requests diff --git a/LICENSE.md b/LICENSE.md index d73a6e9..c1602fc 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2021 Appwrite (https://appwrite.io) and individual contributors. +Copyright (c) 2025 Appwrite (https://appwrite.io) and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -7,6 +7,6 @@ Redistribution and use in source and binary forms, with or without modification, 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name Appwrite nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md index 862d6b8..a0c4c6d 100644 --- a/README.md +++ b/README.md @@ -2,16 +2,16 @@ ![Maven Central](https://img.shields.io/maven-central/v/io.appwrite/sdk-for-android.svg?color=green&style=flat-square) ![License](https://img.shields.io/github/license/appwrite/sdk-for-android.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-0.11.0-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-1.8.0-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_io?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite_io) +[![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 0.11.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-android/releases).** +**This SDK is compatible with Appwrite server version 1.8.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-android/releases).** Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Android 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) -![Appwrite](https://appwrite.io/images/github.png) +![Appwrite](https://github.com/appwrite/appwrite/raw/main/public/images/github.png) ## Installation @@ -38,7 +38,7 @@ repositories { Next, add the dependency to your project's `build.gradle(.kts)` file: ```groovy -implementation("io.appwrite:sdk-for-android:0.2.1") +implementation("io.appwrite:sdk-for-android:9.0.0") ``` ### Maven @@ -49,7 +49,7 @@ Add this to your project's `pom.xml` file: io.appwrite sdk-for-android - 0.2.1 + 9.0.0 ``` @@ -75,7 +75,7 @@ In order to capture the Appwrite OAuth callback url, the following activity need - + @@ -91,8 +91,8 @@ import io.appwrite.Client import io.appwrite.services.Account val client = Client(context) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID + .setEndpoint("https:///v1") // Your API Endpoint + .setProject("") // Your project ID .setSelfSigned(true) // Remove in production ``` @@ -108,8 +108,10 @@ When trying to connect to Appwrite from an emulator or a mobile device, localhos // Register User val account = Account(client) val response = account.create( - "email@example.com", - "password" + ID.unique(), + "email@example.com", + "password", + "Walter O'Brien" ) ``` @@ -118,28 +120,158 @@ val response = account.create( ```kotlin import io.appwrite.Client import io.appwrite.services.Account +import io.appwrite.ID val client = Client(context) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID + .setEndpoint("https:///v1") // Your API Endpoint + .setProject("") // Your project ID .setSelfSigned(true) // Remove in production val account = Account(client) -val response = account.create( - "email@example.com", - "password" +val user = account.create( + ID.unique(), + "email@example.com", + "password", + "Walter O'Brien" +) +``` + +### Type Safety with Models + +The Appwrite Android SDK provides type safety when working with database documents through generic methods. Methods like `listDocuments`, `getDocument`, and others accept a `nestedType` parameter that allows you to specify your custom model type for full type safety. + +**Kotlin:** +```kotlin +data class Book( + val name: String, + val author: String, + val releaseYear: String? = null, + val category: String? = null, + val genre: List? = null, + val isCheckedOut: Boolean +) + +val databases = Databases(client) + +try { + val documents = databases.listDocuments( + databaseId = "your-database-id", + collectionId = "your-collection-id", + nestedType = Book::class.java // Pass in your custom model type + ) + + for (book in documents.documents) { + Log.d("Appwrite", "Book: ${book.name} by ${book.author}") // Now you have full type safety + } +} catch (e: AppwriteException) { + Log.e("Appwrite", e.message ?: "Unknown error") +} +``` + +**Java:** +```java +public class Book { + private String name; + private String author; + private String releaseYear; + private String category; + private List genre; + private boolean isCheckedOut; + + // Constructor + public Book(String name, String author, boolean isCheckedOut) { + this.name = name; + this.author = author; + this.isCheckedOut = isCheckedOut; + } + + // Getters and setters + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getAuthor() { return author; } + public void setAuthor(String author) { this.author = author; } + + public String getReleaseYear() { return releaseYear; } + public void setReleaseYear(String releaseYear) { this.releaseYear = releaseYear; } + + public String getCategory() { return category; } + public void setCategory(String category) { this.category = category; } + + public List getGenre() { return genre; } + public void setGenre(List genre) { this.genre = genre; } + + public boolean isCheckedOut() { return isCheckedOut; } + public void setCheckedOut(boolean checkedOut) { isCheckedOut = checkedOut; } +} + +Databases databases = new Databases(client); + +try { + DocumentList documents = databases.listDocuments( + "your-database-id", + "your-collection-id", + Book.class // Pass in your custom model type + ); + + for (Book book : documents.getDocuments()) { + Log.d("Appwrite", "Book: " + book.getName() + " by " + book.getAuthor()); // Now you have full type safety + } +} catch (AppwriteException e) { + Log.e("Appwrite", e.getMessage() != null ? e.getMessage() : "Unknown error"); +} +``` + +**Tip**: You can use the `appwrite types` command to automatically generate model definitions based on your Appwrite database schema. Learn more about [type generation](https://appwrite.io/docs/products/databases/type-generation). + +### Working with Model Methods + +All Appwrite models come with built-in methods for data conversion and manipulation: + +**`toMap()`** - Converts a model instance to a Map format, useful for debugging or manual data manipulation: +```kotlin +val account = Account(client) +val user = account.get() +val userMap = user.toMap() +Log.d("Appwrite", userMap.toString()) // Prints all user properties as a Map +``` + +**`from(map:, nestedType:)`** - Creates a model instance from a Map, useful when working with raw data: +```kotlin +val userData: Map = mapOf( + "\$id" to "123", + "name" to "John", + "email" to "john@example.com" ) +val user = User.from(userData, User::class.java) +``` + +**JSON Serialization** - Models can be easily converted to/from JSON using Gson (which the SDK uses internally): +```kotlin +import com.google.gson.Gson + +val account = Account(client) +val user = account.get() + +// Convert to JSON +val gson = Gson() +val jsonString = gson.toJson(user) +Log.d("Appwrite", "User JSON: $jsonString") + +// Convert from JSON +val userFromJson = gson.fromJson(jsonString, User::class.java) ``` ### Error Handling + The Appwrite Android SDK raises an `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example. ```kotlin try { - var response = account.create("email@example.com", "password") - Log.d("Appwrite response", response.body?.string()) + var user = account.create(ID.unique(),"email@example.com","password","Walter O'Brien") + Log.d("Appwrite user", user.toMap()) } catch(e : AppwriteException) { - Log.e("AppwriteException",e.message.toString()) + e.printStackTrace() } ``` @@ -150,6 +282,7 @@ You can use the following resources to learn more and get help - 💬 [Discord Community](https://appwrite.io/discord) - 🚂 [Appwrite Android Playground](https://github.com/appwrite/playground-for-android) + ## Contribution This library is auto-generated by Appwrite custom [SDK Generator](https://github.com/appwrite/sdk-generator). To learn more about how you can help us improve this SDK, please check the [contribution guide](https://github.com/appwrite/sdk-generator/blob/master/CONTRIBUTING.md) before sending a pull-request. diff --git a/build.gradle b/build.gradle index 4df4d35..0b0c86c 100644 --- a/build.gradle +++ b/build.gradle @@ -2,20 +2,19 @@ apply plugin: 'io.github.gradle-nexus.publish-plugin' // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { - ext.kotlin_version = "1.4.31" - version '0.2.1' + ext.kotlin_version = "1.9.10" + + version System.getenv("SDK_VERSION") + repositories { maven { url "https://plugins.gradle.org/m2/" } google() mavenCentral() } dependencies { - classpath "com.android.tools.build:gradle:4.2.0" + classpath "com.android.tools.build:gradle:8.2.2" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath 'io.github.gradle-nexus:publish-plugin:1.1.0' - - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files + classpath "io.github.gradle-nexus:publish-plugin:1.3.0" } } diff --git a/docs/examples/java/account/create-anonymous-session.md b/docs/examples/java/account/create-anonymous-session.md index b1a2a25..9d80588 100644 --- a/docs/examples/java/account/create-anonymous-session.md +++ b/docs/examples/java/account/create-anonymous-session.md @@ -1,46 +1,18 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.createAnonymousSession(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); +account.createAnonymousSession(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; } -} \ No newline at end of file + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/create-email-password-session.md b/docs/examples/java/account/create-email-password-session.md new file mode 100644 index 0000000..428b6fd --- /dev/null +++ b/docs/examples/java/account/create-email-password-session.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createEmailPasswordSession( + "email@example.com", // email + "password", // password + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-email-token.md b/docs/examples/java/account/create-email-token.md new file mode 100644 index 0000000..869f4a8 --- /dev/null +++ b/docs/examples/java/account/create-email-token.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createEmailToken( + "", // userId + "email@example.com", // email + false, // phrase (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-j-w-t.md b/docs/examples/java/account/create-j-w-t.md deleted file mode 100644 index 3a97c33..0000000 --- a/docs/examples/java/account/create-j-w-t.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.createJWT(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create-jwt.md b/docs/examples/java/account/create-jwt.md new file mode 100644 index 0000000..9e3bd28 --- /dev/null +++ b/docs/examples/java/account/create-jwt.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createJWT(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/create-magic-u-r-l-session.md b/docs/examples/java/account/create-magic-u-r-l-session.md deleted file mode 100644 index 36fc58a..0000000 --- a/docs/examples/java/account/create-magic-u-r-l-session.md +++ /dev/null @@ -1,48 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.createMagicURLSession( - "email@example.com", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create-magic-url-token.md b/docs/examples/java/account/create-magic-url-token.md new file mode 100644 index 0000000..6253e00 --- /dev/null +++ b/docs/examples/java/account/create-magic-url-token.md @@ -0,0 +1,25 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createMagicURLToken( + "", // userId + "email@example.com", // email + "https://example.com", // url (optional) + false, // phrase (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-mfa-authenticator.md b/docs/examples/java/account/create-mfa-authenticator.md new file mode 100644 index 0000000..d236f46 --- /dev/null +++ b/docs/examples/java/account/create-mfa-authenticator.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.AuthenticatorType; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createMFAAuthenticator( + AuthenticatorType.TOTP, // type + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-mfa-challenge.md b/docs/examples/java/account/create-mfa-challenge.md new file mode 100644 index 0000000..222c0bd --- /dev/null +++ b/docs/examples/java/account/create-mfa-challenge.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.AuthenticationFactor; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createMFAChallenge( + AuthenticationFactor.EMAIL, // factor + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-mfa-recovery-codes.md b/docs/examples/java/account/create-mfa-recovery-codes.md new file mode 100644 index 0000000..792e086 --- /dev/null +++ b/docs/examples/java/account/create-mfa-recovery-codes.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createMFARecoveryCodes(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/create-o-auth-2-session.md b/docs/examples/java/account/create-o-auth-2-session.md new file mode 100644 index 0000000..4420859 --- /dev/null +++ b/docs/examples/java/account/create-o-auth-2-session.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.OAuthProvider; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createOAuth2Session( + OAuthProvider.AMAZON, // provider + "https://example.com", // success (optional) + "https://example.com", // failure (optional) + listOf(), // scopes (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-o-auth-2-token.md b/docs/examples/java/account/create-o-auth-2-token.md new file mode 100644 index 0000000..e5590c8 --- /dev/null +++ b/docs/examples/java/account/create-o-auth-2-token.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.OAuthProvider; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createOAuth2Token( + OAuthProvider.AMAZON, // provider + "https://example.com", // success (optional) + "https://example.com", // failure (optional) + listOf(), // scopes (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-o-auth2session.md b/docs/examples/java/account/create-o-auth2session.md deleted file mode 100644 index e4cfb8d..0000000 --- a/docs/examples/java/account/create-o-auth2session.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.createOAuth2Session( - this, - "amazon", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create-phone-token.md b/docs/examples/java/account/create-phone-token.md new file mode 100644 index 0000000..19d90b3 --- /dev/null +++ b/docs/examples/java/account/create-phone-token.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createPhoneToken( + "", // userId + "+12065550100", // phone + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-phone-verification.md b/docs/examples/java/account/create-phone-verification.md new file mode 100644 index 0000000..8c16b6c --- /dev/null +++ b/docs/examples/java/account/create-phone-verification.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createPhoneVerification(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/create-push-target.md b/docs/examples/java/account/create-push-target.md new file mode 100644 index 0000000..d434a5c --- /dev/null +++ b/docs/examples/java/account/create-push-target.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.createPushTarget( + "", // targetId + "", // identifier + "", // providerId (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/create-recovery.md b/docs/examples/java/account/create-recovery.md index 459213b..5592c6e 100644 --- a/docs/examples/java/account/create-recovery.md +++ b/docs/examples/java/account/create-recovery.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.createRecovery( + "email@example.com", // email + "https://example.com", // url + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.createRecovery( - "email@example.com", - "https://example.com" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create-session.md b/docs/examples/java/account/create-session.md index 34dfca5..0c59a80 100644 --- a/docs/examples/java/account/create-session.md +++ b/docs/examples/java/account/create-session.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.createSession( + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.createSession( - "email@example.com", - "password" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create-verification.md b/docs/examples/java/account/create-verification.md index b8b1c20..e91acc8 100644 --- a/docs/examples/java/account/create-verification.md +++ b/docs/examples/java/account/create-verification.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.createVerification( + "https://example.com", // url + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.createVerification( - "https://example.com" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/create.md b/docs/examples/java/account/create.md index 3ff5ab9..ad04805 100644 --- a/docs/examples/java/account/create.md +++ b/docs/examples/java/account/create.md @@ -1,49 +1,25 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.create( + "", // userId + "email@example.com", // email + "", // password + "", // name (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.create( - "email@example.com", - "password", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/delete-identity.md b/docs/examples/java/account/delete-identity.md new file mode 100644 index 0000000..d556722 --- /dev/null +++ b/docs/examples/java/account/delete-identity.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.deleteIdentity( + "", // identityId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/delete-mfa-authenticator.md b/docs/examples/java/account/delete-mfa-authenticator.md new file mode 100644 index 0000000..b5ff26c --- /dev/null +++ b/docs/examples/java/account/delete-mfa-authenticator.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.AuthenticatorType; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.deleteMFAAuthenticator( + AuthenticatorType.TOTP, // type + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/delete-push-target.md b/docs/examples/java/account/delete-push-target.md new file mode 100644 index 0000000..00ab902 --- /dev/null +++ b/docs/examples/java/account/delete-push-target.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.deletePushTarget( + "", // targetId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/delete-session.md b/docs/examples/java/account/delete-session.md index b3549c7..99d2f8e 100644 --- a/docs/examples/java/account/delete-session.md +++ b/docs/examples/java/account/delete-session.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.deleteSession( + "", // sessionId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.deleteSession( - "[SESSION_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/delete-sessions.md b/docs/examples/java/account/delete-sessions.md index 153c323..e93f3e3 100644 --- a/docs/examples/java/account/delete-sessions.md +++ b/docs/examples/java/account/delete-sessions.md @@ -1,46 +1,18 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.deleteSessions(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); +account.deleteSessions(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; } -} \ No newline at end of file + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/delete.md b/docs/examples/java/account/delete.md deleted file mode 100644 index aec96f1..0000000 --- a/docs/examples/java/account/delete.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.delete(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/get-logs.md b/docs/examples/java/account/get-logs.md deleted file mode 100644 index f2dea96..0000000 --- a/docs/examples/java/account/get-logs.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.getLogs(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/get-mfa-recovery-codes.md b/docs/examples/java/account/get-mfa-recovery-codes.md new file mode 100644 index 0000000..22bc1c1 --- /dev/null +++ b/docs/examples/java/account/get-mfa-recovery-codes.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.getMFARecoveryCodes(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/get-prefs.md b/docs/examples/java/account/get-prefs.md index 25ab6c3..5bb11a4 100644 --- a/docs/examples/java/account/get-prefs.md +++ b/docs/examples/java/account/get-prefs.md @@ -1,46 +1,18 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.getPrefs(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); +account.getPrefs(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; } -} \ No newline at end of file + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/get-session.md b/docs/examples/java/account/get-session.md index 8d4c95a..288cd3b 100644 --- a/docs/examples/java/account/get-session.md +++ b/docs/examples/java/account/get-session.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.getSession( + "", // sessionId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.getSession( - "[SESSION_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/get-sessions.md b/docs/examples/java/account/get-sessions.md deleted file mode 100644 index 7afe852..0000000 --- a/docs/examples/java/account/get-sessions.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.getSessions(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/get.md b/docs/examples/java/account/get.md index 146a5e5..6b5eb3b 100644 --- a/docs/examples/java/account/get.md +++ b/docs/examples/java/account/get.md @@ -1,46 +1,18 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.get(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); +account.get(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; } -} \ No newline at end of file + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/list-identities.md b/docs/examples/java/account/list-identities.md new file mode 100644 index 0000000..d4a6f9f --- /dev/null +++ b/docs/examples/java/account/list-identities.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.listIdentities( + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/list-logs.md b/docs/examples/java/account/list-logs.md new file mode 100644 index 0000000..951a479 --- /dev/null +++ b/docs/examples/java/account/list-logs.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.listLogs( + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/list-mfa-factors.md b/docs/examples/java/account/list-mfa-factors.md new file mode 100644 index 0000000..06f20e1 --- /dev/null +++ b/docs/examples/java/account/list-mfa-factors.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.listMFAFactors(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/list-sessions.md b/docs/examples/java/account/list-sessions.md new file mode 100644 index 0000000..8946d96 --- /dev/null +++ b/docs/examples/java/account/list-sessions.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.listSessions(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/update-email.md b/docs/examples/java/account/update-email.md index 56a1bc0..ac80e45 100644 --- a/docs/examples/java/account/update-email.md +++ b/docs/examples/java/account/update-email.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updateEmail( + "email@example.com", // email + "password", // password + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updateEmail( - "email@example.com", - "password" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-magic-u-r-l-session.md b/docs/examples/java/account/update-magic-u-r-l-session.md deleted file mode 100644 index d0734e1..0000000 --- a/docs/examples/java/account/update-magic-u-r-l-session.md +++ /dev/null @@ -1,49 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Account account = new Account(client); - - account.updateMagicURLSession( - "[USER_ID]", - "[SECRET]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-magic-url-session.md b/docs/examples/java/account/update-magic-url-session.md new file mode 100644 index 0000000..5893aa6 --- /dev/null +++ b/docs/examples/java/account/update-magic-url-session.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateMagicURLSession( + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-mfa-authenticator.md b/docs/examples/java/account/update-mfa-authenticator.md new file mode 100644 index 0000000..00ddd46 --- /dev/null +++ b/docs/examples/java/account/update-mfa-authenticator.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; +import io.appwrite.enums.AuthenticatorType; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateMFAAuthenticator( + AuthenticatorType.TOTP, // type + "", // otp + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-mfa-challenge.md b/docs/examples/java/account/update-mfa-challenge.md new file mode 100644 index 0000000..10b5db4 --- /dev/null +++ b/docs/examples/java/account/update-mfa-challenge.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateMFAChallenge( + "", // challengeId + "", // otp + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-mfa-recovery-codes.md b/docs/examples/java/account/update-mfa-recovery-codes.md new file mode 100644 index 0000000..c0d6c69 --- /dev/null +++ b/docs/examples/java/account/update-mfa-recovery-codes.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateMFARecoveryCodes(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/update-mfa.md b/docs/examples/java/account/update-mfa.md new file mode 100644 index 0000000..b765cda --- /dev/null +++ b/docs/examples/java/account/update-mfa.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateMFA( + false, // mfa + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-name.md b/docs/examples/java/account/update-name.md index 9842a22..47582c2 100644 --- a/docs/examples/java/account/update-name.md +++ b/docs/examples/java/account/update-name.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updateName( + "", // name + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updateName( - "[NAME]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-password.md b/docs/examples/java/account/update-password.md index 468bdc2..09f572e 100644 --- a/docs/examples/java/account/update-password.md +++ b/docs/examples/java/account/update-password.md @@ -1,48 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updatePassword( + "", // password + "password", // oldPassword (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updatePassword( - "password", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-phone-session.md b/docs/examples/java/account/update-phone-session.md new file mode 100644 index 0000000..2e1b880 --- /dev/null +++ b/docs/examples/java/account/update-phone-session.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updatePhoneSession( + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-phone-verification.md b/docs/examples/java/account/update-phone-verification.md new file mode 100644 index 0000000..f93ae69 --- /dev/null +++ b/docs/examples/java/account/update-phone-verification.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updatePhoneVerification( + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-phone.md b/docs/examples/java/account/update-phone.md new file mode 100644 index 0000000..fae9bfa --- /dev/null +++ b/docs/examples/java/account/update-phone.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updatePhone( + "+12065550100", // phone + "password", // password + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-prefs.md b/docs/examples/java/account/update-prefs.md index 9f94b8f..f1a16c7 100644 --- a/docs/examples/java/account/update-prefs.md +++ b/docs/examples/java/account/update-prefs.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updatePrefs( + mapOf( "a" to "b" ), // prefs + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updatePrefs( - mapOf( "a" to "b" ) - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-push-target.md b/docs/examples/java/account/update-push-target.md new file mode 100644 index 0000000..197a909 --- /dev/null +++ b/docs/examples/java/account/update-push-target.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updatePushTarget( + "", // targetId + "", // identifier + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-recovery.md b/docs/examples/java/account/update-recovery.md index bfcc89e..953bde4 100644 --- a/docs/examples/java/account/update-recovery.md +++ b/docs/examples/java/account/update-recovery.md @@ -1,51 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updateRecovery( + "", // userId + "", // secret + "", // password + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updateRecovery( - "[USER_ID]", - "[SECRET]", - "password", - "password" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/account/update-session.md b/docs/examples/java/account/update-session.md new file mode 100644 index 0000000..ed82840 --- /dev/null +++ b/docs/examples/java/account/update-session.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateSession( + "", // sessionId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/account/update-status.md b/docs/examples/java/account/update-status.md new file mode 100644 index 0000000..9a283c0 --- /dev/null +++ b/docs/examples/java/account/update-status.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +account.updateStatus(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/account/update-verification.md b/docs/examples/java/account/update-verification.md index 8cf8d67..caa3869 100644 --- a/docs/examples/java/account/update-verification.md +++ b/docs/examples/java/account/update-verification.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Account; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Account account = new Account(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +account.updateVerification( + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Account account = new Account(client); + Log.d("Appwrite", result.toString()); + }) +); - account.updateVerification( - "[USER_ID]", - "[SECRET]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-browser.md b/docs/examples/java/avatars/get-browser.md index fa88749..1b6632f 100644 --- a/docs/examples/java/avatars/get-browser.md +++ b/docs/examples/java/avatars/get-browser.md @@ -1,48 +1,26 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; +import io.appwrite.enums.Browser; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getBrowser( + Browser.AVANT_BROWSER, // code + 0, // width (optional) + 0, // height (optional) + -1, // quality (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getBrowser( - "aa", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-credit-card.md b/docs/examples/java/avatars/get-credit-card.md index 2ddda86..e2ac2c2 100644 --- a/docs/examples/java/avatars/get-credit-card.md +++ b/docs/examples/java/avatars/get-credit-card.md @@ -1,48 +1,26 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; +import io.appwrite.enums.CreditCard; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getCreditCard( + CreditCard.AMERICAN_EXPRESS, // code + 0, // width (optional) + 0, // height (optional) + -1, // quality (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getCreditCard( - "amex", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-favicon.md b/docs/examples/java/avatars/get-favicon.md index 39c1432..70373a6 100644 --- a/docs/examples/java/avatars/get-favicon.md +++ b/docs/examples/java/avatars/get-favicon.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getFavicon( + "https://example.com", // url + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getFavicon( - "https://example.com" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-flag.md b/docs/examples/java/avatars/get-flag.md index 77bf3b1..689e27f 100644 --- a/docs/examples/java/avatars/get-flag.md +++ b/docs/examples/java/avatars/get-flag.md @@ -1,48 +1,26 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; +import io.appwrite.enums.Flag; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getFlag( + Flag.AFGHANISTAN, // code + 0, // width (optional) + 0, // height (optional) + -1, // quality (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getFlag( - "af", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-image.md b/docs/examples/java/avatars/get-image.md index 69371da..71a90dd 100644 --- a/docs/examples/java/avatars/get-image.md +++ b/docs/examples/java/avatars/get-image.md @@ -1,48 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getImage( + "https://example.com", // url + 0, // width (optional) + 0, // height (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getImage( - "https://example.com", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-initials.md b/docs/examples/java/avatars/get-initials.md index eea5669..ca16ee7 100644 --- a/docs/examples/java/avatars/get-initials.md +++ b/docs/examples/java/avatars/get-initials.md @@ -1,47 +1,25 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Avatars avatars = new Avatars(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +avatars.getInitials( + "", // name (optional) + 0, // width (optional) + 0, // height (optional) + "", // background (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Avatars avatars = new Avatars(client); + Log.d("Appwrite", result.toString()); + }) +); - avatars.getInitials( - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-q-r.md b/docs/examples/java/avatars/get-q-r.md deleted file mode 100644 index e2c48cd..0000000 --- a/docs/examples/java/avatars/get-q-r.md +++ /dev/null @@ -1,48 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Avatars avatars = new Avatars(client); - - avatars.getQR( - "[TEXT]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/avatars/get-qr.md b/docs/examples/java/avatars/get-qr.md new file mode 100644 index 0000000..781acf6 --- /dev/null +++ b/docs/examples/java/avatars/get-qr.md @@ -0,0 +1,25 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Avatars; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Avatars avatars = new Avatars(client); + +avatars.getQR( + "", // text + 1, // size (optional) + 0, // margin (optional) + false, // download (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/database/create-document.md b/docs/examples/java/database/create-document.md deleted file mode 100644 index b3a5b28..0000000 --- a/docs/examples/java/database/create-document.md +++ /dev/null @@ -1,49 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Database database = new Database(client); - - database.createDocument( - "[COLLECTION_ID]", - mapOf( "a" to "b" ), - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/database/delete-document.md b/docs/examples/java/database/delete-document.md deleted file mode 100644 index 75877c4..0000000 --- a/docs/examples/java/database/delete-document.md +++ /dev/null @@ -1,49 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Database database = new Database(client); - - database.deleteDocument( - "[COLLECTION_ID]", - "[DOCUMENT_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/database/get-document.md b/docs/examples/java/database/get-document.md deleted file mode 100644 index 69aff1d..0000000 --- a/docs/examples/java/database/get-document.md +++ /dev/null @@ -1,49 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Database database = new Database(client); - - database.getDocument( - "[COLLECTION_ID]", - "[DOCUMENT_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/database/list-documents.md b/docs/examples/java/database/list-documents.md deleted file mode 100644 index 711aa41..0000000 --- a/docs/examples/java/database/list-documents.md +++ /dev/null @@ -1,48 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Database database = new Database(client); - - database.listDocuments( - "[COLLECTION_ID]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/database/update-document.md b/docs/examples/java/database/update-document.md deleted file mode 100644 index a14c91f..0000000 --- a/docs/examples/java/database/update-document.md +++ /dev/null @@ -1,50 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Database database = new Database(client); - - database.updateDocument( - "[COLLECTION_ID]", - "[DOCUMENT_ID]", - mapOf( "a" to "b" ), - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/databases/create-document.md b/docs/examples/java/databases/create-document.md new file mode 100644 index 0000000..4804d75 --- /dev/null +++ b/docs/examples/java/databases/create-document.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.createDocument( + "", // databaseId + "", // collectionId + "", // documentId + mapOf( "a" to "b" ), // data + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/decrement-document-attribute.md b/docs/examples/java/databases/decrement-document-attribute.md new file mode 100644 index 0000000..de6a4ab --- /dev/null +++ b/docs/examples/java/databases/decrement-document-attribute.md @@ -0,0 +1,27 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.decrementDocumentAttribute( + "", // databaseId + "", // collectionId + "", // documentId + "", // attribute + 0, // value (optional) + 0, // min (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/delete-document.md b/docs/examples/java/databases/delete-document.md new file mode 100644 index 0000000..5288e53 --- /dev/null +++ b/docs/examples/java/databases/delete-document.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.deleteDocument( + "", // databaseId + "", // collectionId + "", // documentId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/get-document.md b/docs/examples/java/databases/get-document.md new file mode 100644 index 0000000..e7ae207 --- /dev/null +++ b/docs/examples/java/databases/get-document.md @@ -0,0 +1,25 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.getDocument( + "", // databaseId + "", // collectionId + "", // documentId + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/increment-document-attribute.md b/docs/examples/java/databases/increment-document-attribute.md new file mode 100644 index 0000000..94ffa9d --- /dev/null +++ b/docs/examples/java/databases/increment-document-attribute.md @@ -0,0 +1,27 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.incrementDocumentAttribute( + "", // databaseId + "", // collectionId + "", // documentId + "", // attribute + 0, // value (optional) + 0, // max (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/list-documents.md b/docs/examples/java/databases/list-documents.md new file mode 100644 index 0000000..606d677 --- /dev/null +++ b/docs/examples/java/databases/list-documents.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.listDocuments( + "", // databaseId + "", // collectionId + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/update-document.md b/docs/examples/java/databases/update-document.md new file mode 100644 index 0000000..baa827c --- /dev/null +++ b/docs/examples/java/databases/update-document.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.updateDocument( + "", // databaseId + "", // collectionId + "", // documentId + mapOf( "a" to "b" ), // data (optional) + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/databases/upsert-document.md b/docs/examples/java/databases/upsert-document.md new file mode 100644 index 0000000..868576b --- /dev/null +++ b/docs/examples/java/databases/upsert-document.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Databases; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Databases databases = new Databases(client); + +databases.upsertDocument( + "", // databaseId + "", // collectionId + "", // documentId + mapOf( "a" to "b" ), // data + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/functions/create-execution.md b/docs/examples/java/functions/create-execution.md index ea30fad..06c5027 100644 --- a/docs/examples/java/functions/create-execution.md +++ b/docs/examples/java/functions/create-execution.md @@ -1,48 +1,28 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Functions +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Functions; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Functions functions = new Functions(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +functions.createExecution( + "", // functionId + "", // body (optional) + false, // async (optional) + "", // path (optional) + ExecutionMethod.GET, // method (optional) + mapOf( "a" to "b" ), // headers (optional) + "", // scheduledAt (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Functions functions = new Functions(client); + Log.d("Appwrite", result.toString()); + }) +); - functions.createExecution( - "[FUNCTION_ID]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/functions/get-execution.md b/docs/examples/java/functions/get-execution.md index 2f4e57e..f3195fa 100644 --- a/docs/examples/java/functions/get-execution.md +++ b/docs/examples/java/functions/get-execution.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Functions +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Functions; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Functions functions = new Functions(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +functions.getExecution( + "", // functionId + "", // executionId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Functions functions = new Functions(client); + Log.d("Appwrite", result.toString()); + }) +); - functions.getExecution( - "[FUNCTION_ID]", - "[EXECUTION_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/functions/list-executions.md b/docs/examples/java/functions/list-executions.md index 68f767d..0270cf0 100644 --- a/docs/examples/java/functions/list-executions.md +++ b/docs/examples/java/functions/list-executions.md @@ -1,48 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Functions +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Functions; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Functions functions = new Functions(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +functions.listExecutions( + "", // functionId + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Functions functions = new Functions(client); + Log.d("Appwrite", result.toString()); + }) +); - functions.listExecutions( - "[FUNCTION_ID]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/graphql/mutation.md b/docs/examples/java/graphql/mutation.md new file mode 100644 index 0000000..25f095e --- /dev/null +++ b/docs/examples/java/graphql/mutation.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Graphql; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Graphql graphql = new Graphql(client); + +graphql.mutation( + mapOf( "a" to "b" ), // query + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/graphql/query.md b/docs/examples/java/graphql/query.md new file mode 100644 index 0000000..6b2a04d --- /dev/null +++ b/docs/examples/java/graphql/query.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Graphql; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Graphql graphql = new Graphql(client); + +graphql.query( + mapOf( "a" to "b" ), // query + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/locale/get-continents.md b/docs/examples/java/locale/get-continents.md deleted file mode 100644 index e96a9fe..0000000 --- a/docs/examples/java/locale/get-continents.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getContinents(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get-countries-e-u.md b/docs/examples/java/locale/get-countries-e-u.md deleted file mode 100644 index ec478bc..0000000 --- a/docs/examples/java/locale/get-countries-e-u.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getCountriesEU(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get-countries-phones.md b/docs/examples/java/locale/get-countries-phones.md deleted file mode 100644 index 34368d2..0000000 --- a/docs/examples/java/locale/get-countries-phones.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getCountriesPhones(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get-countries.md b/docs/examples/java/locale/get-countries.md deleted file mode 100644 index f1c50fc..0000000 --- a/docs/examples/java/locale/get-countries.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getCountries(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get-currencies.md b/docs/examples/java/locale/get-currencies.md deleted file mode 100644 index 63af14b..0000000 --- a/docs/examples/java/locale/get-currencies.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getCurrencies(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get-languages.md b/docs/examples/java/locale/get-languages.md deleted file mode 100644 index 5952daa..0000000 --- a/docs/examples/java/locale/get-languages.md +++ /dev/null @@ -1,46 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.getLanguages(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } -} \ No newline at end of file diff --git a/docs/examples/java/locale/get.md b/docs/examples/java/locale/get.md index 417fc16..89e1e88 100644 --- a/docs/examples/java/locale/get.md +++ b/docs/examples/java/locale/get.md @@ -1,46 +1,18 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Locale locale = new Locale(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Locale locale = new Locale(client); - - locale.get(new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); +locale.get(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; } -} \ No newline at end of file + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-codes.md b/docs/examples/java/locale/list-codes.md new file mode 100644 index 0000000..85a96fc --- /dev/null +++ b/docs/examples/java/locale/list-codes.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listCodes(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-continents.md b/docs/examples/java/locale/list-continents.md new file mode 100644 index 0000000..6f4572d --- /dev/null +++ b/docs/examples/java/locale/list-continents.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listContinents(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-countries-eu.md b/docs/examples/java/locale/list-countries-eu.md new file mode 100644 index 0000000..51458a9 --- /dev/null +++ b/docs/examples/java/locale/list-countries-eu.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listCountriesEU(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-countries-phones.md b/docs/examples/java/locale/list-countries-phones.md new file mode 100644 index 0000000..93438d2 --- /dev/null +++ b/docs/examples/java/locale/list-countries-phones.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listCountriesPhones(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-countries.md b/docs/examples/java/locale/list-countries.md new file mode 100644 index 0000000..5cd5525 --- /dev/null +++ b/docs/examples/java/locale/list-countries.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listCountries(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-currencies.md b/docs/examples/java/locale/list-currencies.md new file mode 100644 index 0000000..d3ef02c --- /dev/null +++ b/docs/examples/java/locale/list-currencies.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listCurrencies(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/locale/list-languages.md b/docs/examples/java/locale/list-languages.md new file mode 100644 index 0000000..0d72494 --- /dev/null +++ b/docs/examples/java/locale/list-languages.md @@ -0,0 +1,18 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Locale; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Locale locale = new Locale(client); + +locale.listLanguages(new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); +})); diff --git a/docs/examples/java/messaging/create-subscriber.md b/docs/examples/java/messaging/create-subscriber.md new file mode 100644 index 0000000..5616435 --- /dev/null +++ b/docs/examples/java/messaging/create-subscriber.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Messaging; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Messaging messaging = new Messaging(client); + +messaging.createSubscriber( + "", // topicId + "", // subscriberId + "", // targetId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/messaging/delete-subscriber.md b/docs/examples/java/messaging/delete-subscriber.md new file mode 100644 index 0000000..9adae5e --- /dev/null +++ b/docs/examples/java/messaging/delete-subscriber.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Messaging; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Messaging messaging = new Messaging(client); + +messaging.deleteSubscriber( + "", // topicId + "", // subscriberId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/storage/create-file.md b/docs/examples/java/storage/create-file.md index 172ef7e..598e683 100644 --- a/docs/examples/java/storage/create-file.md +++ b/docs/examples/java/storage/create-file.md @@ -1,48 +1,26 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.models.InputFile; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.createFile( + "", // bucketId + "", // fileId + InputFile.fromPath("file.png"), // file + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.createFile( - File("./path-to-files/image.jpg"), - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/delete-file.md b/docs/examples/java/storage/delete-file.md index aafae2c..5c63ae7 100644 --- a/docs/examples/java/storage/delete-file.md +++ b/docs/examples/java/storage/delete-file.md @@ -1,48 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.deleteFile( + "", // bucketId + "", // fileId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.deleteFile( - "[FILE_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/get-file-download.md b/docs/examples/java/storage/get-file-download.md index d56f293..73a8617 100644 --- a/docs/examples/java/storage/get-file-download.md +++ b/docs/examples/java/storage/get-file-download.md @@ -1,48 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.getFileDownload( + "", // bucketId + "", // fileId + "", // token (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.getFileDownload( - "[FILE_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/get-file-preview.md b/docs/examples/java/storage/get-file-preview.md index 00b54f2..67b92eb 100644 --- a/docs/examples/java/storage/get-file-preview.md +++ b/docs/examples/java/storage/get-file-preview.md @@ -1,48 +1,35 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.getFilePreview( + "", // bucketId + "", // fileId + 0, // width (optional) + 0, // height (optional) + ImageGravity.CENTER, // gravity (optional) + -1, // quality (optional) + 0, // borderWidth (optional) + "", // borderColor (optional) + 0, // borderRadius (optional) + 0, // opacity (optional) + -360, // rotation (optional) + "", // background (optional) + ImageFormat.JPG, // output (optional) + "", // token (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.getFilePreview( - "[FILE_ID]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/get-file-view.md b/docs/examples/java/storage/get-file-view.md index 087a48b..b042b1f 100644 --- a/docs/examples/java/storage/get-file-view.md +++ b/docs/examples/java/storage/get-file-view.md @@ -1,48 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.getFileView( + "", // bucketId + "", // fileId + "", // token (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.getFileView( - "[FILE_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/get-file.md b/docs/examples/java/storage/get-file.md index 9473cab..c9cc00d 100644 --- a/docs/examples/java/storage/get-file.md +++ b/docs/examples/java/storage/get-file.md @@ -1,48 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.getFile( + "", // bucketId + "", // fileId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.getFile( - "[FILE_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/list-files.md b/docs/examples/java/storage/list-files.md index e2eab69..a87286c 100644 --- a/docs/examples/java/storage/list-files.md +++ b/docs/examples/java/storage/list-files.md @@ -1,47 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.listFiles( + "", // bucketId + listOf(), // queries (optional) + "", // search (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.listFiles( - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/storage/update-file.md b/docs/examples/java/storage/update-file.md index 1477615..14fa779 100644 --- a/docs/examples/java/storage/update-file.md +++ b/docs/examples/java/storage/update-file.md @@ -1,50 +1,25 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Storage +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Storage; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Storage storage = new Storage(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +storage.updateFile( + "", // bucketId + "", // fileId + "", // name (optional) + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Storage storage = new Storage(client); + Log.d("Appwrite", result.toString()); + }) +); - storage.updateFile( - "[FILE_ID]", - listOf(), - listOf() - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/tablesdb/create-row.md b/docs/examples/java/tablesdb/create-row.md new file mode 100644 index 0000000..12d1680 --- /dev/null +++ b/docs/examples/java/tablesdb/create-row.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.createRow( + "", // databaseId + "", // tableId + "", // rowId + mapOf( "a" to "b" ), // data + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/decrement-row-column.md b/docs/examples/java/tablesdb/decrement-row-column.md new file mode 100644 index 0000000..73f2128 --- /dev/null +++ b/docs/examples/java/tablesdb/decrement-row-column.md @@ -0,0 +1,27 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.decrementRowColumn( + "", // databaseId + "", // tableId + "", // rowId + "", // column + 0, // value (optional) + 0, // min (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/delete-row.md b/docs/examples/java/tablesdb/delete-row.md new file mode 100644 index 0000000..d4c351b --- /dev/null +++ b/docs/examples/java/tablesdb/delete-row.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.deleteRow( + "", // databaseId + "", // tableId + "", // rowId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/get-row.md b/docs/examples/java/tablesdb/get-row.md new file mode 100644 index 0000000..191fc89 --- /dev/null +++ b/docs/examples/java/tablesdb/get-row.md @@ -0,0 +1,25 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.getRow( + "", // databaseId + "", // tableId + "", // rowId + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/increment-row-column.md b/docs/examples/java/tablesdb/increment-row-column.md new file mode 100644 index 0000000..dc2120e --- /dev/null +++ b/docs/examples/java/tablesdb/increment-row-column.md @@ -0,0 +1,27 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.incrementRowColumn( + "", // databaseId + "", // tableId + "", // rowId + "", // column + 0, // value (optional) + 0, // max (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/list-rows.md b/docs/examples/java/tablesdb/list-rows.md new file mode 100644 index 0000000..dc50574 --- /dev/null +++ b/docs/examples/java/tablesdb/list-rows.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.listRows( + "", // databaseId + "", // tableId + listOf(), // queries (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/update-row.md b/docs/examples/java/tablesdb/update-row.md new file mode 100644 index 0000000..0f1fabc --- /dev/null +++ b/docs/examples/java/tablesdb/update-row.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.updateRow( + "", // databaseId + "", // tableId + "", // rowId + mapOf( "a" to "b" ), // data (optional) + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/tablesdb/upsert-row.md b/docs/examples/java/tablesdb/upsert-row.md new file mode 100644 index 0000000..22c0e94 --- /dev/null +++ b/docs/examples/java/tablesdb/upsert-row.md @@ -0,0 +1,26 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.TablesDB; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +TablesDB tablesDB = new TablesDB(client); + +tablesDB.upsertRow( + "", // databaseId + "", // tableId + "", // rowId + mapOf( "a" to "b" ), // data (optional) + listOf("read("any")"), // permissions (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/create-membership.md b/docs/examples/java/teams/create-membership.md index f4d96de..bb5293e 100644 --- a/docs/examples/java/teams/create-membership.md +++ b/docs/examples/java/teams/create-membership.md @@ -1,51 +1,28 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.createMembership( + "", // teamId + listOf(), // roles + "email@example.com", // email (optional) + "", // userId (optional) + "+12065550100", // phone (optional) + "https://example.com", // url (optional) + "", // name (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.createMembership( - "[TEAM_ID]", - "email@example.com", - listOf(), - "https://example.com", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/create.md b/docs/examples/java/teams/create.md index a715c0a..ae2fdf3 100644 --- a/docs/examples/java/teams/create.md +++ b/docs/examples/java/teams/create.md @@ -1,48 +1,24 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.create( + "", // teamId + "", // name + listOf(), // roles (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.create( - "[NAME]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/delete-membership.md b/docs/examples/java/teams/delete-membership.md index 98cb29a..c8bb088 100644 --- a/docs/examples/java/teams/delete-membership.md +++ b/docs/examples/java/teams/delete-membership.md @@ -1,49 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.deleteMembership( + "", // teamId + "", // membershipId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.deleteMembership( - "[TEAM_ID]", - "[MEMBERSHIP_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/delete.md b/docs/examples/java/teams/delete.md index 828b457..74f6a4f 100644 --- a/docs/examples/java/teams/delete.md +++ b/docs/examples/java/teams/delete.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.delete( + "", // teamId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.delete( - "[TEAM_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/get-membership.md b/docs/examples/java/teams/get-membership.md new file mode 100644 index 0000000..e9dc578 --- /dev/null +++ b/docs/examples/java/teams/get-membership.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.getMembership( + "", // teamId + "", // membershipId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/get-memberships.md b/docs/examples/java/teams/get-memberships.md deleted file mode 100644 index d8a4100..0000000 --- a/docs/examples/java/teams/get-memberships.md +++ /dev/null @@ -1,48 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Teams teams = new Teams(client); - - teams.getMemberships( - "[TEAM_ID]", - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/get-prefs.md b/docs/examples/java/teams/get-prefs.md new file mode 100644 index 0000000..8ba1435 --- /dev/null +++ b/docs/examples/java/teams/get-prefs.md @@ -0,0 +1,22 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.getPrefs( + "", // teamId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/get.md b/docs/examples/java/teams/get.md index 53ba33c..f00057a 100644 --- a/docs/examples/java/teams/get.md +++ b/docs/examples/java/teams/get.md @@ -1,48 +1,22 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.get( + "", // teamId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.get( - "[TEAM_ID]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/list-memberships.md b/docs/examples/java/teams/list-memberships.md new file mode 100644 index 0000000..216ca40 --- /dev/null +++ b/docs/examples/java/teams/list-memberships.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.listMemberships( + "", // teamId + listOf(), // queries (optional) + "", // search (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/list.md b/docs/examples/java/teams/list.md index 61c2aa3..b69f21e 100644 --- a/docs/examples/java/teams/list.md +++ b/docs/examples/java/teams/list.md @@ -1,47 +1,23 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.list( + listOf(), // queries (optional) + "", // search (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.list( - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/update-membership-roles.md b/docs/examples/java/teams/update-membership-roles.md deleted file mode 100644 index ef6c673..0000000 --- a/docs/examples/java/teams/update-membership-roles.md +++ /dev/null @@ -1,50 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Teams teams = new Teams(client); - - teams.updateMembershipRoles( - "[TEAM_ID]", - "[MEMBERSHIP_ID]", - listOf() - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/update-membership-status.md b/docs/examples/java/teams/update-membership-status.md index 447d0da..4b31ed5 100644 --- a/docs/examples/java/teams/update-membership-status.md +++ b/docs/examples/java/teams/update-membership-status.md @@ -1,51 +1,25 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; -public class MainActivity extends AppCompatActivity { +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); +Teams teams = new Teams(client); - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID +teams.updateMembershipStatus( + "", // teamId + "", // membershipId + "", // userId + "", // secret + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Teams teams = new Teams(client); + Log.d("Appwrite", result.toString()); + }) +); - teams.updateMembershipStatus( - "[TEAM_ID]", - "[MEMBERSHIP_ID]", - "[USER_ID]", - "[SECRET]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/java/teams/update-membership.md b/docs/examples/java/teams/update-membership.md new file mode 100644 index 0000000..481be43 --- /dev/null +++ b/docs/examples/java/teams/update-membership.md @@ -0,0 +1,24 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.updateMembership( + "", // teamId + "", // membershipId + listOf(), // roles + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/update-name.md b/docs/examples/java/teams/update-name.md new file mode 100644 index 0000000..207bcc8 --- /dev/null +++ b/docs/examples/java/teams/update-name.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.updateName( + "", // teamId + "", // name + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/update-prefs.md b/docs/examples/java/teams/update-prefs.md new file mode 100644 index 0000000..5a0186f --- /dev/null +++ b/docs/examples/java/teams/update-prefs.md @@ -0,0 +1,23 @@ +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.services.Teams; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Teams teams = new Teams(client); + +teams.updatePrefs( + "", // teamId + mapOf( "a" to "b" ), // prefs + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) +); + diff --git a/docs/examples/java/teams/update.md b/docs/examples/java/teams/update.md deleted file mode 100644 index b4df429..0000000 --- a/docs/examples/java/teams/update.md +++ /dev/null @@ -1,49 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2"); // Your project ID - - Teams teams = new Teams(client); - - teams.update( - "[TEAM_ID]", - "[NAME]" - new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - } - ); - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-anonymous-session.md b/docs/examples/kotlin/account/create-anonymous-session.md index 5fa0699..d2966a1 100644 --- a/docs/examples/kotlin/account/create-anonymous-session.md +++ b/docs/examples/kotlin/account/create-anonymous-session.md @@ -1,24 +1,11 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.createAnonymousSession() - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.createAnonymousSession() diff --git a/docs/examples/kotlin/account/create-email-password-session.md b/docs/examples/kotlin/account/create-email-password-session.md new file mode 100644 index 0000000..a327cf2 --- /dev/null +++ b/docs/examples/kotlin/account/create-email-password-session.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createEmailPasswordSession( + email = "email@example.com", + password = "password", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-email-token.md b/docs/examples/kotlin/account/create-email-token.md new file mode 100644 index 0000000..37c9e1b --- /dev/null +++ b/docs/examples/kotlin/account/create-email-token.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createEmailToken( + userId = "", + email = "email@example.com", + phrase = false, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-j-w-t.md b/docs/examples/kotlin/account/create-j-w-t.md deleted file mode 100644 index 212838b..0000000 --- a/docs/examples/kotlin/account/create-j-w-t.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.createJWT() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-jwt.md b/docs/examples/kotlin/account/create-jwt.md new file mode 100644 index 0000000..c87eaf3 --- /dev/null +++ b/docs/examples/kotlin/account/create-jwt.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createJWT() diff --git a/docs/examples/kotlin/account/create-magic-u-r-l-session.md b/docs/examples/kotlin/account/create-magic-u-r-l-session.md deleted file mode 100644 index c803d1a..0000000 --- a/docs/examples/kotlin/account/create-magic-u-r-l-session.md +++ /dev/null @@ -1,26 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.createMagicURLSession( - email = "email@example.com", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-magic-url-token.md b/docs/examples/kotlin/account/create-magic-url-token.md new file mode 100644 index 0000000..76f4c91 --- /dev/null +++ b/docs/examples/kotlin/account/create-magic-url-token.md @@ -0,0 +1,16 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createMagicURLToken( + userId = "", + email = "email@example.com", + url = "https://example.com", // (optional) + phrase = false, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-mfa-authenticator.md b/docs/examples/kotlin/account/create-mfa-authenticator.md new file mode 100644 index 0000000..934de1c --- /dev/null +++ b/docs/examples/kotlin/account/create-mfa-authenticator.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.AuthenticatorType + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createMFAAuthenticator( + type = AuthenticatorType.TOTP, +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-mfa-challenge.md b/docs/examples/kotlin/account/create-mfa-challenge.md new file mode 100644 index 0000000..f79c498 --- /dev/null +++ b/docs/examples/kotlin/account/create-mfa-challenge.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.AuthenticationFactor + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createMFAChallenge( + factor = AuthenticationFactor.EMAIL, +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-mfa-recovery-codes.md b/docs/examples/kotlin/account/create-mfa-recovery-codes.md new file mode 100644 index 0000000..cc56966 --- /dev/null +++ b/docs/examples/kotlin/account/create-mfa-recovery-codes.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createMFARecoveryCodes() diff --git a/docs/examples/kotlin/account/create-o-auth-2-session.md b/docs/examples/kotlin/account/create-o-auth-2-session.md new file mode 100644 index 0000000..61ea634 --- /dev/null +++ b/docs/examples/kotlin/account/create-o-auth-2-session.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.OAuthProvider + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +account.createOAuth2Session( + provider = OAuthProvider.AMAZON, + success = "https://example.com", // (optional) + failure = "https://example.com", // (optional) + scopes = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-o-auth-2-token.md b/docs/examples/kotlin/account/create-o-auth-2-token.md new file mode 100644 index 0000000..cdd2ef3 --- /dev/null +++ b/docs/examples/kotlin/account/create-o-auth-2-token.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.OAuthProvider + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +account.createOAuth2Token( + provider = OAuthProvider.AMAZON, + success = "https://example.com", // (optional) + failure = "https://example.com", // (optional) + scopes = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-o-auth2session.md b/docs/examples/kotlin/account/create-o-auth2session.md deleted file mode 100644 index baf9930..0000000 --- a/docs/examples/kotlin/account/create-o-auth2session.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - account.createOAuth2Session( - activity = this@MainActivity, - provider = "amazon", - ) - - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-phone-token.md b/docs/examples/kotlin/account/create-phone-token.md new file mode 100644 index 0000000..4eb1a9a --- /dev/null +++ b/docs/examples/kotlin/account/create-phone-token.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createPhoneToken( + userId = "", + phone = "+12065550100", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-phone-verification.md b/docs/examples/kotlin/account/create-phone-verification.md new file mode 100644 index 0000000..f759466 --- /dev/null +++ b/docs/examples/kotlin/account/create-phone-verification.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createPhoneVerification() diff --git a/docs/examples/kotlin/account/create-push-target.md b/docs/examples/kotlin/account/create-push-target.md new file mode 100644 index 0000000..59b252b --- /dev/null +++ b/docs/examples/kotlin/account/create-push-target.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createPushTarget( + targetId = "", + identifier = "", + providerId = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-recovery.md b/docs/examples/kotlin/account/create-recovery.md index 2c1e759..7e13138 100644 --- a/docs/examples/kotlin/account/create-recovery.md +++ b/docs/examples/kotlin/account/create-recovery.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.createRecovery( - email = "email@example.com", - url = "https://example.com" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.createRecovery( + email = "email@example.com", + url = "https://example.com", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-session.md b/docs/examples/kotlin/account/create-session.md index 4999232..ab9e20e 100644 --- a/docs/examples/kotlin/account/create-session.md +++ b/docs/examples/kotlin/account/create-session.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.createSession( - email = "email@example.com", - password = "password" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.createSession( + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create-verification.md b/docs/examples/kotlin/account/create-verification.md index 1ebddee..669b00b 100644 --- a/docs/examples/kotlin/account/create-verification.md +++ b/docs/examples/kotlin/account/create-verification.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.createVerification( - url = "https://example.com" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.createVerification( + url = "https://example.com", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/create.md b/docs/examples/kotlin/account/create.md index a8528ec..16f3a60 100644 --- a/docs/examples/kotlin/account/create.md +++ b/docs/examples/kotlin/account/create.md @@ -1,27 +1,16 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.create( - email = "email@example.com", - password = "password", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.create( + userId = "", + email = "email@example.com", + password = "", + name = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/delete-identity.md b/docs/examples/kotlin/account/delete-identity.md new file mode 100644 index 0000000..c8d7463 --- /dev/null +++ b/docs/examples/kotlin/account/delete-identity.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.deleteIdentity( + identityId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/delete-mfa-authenticator.md b/docs/examples/kotlin/account/delete-mfa-authenticator.md new file mode 100644 index 0000000..b140a11 --- /dev/null +++ b/docs/examples/kotlin/account/delete-mfa-authenticator.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.AuthenticatorType + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.deleteMFAAuthenticator( + type = AuthenticatorType.TOTP, +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/delete-push-target.md b/docs/examples/kotlin/account/delete-push-target.md new file mode 100644 index 0000000..8e0b418 --- /dev/null +++ b/docs/examples/kotlin/account/delete-push-target.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.deletePushTarget( + targetId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/delete-session.md b/docs/examples/kotlin/account/delete-session.md index e670623..6af414b 100644 --- a/docs/examples/kotlin/account/delete-session.md +++ b/docs/examples/kotlin/account/delete-session.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.deleteSession( - sessionId = "[SESSION_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.deleteSession( + sessionId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/delete-sessions.md b/docs/examples/kotlin/account/delete-sessions.md index ec30efd..f7e6c71 100644 --- a/docs/examples/kotlin/account/delete-sessions.md +++ b/docs/examples/kotlin/account/delete-sessions.md @@ -1,24 +1,11 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.deleteSessions() - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.deleteSessions() diff --git a/docs/examples/kotlin/account/delete.md b/docs/examples/kotlin/account/delete.md deleted file mode 100644 index 7bfe95e..0000000 --- a/docs/examples/kotlin/account/delete.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.delete() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/get-logs.md b/docs/examples/kotlin/account/get-logs.md deleted file mode 100644 index 9f79f0a..0000000 --- a/docs/examples/kotlin/account/get-logs.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.getLogs() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/get-mfa-recovery-codes.md b/docs/examples/kotlin/account/get-mfa-recovery-codes.md new file mode 100644 index 0000000..f9d3612 --- /dev/null +++ b/docs/examples/kotlin/account/get-mfa-recovery-codes.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.getMFARecoveryCodes() diff --git a/docs/examples/kotlin/account/get-prefs.md b/docs/examples/kotlin/account/get-prefs.md index 9378cd2..85dbb18 100644 --- a/docs/examples/kotlin/account/get-prefs.md +++ b/docs/examples/kotlin/account/get-prefs.md @@ -1,24 +1,11 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.getPrefs() - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.getPrefs() diff --git a/docs/examples/kotlin/account/get-session.md b/docs/examples/kotlin/account/get-session.md index 45f00b6..4de64a1 100644 --- a/docs/examples/kotlin/account/get-session.md +++ b/docs/examples/kotlin/account/get-session.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.getSession( - sessionId = "[SESSION_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.getSession( + sessionId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/get-sessions.md b/docs/examples/kotlin/account/get-sessions.md deleted file mode 100644 index 4f939cc..0000000 --- a/docs/examples/kotlin/account/get-sessions.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.getSessions() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/get.md b/docs/examples/kotlin/account/get.md index c4c81a2..3e85e79 100644 --- a/docs/examples/kotlin/account/get.md +++ b/docs/examples/kotlin/account/get.md @@ -1,24 +1,11 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.get() - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.get() diff --git a/docs/examples/kotlin/account/list-identities.md b/docs/examples/kotlin/account/list-identities.md new file mode 100644 index 0000000..5908a44 --- /dev/null +++ b/docs/examples/kotlin/account/list-identities.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.listIdentities( + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/list-logs.md b/docs/examples/kotlin/account/list-logs.md new file mode 100644 index 0000000..385ccc0 --- /dev/null +++ b/docs/examples/kotlin/account/list-logs.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.listLogs( + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/list-mfa-factors.md b/docs/examples/kotlin/account/list-mfa-factors.md new file mode 100644 index 0000000..56d1c4d --- /dev/null +++ b/docs/examples/kotlin/account/list-mfa-factors.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.listMFAFactors() diff --git a/docs/examples/kotlin/account/list-sessions.md b/docs/examples/kotlin/account/list-sessions.md new file mode 100644 index 0000000..573dd86 --- /dev/null +++ b/docs/examples/kotlin/account/list-sessions.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.listSessions() diff --git a/docs/examples/kotlin/account/update-email.md b/docs/examples/kotlin/account/update-email.md index a9ec88b..0862f11 100644 --- a/docs/examples/kotlin/account/update-email.md +++ b/docs/examples/kotlin/account/update-email.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updateEmail( - email = "email@example.com", - password = "password" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updateEmail( + email = "email@example.com", + password = "password", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-magic-u-r-l-session.md b/docs/examples/kotlin/account/update-magic-u-r-l-session.md deleted file mode 100644 index 3fe1b7c..0000000 --- a/docs/examples/kotlin/account/update-magic-u-r-l-session.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Account - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val account = Account(client) - - GlobalScope.launch { - val response = account.updateMagicURLSession( - userId = "[USER_ID]", - secret = "[SECRET]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-magic-url-session.md b/docs/examples/kotlin/account/update-magic-url-session.md new file mode 100644 index 0000000..2c1a0b0 --- /dev/null +++ b/docs/examples/kotlin/account/update-magic-url-session.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateMagicURLSession( + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-mfa-authenticator.md b/docs/examples/kotlin/account/update-mfa-authenticator.md new file mode 100644 index 0000000..4f6ecd7 --- /dev/null +++ b/docs/examples/kotlin/account/update-mfa-authenticator.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account +import io.appwrite.enums.AuthenticatorType + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateMFAAuthenticator( + type = AuthenticatorType.TOTP, + otp = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-mfa-challenge.md b/docs/examples/kotlin/account/update-mfa-challenge.md new file mode 100644 index 0000000..d5cbc1f --- /dev/null +++ b/docs/examples/kotlin/account/update-mfa-challenge.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateMFAChallenge( + challengeId = "", + otp = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-mfa-recovery-codes.md b/docs/examples/kotlin/account/update-mfa-recovery-codes.md new file mode 100644 index 0000000..0277ca7 --- /dev/null +++ b/docs/examples/kotlin/account/update-mfa-recovery-codes.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateMFARecoveryCodes() diff --git a/docs/examples/kotlin/account/update-mfa.md b/docs/examples/kotlin/account/update-mfa.md new file mode 100644 index 0000000..f214e78 --- /dev/null +++ b/docs/examples/kotlin/account/update-mfa.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateMFA( + mfa = false, +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-name.md b/docs/examples/kotlin/account/update-name.md index ce9d8a3..2cb5327 100644 --- a/docs/examples/kotlin/account/update-name.md +++ b/docs/examples/kotlin/account/update-name.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updateName( - name = "[NAME]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updateName( + name = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-password.md b/docs/examples/kotlin/account/update-password.md index edee78e..140ca8b 100644 --- a/docs/examples/kotlin/account/update-password.md +++ b/docs/examples/kotlin/account/update-password.md @@ -1,26 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updatePassword( - password = "password", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updatePassword( + password = "", + oldPassword = "password", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-phone-session.md b/docs/examples/kotlin/account/update-phone-session.md new file mode 100644 index 0000000..b3911dd --- /dev/null +++ b/docs/examples/kotlin/account/update-phone-session.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updatePhoneSession( + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-phone-verification.md b/docs/examples/kotlin/account/update-phone-verification.md new file mode 100644 index 0000000..ad0d5d7 --- /dev/null +++ b/docs/examples/kotlin/account/update-phone-verification.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updatePhoneVerification( + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-phone.md b/docs/examples/kotlin/account/update-phone.md new file mode 100644 index 0000000..84ff508 --- /dev/null +++ b/docs/examples/kotlin/account/update-phone.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updatePhone( + phone = "+12065550100", + password = "password", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-prefs.md b/docs/examples/kotlin/account/update-prefs.md index 3059bc8..fdfed57 100644 --- a/docs/examples/kotlin/account/update-prefs.md +++ b/docs/examples/kotlin/account/update-prefs.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updatePrefs( - prefs = mapOf( "a" to "b" ) - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updatePrefs( + prefs = mapOf( "a" to "b" ), +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-push-target.md b/docs/examples/kotlin/account/update-push-target.md new file mode 100644 index 0000000..5c38168 --- /dev/null +++ b/docs/examples/kotlin/account/update-push-target.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updatePushTarget( + targetId = "", + identifier = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-recovery.md b/docs/examples/kotlin/account/update-recovery.md index 81c00b4..d505d1a 100644 --- a/docs/examples/kotlin/account/update-recovery.md +++ b/docs/examples/kotlin/account/update-recovery.md @@ -1,29 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updateRecovery( - userId = "[USER_ID]", - secret = "[SECRET]", - password = "password", - passwordAgain = "password" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updateRecovery( + userId = "", + secret = "", + password = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-session.md b/docs/examples/kotlin/account/update-session.md new file mode 100644 index 0000000..6fc9a9f --- /dev/null +++ b/docs/examples/kotlin/account/update-session.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateSession( + sessionId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/account/update-status.md b/docs/examples/kotlin/account/update-status.md new file mode 100644 index 0000000..b86a25a --- /dev/null +++ b/docs/examples/kotlin/account/update-status.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateStatus() diff --git a/docs/examples/kotlin/account/update-verification.md b/docs/examples/kotlin/account/update-verification.md index cea2592..028eb7c 100644 --- a/docs/examples/kotlin/account/update-verification.md +++ b/docs/examples/kotlin/account/update-verification.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Account -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val account = Account(client) - val account = Account(client) - - GlobalScope.launch { - val response = account.updateVerification( - userId = "[USER_ID]", - secret = "[SECRET]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = account.updateVerification( + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-browser.md b/docs/examples/kotlin/avatars/get-browser.md index 95a2201..d04adfb 100644 --- a/docs/examples/kotlin/avatars/get-browser.md +++ b/docs/examples/kotlin/avatars/get-browser.md @@ -1,26 +1,17 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars +import io.appwrite.enums.Browser -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getBrowser( - code = "aa", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getBrowser( + code = Browser.AVANT_BROWSER, + width = 0, // (optional) + height = 0, // (optional) + quality = -1, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-credit-card.md b/docs/examples/kotlin/avatars/get-credit-card.md index 7507c40..91c88da 100644 --- a/docs/examples/kotlin/avatars/get-credit-card.md +++ b/docs/examples/kotlin/avatars/get-credit-card.md @@ -1,26 +1,17 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars +import io.appwrite.enums.CreditCard -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getCreditCard( - code = "amex", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getCreditCard( + code = CreditCard.AMERICAN_EXPRESS, + width = 0, // (optional) + height = 0, // (optional) + quality = -1, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-favicon.md b/docs/examples/kotlin/avatars/get-favicon.md index f8e2b40..01df8cb 100644 --- a/docs/examples/kotlin/avatars/get-favicon.md +++ b/docs/examples/kotlin/avatars/get-favicon.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getFavicon( - url = "https://example.com" - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getFavicon( + url = "https://example.com", +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-flag.md b/docs/examples/kotlin/avatars/get-flag.md index 738ec8a..1dbc1cd 100644 --- a/docs/examples/kotlin/avatars/get-flag.md +++ b/docs/examples/kotlin/avatars/get-flag.md @@ -1,26 +1,17 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars +import io.appwrite.enums.Flag -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getFlag( - code = "af", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getFlag( + code = Flag.AFGHANISTAN, + width = 0, // (optional) + height = 0, // (optional) + quality = -1, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-image.md b/docs/examples/kotlin/avatars/get-image.md index 25171b1..64166c0 100644 --- a/docs/examples/kotlin/avatars/get-image.md +++ b/docs/examples/kotlin/avatars/get-image.md @@ -1,26 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getImage( - url = "https://example.com", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getImage( + url = "https://example.com", + width = 0, // (optional) + height = 0, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-initials.md b/docs/examples/kotlin/avatars/get-initials.md index e53a647..883da02 100644 --- a/docs/examples/kotlin/avatars/get-initials.md +++ b/docs/examples/kotlin/avatars/get-initials.md @@ -1,25 +1,16 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Avatars -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val avatars = Avatars(client) - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getInitials( - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = avatars.getInitials( + name = "", // (optional) + width = 0, // (optional) + height = 0, // (optional) + background = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-q-r.md b/docs/examples/kotlin/avatars/get-q-r.md deleted file mode 100644 index c9d60ea..0000000 --- a/docs/examples/kotlin/avatars/get-q-r.md +++ /dev/null @@ -1,26 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Avatars - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val avatars = Avatars(client) - - GlobalScope.launch { - val result = avatars.getQR( - text = "[TEXT]", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/avatars/get-qr.md b/docs/examples/kotlin/avatars/get-qr.md new file mode 100644 index 0000000..fa8a38c --- /dev/null +++ b/docs/examples/kotlin/avatars/get-qr.md @@ -0,0 +1,16 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Avatars + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val avatars = Avatars(client) + +val result = avatars.getQR( + text = "", + size = 1, // (optional) + margin = 0, // (optional) + download = false, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/database/create-document.md b/docs/examples/kotlin/database/create-document.md deleted file mode 100644 index 72ec7ad..0000000 --- a/docs/examples/kotlin/database/create-document.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val database = Database(client) - - GlobalScope.launch { - val response = database.createDocument( - collectionId = "[COLLECTION_ID]", - data = mapOf( "a" to "b" ), - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/database/delete-document.md b/docs/examples/kotlin/database/delete-document.md deleted file mode 100644 index 49a85c8..0000000 --- a/docs/examples/kotlin/database/delete-document.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val database = Database(client) - - GlobalScope.launch { - val response = database.deleteDocument( - collectionId = "[COLLECTION_ID]", - documentId = "[DOCUMENT_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/database/get-document.md b/docs/examples/kotlin/database/get-document.md deleted file mode 100644 index 3dd65c0..0000000 --- a/docs/examples/kotlin/database/get-document.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val database = Database(client) - - GlobalScope.launch { - val response = database.getDocument( - collectionId = "[COLLECTION_ID]", - documentId = "[DOCUMENT_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/database/list-documents.md b/docs/examples/kotlin/database/list-documents.md deleted file mode 100644 index 6511981..0000000 --- a/docs/examples/kotlin/database/list-documents.md +++ /dev/null @@ -1,26 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val database = Database(client) - - GlobalScope.launch { - val response = database.listDocuments( - collectionId = "[COLLECTION_ID]", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/database/update-document.md b/docs/examples/kotlin/database/update-document.md deleted file mode 100644 index e19ce4a..0000000 --- a/docs/examples/kotlin/database/update-document.md +++ /dev/null @@ -1,28 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Database - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val database = Database(client) - - GlobalScope.launch { - val response = database.updateDocument( - collectionId = "[COLLECTION_ID]", - documentId = "[DOCUMENT_ID]", - data = mapOf( "a" to "b" ), - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/databases/create-document.md b/docs/examples/kotlin/databases/create-document.md new file mode 100644 index 0000000..849a636 --- /dev/null +++ b/docs/examples/kotlin/databases/create-document.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.createDocument( + databaseId = "", + collectionId = "", + documentId = "", + data = mapOf( "a" to "b" ), + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/decrement-document-attribute.md b/docs/examples/kotlin/databases/decrement-document-attribute.md new file mode 100644 index 0000000..c500fa8 --- /dev/null +++ b/docs/examples/kotlin/databases/decrement-document-attribute.md @@ -0,0 +1,18 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.decrementDocumentAttribute( + databaseId = "", + collectionId = "", + documentId = "", + attribute = "", + value = 0, // (optional) + min = 0, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/delete-document.md b/docs/examples/kotlin/databases/delete-document.md new file mode 100644 index 0000000..052bf97 --- /dev/null +++ b/docs/examples/kotlin/databases/delete-document.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.deleteDocument( + databaseId = "", + collectionId = "", + documentId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/get-document.md b/docs/examples/kotlin/databases/get-document.md new file mode 100644 index 0000000..157af2b --- /dev/null +++ b/docs/examples/kotlin/databases/get-document.md @@ -0,0 +1,16 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.getDocument( + databaseId = "", + collectionId = "", + documentId = "", + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/increment-document-attribute.md b/docs/examples/kotlin/databases/increment-document-attribute.md new file mode 100644 index 0000000..0ae6b02 --- /dev/null +++ b/docs/examples/kotlin/databases/increment-document-attribute.md @@ -0,0 +1,18 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.incrementDocumentAttribute( + databaseId = "", + collectionId = "", + documentId = "", + attribute = "", + value = 0, // (optional) + max = 0, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/list-documents.md b/docs/examples/kotlin/databases/list-documents.md new file mode 100644 index 0000000..1cc785f --- /dev/null +++ b/docs/examples/kotlin/databases/list-documents.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.listDocuments( + databaseId = "", + collectionId = "", + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/update-document.md b/docs/examples/kotlin/databases/update-document.md new file mode 100644 index 0000000..d61fdea --- /dev/null +++ b/docs/examples/kotlin/databases/update-document.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.updateDocument( + databaseId = "", + collectionId = "", + documentId = "", + data = mapOf( "a" to "b" ), // (optional) + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/databases/upsert-document.md b/docs/examples/kotlin/databases/upsert-document.md new file mode 100644 index 0000000..a31dfc8 --- /dev/null +++ b/docs/examples/kotlin/databases/upsert-document.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Databases + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val databases = Databases(client) + +val result = databases.upsertDocument( + databaseId = "", + collectionId = "", + documentId = "", + data = mapOf( "a" to "b" ), + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/functions/create-execution.md b/docs/examples/kotlin/functions/create-execution.md index 3a7e599..5e1950b 100644 --- a/docs/examples/kotlin/functions/create-execution.md +++ b/docs/examples/kotlin/functions/create-execution.md @@ -1,26 +1,19 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Functions -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val functions = Functions(client) - val functions = Functions(client) - - GlobalScope.launch { - val response = functions.createExecution( - functionId = "[FUNCTION_ID]", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = functions.createExecution( + functionId = "", + body = "", // (optional) + async = false, // (optional) + path = "", // (optional) + method = ExecutionMethod.GET, // (optional) + headers = mapOf( "a" to "b" ), // (optional) + scheduledAt = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/functions/get-execution.md b/docs/examples/kotlin/functions/get-execution.md index 781f26c..267be53 100644 --- a/docs/examples/kotlin/functions/get-execution.md +++ b/docs/examples/kotlin/functions/get-execution.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Functions -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val functions = Functions(client) - val functions = Functions(client) - - GlobalScope.launch { - val response = functions.getExecution( - functionId = "[FUNCTION_ID]", - executionId = "[EXECUTION_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = functions.getExecution( + functionId = "", + executionId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/functions/list-executions.md b/docs/examples/kotlin/functions/list-executions.md index 4f11574..37ea8b8 100644 --- a/docs/examples/kotlin/functions/list-executions.md +++ b/docs/examples/kotlin/functions/list-executions.md @@ -1,26 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Functions -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val functions = Functions(client) - val functions = Functions(client) - - GlobalScope.launch { - val response = functions.listExecutions( - functionId = "[FUNCTION_ID]", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = functions.listExecutions( + functionId = "", + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/graphql/mutation.md b/docs/examples/kotlin/graphql/mutation.md new file mode 100644 index 0000000..a3a7622 --- /dev/null +++ b/docs/examples/kotlin/graphql/mutation.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Graphql + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val graphql = Graphql(client) + +val result = graphql.mutation( + query = mapOf( "a" to "b" ), +) \ No newline at end of file diff --git a/docs/examples/kotlin/graphql/query.md b/docs/examples/kotlin/graphql/query.md new file mode 100644 index 0000000..13f149c --- /dev/null +++ b/docs/examples/kotlin/graphql/query.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Graphql + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val graphql = Graphql(client) + +val result = graphql.query( + query = mapOf( "a" to "b" ), +) \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-continents.md b/docs/examples/kotlin/locale/get-continents.md deleted file mode 100644 index faf1448..0000000 --- a/docs/examples/kotlin/locale/get-continents.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getContinents() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-countries-e-u.md b/docs/examples/kotlin/locale/get-countries-e-u.md deleted file mode 100644 index 5a3552f..0000000 --- a/docs/examples/kotlin/locale/get-countries-e-u.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getCountriesEU() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-countries-phones.md b/docs/examples/kotlin/locale/get-countries-phones.md deleted file mode 100644 index 565097e..0000000 --- a/docs/examples/kotlin/locale/get-countries-phones.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getCountriesPhones() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-countries.md b/docs/examples/kotlin/locale/get-countries.md deleted file mode 100644 index e327c14..0000000 --- a/docs/examples/kotlin/locale/get-countries.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getCountries() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-currencies.md b/docs/examples/kotlin/locale/get-currencies.md deleted file mode 100644 index 00e1199..0000000 --- a/docs/examples/kotlin/locale/get-currencies.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getCurrencies() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get-languages.md b/docs/examples/kotlin/locale/get-languages.md deleted file mode 100644 index 796747a..0000000 --- a/docs/examples/kotlin/locale/get-languages.md +++ /dev/null @@ -1,24 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Locale - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.getLanguages() - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/locale/get.md b/docs/examples/kotlin/locale/get.md index f89c66a..a116aed 100644 --- a/docs/examples/kotlin/locale/get.md +++ b/docs/examples/kotlin/locale/get.md @@ -1,24 +1,11 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Locale -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val locale = Locale(client) - val locale = Locale(client) - - GlobalScope.launch { - val response = locale.get() - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = locale.get() diff --git a/docs/examples/kotlin/locale/list-codes.md b/docs/examples/kotlin/locale/list-codes.md new file mode 100644 index 0000000..0b63b06 --- /dev/null +++ b/docs/examples/kotlin/locale/list-codes.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listCodes() diff --git a/docs/examples/kotlin/locale/list-continents.md b/docs/examples/kotlin/locale/list-continents.md new file mode 100644 index 0000000..98acdc9 --- /dev/null +++ b/docs/examples/kotlin/locale/list-continents.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listContinents() diff --git a/docs/examples/kotlin/locale/list-countries-eu.md b/docs/examples/kotlin/locale/list-countries-eu.md new file mode 100644 index 0000000..c016025 --- /dev/null +++ b/docs/examples/kotlin/locale/list-countries-eu.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listCountriesEU() diff --git a/docs/examples/kotlin/locale/list-countries-phones.md b/docs/examples/kotlin/locale/list-countries-phones.md new file mode 100644 index 0000000..d95c1c6 --- /dev/null +++ b/docs/examples/kotlin/locale/list-countries-phones.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listCountriesPhones() diff --git a/docs/examples/kotlin/locale/list-countries.md b/docs/examples/kotlin/locale/list-countries.md new file mode 100644 index 0000000..4775161 --- /dev/null +++ b/docs/examples/kotlin/locale/list-countries.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listCountries() diff --git a/docs/examples/kotlin/locale/list-currencies.md b/docs/examples/kotlin/locale/list-currencies.md new file mode 100644 index 0000000..6d0a04f --- /dev/null +++ b/docs/examples/kotlin/locale/list-currencies.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listCurrencies() diff --git a/docs/examples/kotlin/locale/list-languages.md b/docs/examples/kotlin/locale/list-languages.md new file mode 100644 index 0000000..de588aa --- /dev/null +++ b/docs/examples/kotlin/locale/list-languages.md @@ -0,0 +1,11 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Locale + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val locale = Locale(client) + +val result = locale.listLanguages() diff --git a/docs/examples/kotlin/messaging/create-subscriber.md b/docs/examples/kotlin/messaging/create-subscriber.md new file mode 100644 index 0000000..b7e244f --- /dev/null +++ b/docs/examples/kotlin/messaging/create-subscriber.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Messaging + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val messaging = Messaging(client) + +val result = messaging.createSubscriber( + topicId = "", + subscriberId = "", + targetId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/messaging/delete-subscriber.md b/docs/examples/kotlin/messaging/delete-subscriber.md new file mode 100644 index 0000000..9e102d6 --- /dev/null +++ b/docs/examples/kotlin/messaging/delete-subscriber.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Messaging + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val messaging = Messaging(client) + +val result = messaging.deleteSubscriber( + topicId = "", + subscriberId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/create-file.md b/docs/examples/kotlin/storage/create-file.md index 92a5e95..1c78c51 100644 --- a/docs/examples/kotlin/storage/create-file.md +++ b/docs/examples/kotlin/storage/create-file.md @@ -1,26 +1,17 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.models.InputFile import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val response = storage.createFile( - file = File("./path-to-files/image.jpg"), - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = storage.createFile( + bucketId = "", + fileId = "", + file = InputFile.fromPath("file.png"), + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/delete-file.md b/docs/examples/kotlin/storage/delete-file.md index f26acac..ca40f41 100644 --- a/docs/examples/kotlin/storage/delete-file.md +++ b/docs/examples/kotlin/storage/delete-file.md @@ -1,26 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val response = storage.deleteFile( - fileId = "[FILE_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = storage.deleteFile( + bucketId = "", + fileId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/get-file-download.md b/docs/examples/kotlin/storage/get-file-download.md index b7d3d4a..89c6e8a 100644 --- a/docs/examples/kotlin/storage/get-file-download.md +++ b/docs/examples/kotlin/storage/get-file-download.md @@ -1,26 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val result = storage.getFileDownload( - fileId = "[FILE_ID]" - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = storage.getFileDownload( + bucketId = "", + fileId = "", + token = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/get-file-preview.md b/docs/examples/kotlin/storage/get-file-preview.md index 9f1d459..d766dc7 100644 --- a/docs/examples/kotlin/storage/get-file-preview.md +++ b/docs/examples/kotlin/storage/get-file-preview.md @@ -1,26 +1,26 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val result = storage.getFilePreview( - fileId = "[FILE_ID]", - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = storage.getFilePreview( + bucketId = "", + fileId = "", + width = 0, // (optional) + height = 0, // (optional) + gravity = ImageGravity.CENTER, // (optional) + quality = -1, // (optional) + borderWidth = 0, // (optional) + borderColor = "", // (optional) + borderRadius = 0, // (optional) + opacity = 0, // (optional) + rotation = -360, // (optional) + background = "", // (optional) + output = ImageFormat.JPG, // (optional) + token = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/get-file-view.md b/docs/examples/kotlin/storage/get-file-view.md index 0b4fe07..513e1f9 100644 --- a/docs/examples/kotlin/storage/get-file-view.md +++ b/docs/examples/kotlin/storage/get-file-view.md @@ -1,26 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val result = storage.getFileView( - fileId = "[FILE_ID]" - ) - println(result); // Resource URL - } - } -} \ No newline at end of file +val result = storage.getFileView( + bucketId = "", + fileId = "", + token = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/get-file.md b/docs/examples/kotlin/storage/get-file.md index b534d3b..1e99430 100644 --- a/docs/examples/kotlin/storage/get-file.md +++ b/docs/examples/kotlin/storage/get-file.md @@ -1,26 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val response = storage.getFile( - fileId = "[FILE_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = storage.getFile( + bucketId = "", + fileId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/list-files.md b/docs/examples/kotlin/storage/list-files.md index 7d63837..06f6cda 100644 --- a/docs/examples/kotlin/storage/list-files.md +++ b/docs/examples/kotlin/storage/list-files.md @@ -1,25 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val response = storage.listFiles( - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = storage.listFiles( + bucketId = "", + queries = listOf(), // (optional) + search = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/storage/update-file.md b/docs/examples/kotlin/storage/update-file.md index 31dfb38..116d156 100644 --- a/docs/examples/kotlin/storage/update-file.md +++ b/docs/examples/kotlin/storage/update-file.md @@ -1,28 +1,16 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Storage -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val storage = Storage(client) - val storage = Storage(client) - - GlobalScope.launch { - val response = storage.updateFile( - fileId = "[FILE_ID]", - read = listOf(), - write = listOf() - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = storage.updateFile( + bucketId = "", + fileId = "", + name = "", // (optional) + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/create-row.md b/docs/examples/kotlin/tablesdb/create-row.md new file mode 100644 index 0000000..1a9cbdb --- /dev/null +++ b/docs/examples/kotlin/tablesdb/create-row.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.createRow( + databaseId = "", + tableId = "", + rowId = "", + data = mapOf( "a" to "b" ), + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/decrement-row-column.md b/docs/examples/kotlin/tablesdb/decrement-row-column.md new file mode 100644 index 0000000..645e9f4 --- /dev/null +++ b/docs/examples/kotlin/tablesdb/decrement-row-column.md @@ -0,0 +1,18 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.decrementRowColumn( + databaseId = "", + tableId = "", + rowId = "", + column = "", + value = 0, // (optional) + min = 0, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/delete-row.md b/docs/examples/kotlin/tablesdb/delete-row.md new file mode 100644 index 0000000..3fcd409 --- /dev/null +++ b/docs/examples/kotlin/tablesdb/delete-row.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.deleteRow( + databaseId = "", + tableId = "", + rowId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/get-row.md b/docs/examples/kotlin/tablesdb/get-row.md new file mode 100644 index 0000000..b754cba --- /dev/null +++ b/docs/examples/kotlin/tablesdb/get-row.md @@ -0,0 +1,16 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.getRow( + databaseId = "", + tableId = "", + rowId = "", + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/increment-row-column.md b/docs/examples/kotlin/tablesdb/increment-row-column.md new file mode 100644 index 0000000..230408a --- /dev/null +++ b/docs/examples/kotlin/tablesdb/increment-row-column.md @@ -0,0 +1,18 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.incrementRowColumn( + databaseId = "", + tableId = "", + rowId = "", + column = "", + value = 0, // (optional) + max = 0, // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/list-rows.md b/docs/examples/kotlin/tablesdb/list-rows.md new file mode 100644 index 0000000..05d9ca3 --- /dev/null +++ b/docs/examples/kotlin/tablesdb/list-rows.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.listRows( + databaseId = "", + tableId = "", + queries = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/update-row.md b/docs/examples/kotlin/tablesdb/update-row.md new file mode 100644 index 0000000..f99f8f2 --- /dev/null +++ b/docs/examples/kotlin/tablesdb/update-row.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.updateRow( + databaseId = "", + tableId = "", + rowId = "", + data = mapOf( "a" to "b" ), // (optional) + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/tablesdb/upsert-row.md b/docs/examples/kotlin/tablesdb/upsert-row.md new file mode 100644 index 0000000..d82406a --- /dev/null +++ b/docs/examples/kotlin/tablesdb/upsert-row.md @@ -0,0 +1,17 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.TablesDB + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val tablesDB = TablesDB(client) + +val result = tablesDB.upsertRow( + databaseId = "", + tableId = "", + rowId = "", + data = mapOf( "a" to "b" ), // (optional) + permissions = listOf("read("any")"), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/create-membership.md b/docs/examples/kotlin/teams/create-membership.md index e2b7d16..70eb7dd 100644 --- a/docs/examples/kotlin/teams/create-membership.md +++ b/docs/examples/kotlin/teams/create-membership.md @@ -1,29 +1,19 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.createMembership( - teamId = "[TEAM_ID]", - email = "email@example.com", - roles = listOf(), - url = "https://example.com", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.createMembership( + teamId = "", + roles = listOf(), + email = "email@example.com", // (optional) + userId = "", // (optional) + phone = "+12065550100", // (optional) + url = "https://example.com", // (optional) + name = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/create.md b/docs/examples/kotlin/teams/create.md index 068fbd6..dfa4df4 100644 --- a/docs/examples/kotlin/teams/create.md +++ b/docs/examples/kotlin/teams/create.md @@ -1,26 +1,15 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.create( - name = "[NAME]", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.create( + teamId = "", + name = "", + roles = listOf(), // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/delete-membership.md b/docs/examples/kotlin/teams/delete-membership.md index 6545af5..adf1119 100644 --- a/docs/examples/kotlin/teams/delete-membership.md +++ b/docs/examples/kotlin/teams/delete-membership.md @@ -1,27 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.deleteMembership( - teamId = "[TEAM_ID]", - membershipId = "[MEMBERSHIP_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.deleteMembership( + teamId = "", + membershipId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/delete.md b/docs/examples/kotlin/teams/delete.md index de12449..e144a78 100644 --- a/docs/examples/kotlin/teams/delete.md +++ b/docs/examples/kotlin/teams/delete.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.delete( - teamId = "[TEAM_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.delete( + teamId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/get-membership.md b/docs/examples/kotlin/teams/get-membership.md new file mode 100644 index 0000000..8fb8c54 --- /dev/null +++ b/docs/examples/kotlin/teams/get-membership.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.getMembership( + teamId = "", + membershipId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/get-memberships.md b/docs/examples/kotlin/teams/get-memberships.md deleted file mode 100644 index 89b4f54..0000000 --- a/docs/examples/kotlin/teams/get-memberships.md +++ /dev/null @@ -1,26 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.getMemberships( - teamId = "[TEAM_ID]", - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/teams/get-prefs.md b/docs/examples/kotlin/teams/get-prefs.md new file mode 100644 index 0000000..5e892fb --- /dev/null +++ b/docs/examples/kotlin/teams/get-prefs.md @@ -0,0 +1,13 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.getPrefs( + teamId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/get.md b/docs/examples/kotlin/teams/get.md index 54550b3..dbb487d 100644 --- a/docs/examples/kotlin/teams/get.md +++ b/docs/examples/kotlin/teams/get.md @@ -1,26 +1,13 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.get( - teamId = "[TEAM_ID]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.get( + teamId = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/list-memberships.md b/docs/examples/kotlin/teams/list-memberships.md new file mode 100644 index 0000000..e305403 --- /dev/null +++ b/docs/examples/kotlin/teams/list-memberships.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.listMemberships( + teamId = "", + queries = listOf(), // (optional) + search = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/list.md b/docs/examples/kotlin/teams/list.md index 6444205..984858d 100644 --- a/docs/examples/kotlin/teams/list.md +++ b/docs/examples/kotlin/teams/list.md @@ -1,25 +1,14 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.list( - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.list( + queries = listOf(), // (optional) + search = "", // (optional) +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update-membership-roles.md b/docs/examples/kotlin/teams/update-membership-roles.md deleted file mode 100644 index d9a8a41..0000000 --- a/docs/examples/kotlin/teams/update-membership-roles.md +++ /dev/null @@ -1,28 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.updateMembershipRoles( - teamId = "[TEAM_ID]", - membershipId = "[MEMBERSHIP_ID]", - roles = listOf() - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update-membership-status.md b/docs/examples/kotlin/teams/update-membership-status.md index f8e10fd..c3770c7 100644 --- a/docs/examples/kotlin/teams/update-membership-status.md +++ b/docs/examples/kotlin/teams/update-membership-status.md @@ -1,29 +1,16 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback import io.appwrite.services.Teams -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID +val teams = Teams(client) - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.updateMembershipStatus( - teamId = "[TEAM_ID]", - membershipId = "[MEMBERSHIP_ID]", - userId = "[USER_ID]", - secret = "[SECRET]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file +val result = teams.updateMembershipStatus( + teamId = "", + membershipId = "", + userId = "", + secret = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update-membership.md b/docs/examples/kotlin/teams/update-membership.md new file mode 100644 index 0000000..86216a8 --- /dev/null +++ b/docs/examples/kotlin/teams/update-membership.md @@ -0,0 +1,15 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.updateMembership( + teamId = "", + membershipId = "", + roles = listOf(), +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update-name.md b/docs/examples/kotlin/teams/update-name.md new file mode 100644 index 0000000..abeb6dc --- /dev/null +++ b/docs/examples/kotlin/teams/update-name.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.updateName( + teamId = "", + name = "", +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update-prefs.md b/docs/examples/kotlin/teams/update-prefs.md new file mode 100644 index 0000000..d0066a9 --- /dev/null +++ b/docs/examples/kotlin/teams/update-prefs.md @@ -0,0 +1,14 @@ +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Teams + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val teams = Teams(client) + +val result = teams.updatePrefs( + teamId = "", + prefs = mapOf( "a" to "b" ), +) \ No newline at end of file diff --git a/docs/examples/kotlin/teams/update.md b/docs/examples/kotlin/teams/update.md deleted file mode 100644 index 59dd69f..0000000 --- a/docs/examples/kotlin/teams/update.md +++ /dev/null @@ -1,27 +0,0 @@ -import androidx.appcompat.app.AppCompatActivity -import android.os.Bundle -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import io.appwrite.Client -import io.appwrite.services.Teams - -class MainActivity : AppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - val client = Client(applicationContext) - .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint - .setProject("5df5acd0d48c2") // Your project ID - - val teams = Teams(client) - - GlobalScope.launch { - val response = teams.update( - teamId = "[TEAM_ID]", - name = "[NAME]" - ) - val json = response.body?.string() - } - } -} \ No newline at end of file diff --git a/example-java/.gitignore b/example-java/.gitignore deleted file mode 100644 index 42afabf..0000000 --- a/example-java/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build \ No newline at end of file diff --git a/example-java/build.gradle b/example-java/build.gradle deleted file mode 100644 index fb49677..0000000 --- a/example-java/build.gradle +++ /dev/null @@ -1,40 +0,0 @@ -plugins { - id 'com.android.application' -} - -android { - compileSdkVersion 30 - buildToolsVersion "30.0.3" - - defaultConfig { - applicationId "io.appwrite.example_java" - minSdkVersion 23 - targetSdkVersion 30 - versionCode 1 - versionName "1.0" - - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } -} - -dependencies { - - implementation project(path: ':library') - implementation 'androidx.appcompat:appcompat:1.3.0' - implementation 'com.google.android.material:material:1.3.0' - implementation 'androidx.constraintlayout:constraintlayout:2.0.4' - testImplementation 'junit:junit:4.+' - androidTestImplementation 'androidx.test.ext:junit:1.1.2' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' -} \ No newline at end of file diff --git a/example-java/src/main/AndroidManifest.xml b/example-java/src/main/AndroidManifest.xml deleted file mode 100644 index 1fd3789..0000000 --- a/example-java/src/main/AndroidManifest.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/example-java/src/main/java/io/appwrite/example_java/MainActivity.java b/example-java/src/main/java/io/appwrite/example_java/MainActivity.java deleted file mode 100644 index 5b0d09b..0000000 --- a/example-java/src/main/java/io/appwrite/example_java/MainActivity.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.appwrite.example_java; - -import androidx.appcompat.app.AppCompatActivity; -import android.os.Bundle; -import android.util.Log; -import org.jetbrains.annotations.NotNull; -import org.json.JSONObject; -import io.appwrite.Client; -import io.appwrite.exceptions.AppwriteException; -import io.appwrite.services.Account; -import kotlin.Result; -import kotlin.coroutines.Continuation; -import kotlin.coroutines.CoroutineContext; -import kotlin.coroutines.EmptyCoroutineContext; -import okhttp3.Response; - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Client client = new Client(getApplicationContext()) - .setEndpoint("https://demo.appwrite.io/v1") - .setProject("6070749e6acd4"); - - Account account = new Account(client); - - try { - account.createSession("test7@test.com","password", new Continuation() { - @NotNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NotNull Object o) { - String json = ""; - try { - if (o instanceof Result.Failure) { - Result.Failure failure = (Result.Failure) o; - throw failure.exception; - } else { - Response response = (Response) o; - json = response.body().string(); - json = new JSONObject(json).toString(8); - Log.d("RESPONSE", json); - } - } catch (Throwable th) { - Log.e("ERROR", th.toString()); - } - } - }); - } catch (AppwriteException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/example-java/src/main/res/drawable/ic_launcher_background.xml b/example-java/src/main/res/drawable/ic_launcher_background.xml deleted file mode 100644 index 07d5da9..0000000 --- a/example-java/src/main/res/drawable/ic_launcher_background.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/example-java/src/main/res/drawable/ic_launcher_foreground.xml b/example-java/src/main/res/drawable/ic_launcher_foreground.xml deleted file mode 100644 index 2b068d1..0000000 --- a/example-java/src/main/res/drawable/ic_launcher_foreground.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/example-java/src/main/res/layout/activity_main.xml b/example-java/src/main/res/layout/activity_main.xml deleted file mode 100644 index 4fc2444..0000000 --- a/example-java/src/main/res/layout/activity_main.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher.xml deleted file mode 100644 index eca70cf..0000000 --- a/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml deleted file mode 100644 index eca70cf..0000000 --- a/example-java/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/example-java/src/main/res/values/colors.xml b/example-java/src/main/res/values/colors.xml deleted file mode 100644 index f8c6127..0000000 --- a/example-java/src/main/res/values/colors.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - #FFBB86FC - #FF6200EE - #FF3700B3 - #FF03DAC5 - #FF018786 - #FF000000 - #FFFFFFFF - \ No newline at end of file diff --git a/example-java/src/main/res/values/strings.xml b/example-java/src/main/res/values/strings.xml deleted file mode 100644 index 71e50b3..0000000 --- a/example-java/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - Example Java - \ No newline at end of file diff --git a/example-java/src/main/res/values/themes.xml b/example-java/src/main/res/values/themes.xml deleted file mode 100644 index dde245d..0000000 --- a/example-java/src/main/res/values/themes.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - \ No newline at end of file diff --git a/example/build.gradle b/example/build.gradle index 6057427..0ebf8b2 100644 --- a/example/build.gradle +++ b/example/build.gradle @@ -1,16 +1,18 @@ plugins { id 'com.android.application' id 'kotlin-android' + id 'kotlin-kapt' } android { - compileSdkVersion 30 - buildToolsVersion "30.0.3" + namespace "io.appwrite.android" + + compileSdkVersion 34 defaultConfig { applicationId "io.appwrite.android" minSdkVersion 21 - targetSdkVersion 30 + targetSdkVersion 34 versionCode 1 versionName "1.0" @@ -37,23 +39,27 @@ android { } dependencies { + implementation(project(path: ':library')) + + implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("com.google.android.material:material:1.11.0") + implementation("androidx.constraintlayout:constraintlayout:2.1.4") + implementation("androidx.navigation:navigation-fragment-ktx:2.7.7") + implementation("androidx.fragment:fragment-ktx:1.6.2") + implementation("androidx.navigation:navigation-ui-ktx:2.7.7") + implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0") + implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0") + implementation("androidx.navigation:navigation-fragment-ktx:2.7.7") + implementation("androidx.navigation:navigation-ui-ktx:2.7.7") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1") + + implementation(platform("com.google.firebase:firebase-bom:32.7.0")) + implementation("com.google.firebase:firebase-messaging") - implementation project(path: ':library') - implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - implementation 'androidx.core:core-ktx:1.5.0' - implementation 'androidx.appcompat:appcompat:1.3.0' - implementation 'com.google.android.material:material:1.3.0' - implementation 'androidx.constraintlayout:constraintlayout:2.0.4' - implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5' - implementation "androidx.fragment:fragment-ktx:1.3.2" - implementation 'androidx.navigation:navigation-ui-ktx:2.3.5' - implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1' - implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1' - implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5' - implementation 'androidx.navigation:navigation-ui-ktx:2.3.5' - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3" - testImplementation 'junit:junit:4.+' - androidTestImplementation 'androidx.test.ext:junit:1.1.2' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + testImplementation("junit:junit:4.13.2") + androidTestImplementation("androidx.test.ext:junit:1.1.5") + androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") } \ No newline at end of file diff --git a/example/src/main/AndroidManifest.xml b/example/src/main/AndroidManifest.xml index 91f2179..3564397 100644 --- a/example/src/main/AndroidManifest.xml +++ b/example/src/main/AndroidManifest.xml @@ -3,20 +3,22 @@ package="io.appwrite.android"> - + android:theme="@style/Theme.AppwriteAndroidSDK" + android:usesCleartextTraffic="true"> + + - + @@ -24,6 +26,13 @@ + + + + + + + \ No newline at end of file diff --git a/example/src/main/java/io/appwrite/android/services/MessagingService.kt b/example/src/main/java/io/appwrite/android/services/MessagingService.kt new file mode 100644 index 0000000..8470c66 --- /dev/null +++ b/example/src/main/java/io/appwrite/android/services/MessagingService.kt @@ -0,0 +1,37 @@ +package io.appwrite.android.services + +import com.google.firebase.messaging.FirebaseMessagingService +import io.appwrite.ID +import io.appwrite.services.Account +import kotlinx.coroutines.runBlocking + +class MessagingService : FirebaseMessagingService() { + + companion object { + var account: Account? = null + } + + override fun onNewToken(token: String) { + super.onNewToken(token) + + val prefs = getSharedPreferences("example", MODE_PRIVATE) + + prefs.edit().putString("fcmToken", token).apply() + + if (account == null) { + return + } + + val targetId = prefs.getString("targetId", null) + + runBlocking { + if (targetId == null) { + val target = account!!.createPushTarget(ID.unique(), token) + + prefs.edit().putString("targetId", target.id).apply() + } else { + account!!.updatePushTarget(targetId, token) + } + } + } +} \ No newline at end of file diff --git a/example/src/main/java/io/appwrite/android/ui/accounts/AccountsFragment.kt b/example/src/main/java/io/appwrite/android/ui/accounts/AccountsFragment.kt index a31cced..40c40b5 100644 --- a/example/src/main/java/io/appwrite/android/ui/accounts/AccountsFragment.kt +++ b/example/src/main/java/io/appwrite/android/ui/accounts/AccountsFragment.kt @@ -1,5 +1,6 @@ package io.appwrite.android.ui.accounts +import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View @@ -9,7 +10,6 @@ import androidx.activity.ComponentActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels -import androidx.lifecycle.Observer import io.appwrite.android.R import io.appwrite.android.databinding.FragmentAccountBinding @@ -31,37 +31,54 @@ class AccountsFragment : Fragment() { false ) binding.lifecycleOwner = viewLifecycleOwner + binding.login.setOnClickListener{ - viewModel.onLogin(binding.email.text, binding.password.text) + viewModel.onLogin( + binding.email.text.toString(), + binding.password.text.toString(), + context + ?.getSharedPreferences("example", Context.MODE_PRIVATE) + ?.getString("fcmToken", null) ?: "" + ) } - binding.signup.setOnClickListener{ - viewModel.onSignup(binding.email.text, binding.password.text, binding.name.text) + viewModel.onSignup( + binding.email.text.toString(), + binding.password.text.toString(), + binding.name.text.toString() + ) } - binding.getUser.setOnClickListener{ viewModel.getUser() } - binding.oAuth.setOnClickListener{ viewModel.oAuthLogin(activity as ComponentActivity) } - binding.logout.setOnClickListener{ viewModel.logout() } - viewModel.error.observe(viewLifecycleOwner, Observer { event -> - event?.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled - Toast.makeText(requireContext(), it.message , Toast.LENGTH_SHORT).show() + viewModel.error.observe(viewLifecycleOwner) { event -> + event?.getContentIfNotHandled()?.let { + Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } - }) + } - viewModel.response.observe(viewLifecycleOwner, Observer { event -> + viewModel.response.observe(viewLifecycleOwner) { event -> event?.getContentIfNotHandled()?.let { binding.responseTV.setText(it) } - }) + } + + viewModel.target.observe(viewLifecycleOwner) { event -> + event?.getContentIfNotHandled()?.let { + context + ?.getSharedPreferences("example", Context.MODE_PRIVATE) + ?.edit() + ?.putString("targetId", it.id) + ?.apply() + } + } return binding.root } diff --git a/example/src/main/java/io/appwrite/android/ui/accounts/AccountsViewModel.kt b/example/src/main/java/io/appwrite/android/ui/accounts/AccountsViewModel.kt index 2d812e8..4302327 100644 --- a/example/src/main/java/io/appwrite/android/ui/accounts/AccountsViewModel.kt +++ b/example/src/main/java/io/appwrite/android/ui/accounts/AccountsViewModel.kt @@ -1,39 +1,56 @@ package io.appwrite.android.ui.accounts -import android.text.Editable import androidx.activity.ComponentActivity import androidx.lifecycle.* +import io.appwrite.ID +import io.appwrite.android.services.MessagingService import io.appwrite.android.utils.Client.client import io.appwrite.android.utils.Event +import io.appwrite.enums.OAuthProvider import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.toJson +import io.appwrite.models.Target import io.appwrite.services.Account import kotlinx.coroutines.launch -import org.json.JSONObject - class AccountsViewModel : ViewModel() { - private val _error = MutableLiveData>().apply { - value = null - } + private val _error = MutableLiveData>().apply { value = null } val error: LiveData> = _error - private val _response = MutableLiveData>().apply { - value = null - } + private val _response = MutableLiveData>().apply { value = null } val response: LiveData> = _response - private val accountService by lazy { - Account(client) + private val _target = MutableLiveData>().apply { value = null } + val target: LiveData> = _target + + private val account by lazy { + val account = Account(client) + + MessagingService.account = account + + account } - fun onLogin(email: Editable , password : Editable) { + fun onLogin( + email: String, + password: String, + token: String?, + ) { viewModelScope.launch { try { - var response = accountService.createSession(email.toString(), password.toString()) - var json = response.body?.string() ?: "" - json = JSONObject(json).toString(8) - _response.postValue(Event(json)) + val session = account.createEmailPasswordSession( + email, + password + ) + + if (token != null) { + val target = account.createPushTarget(ID.unique(), token) + + _target.postValue(Event(target)) + } + + _response.postValue(Event(session.toJson())) } catch (e: AppwriteException) { _error.postValue(Event(e)) } @@ -41,13 +58,16 @@ class AccountsViewModel : ViewModel() { } - fun onSignup(email: Editable , password : Editable, name: Editable) { + fun onSignup(email: String, password: String, name: String) { viewModelScope.launch { try { - var response = accountService.create(email.toString(), password.toString(), name.toString()) - var json = response.body?.string() ?: "" - json = JSONObject(json).toString(2) - _response.postValue(Event(json)) + val user = account.create( + ID.unique(), + email, + password, + name + ) + _response.postValue(Event(user.toJson())) } catch (e: AppwriteException) { _error.postValue(Event(e)) } @@ -58,7 +78,12 @@ class AccountsViewModel : ViewModel() { fun oAuthLogin(activity: ComponentActivity) { viewModelScope.launch { try { - accountService.createOAuth2Session(activity, "facebook", "appwrite-callback-6070749e6acd4://demo.appwrite.io/auth/oauth2/success", "appwrite-callback-6070749e6acd4://demo.appwrite.io/auth/oauth2/failure") + account.createOAuth2Session( + activity, + OAuthProvider.FACEBOOK, + "appwrite-callback-6070749e6acd4://cloud.appwrite.io/auth/oauth2/success", + "appwrite-callback-6070749e6acd4://cloud.appwrite.io/auth/oauth2/failure" + ) } catch (e: Exception) { _error.postValue(Event(e)) } catch (e: AppwriteException) { @@ -70,10 +95,8 @@ class AccountsViewModel : ViewModel() { fun getUser() { viewModelScope.launch { try { - var response = accountService.get() - var json = response.body?.string() ?: "" - json = JSONObject(json).toString(2) - _response.postValue(Event(json)) + val user = account.get() + _response.postValue(Event(user.toJson())) } catch (e: AppwriteException) { _error.postValue(Event(e)) } @@ -83,14 +106,11 @@ class AccountsViewModel : ViewModel() { fun logout() { viewModelScope.launch { try { - var response = accountService.deleteSession("current") - var json = response.body?.string()?.ifEmpty { "{}" } - json = JSONObject(json).toString(4) - _response.postValue(Event(json)) + val result = account.deleteSession("current") + _response.postValue(Event(result.toJson())) } catch (e: AppwriteException) { _error.postValue(Event(e)) } } } - } \ No newline at end of file diff --git a/example/src/main/java/io/appwrite/android/utils/Client.kt b/example/src/main/java/io/appwrite/android/utils/Client.kt index 66ce681..f62869b 100644 --- a/example/src/main/java/io/appwrite/android/utils/Client.kt +++ b/example/src/main/java/io/appwrite/android/utils/Client.kt @@ -8,13 +8,8 @@ object Client { fun create(context: Context) { client = Client(context) - .setEndpoint("https://demo.appwrite.io/v1") - .setProject("6070749e6acd4") - - /* Useful when testing locally */ -// client = Client(context) -// .setEndpoint("https://192.168.1.35/v1") -// .setProject("60bdbc911784e") -// .setSelfSigned(true) + .setEndpoint("https://.cloud.appwrite.io/v1") + .setProject("65a8e2b4632c04b1f5da") + .setSelfSigned(true) } } \ No newline at end of file diff --git a/example/src/main/res/layout/fragment_account.xml b/example/src/main/res/layout/fragment_account.xml index 2fb34c9..4173be1 100644 --- a/example/src/main/res/layout/fragment_account.xml +++ b/example/src/main/res/layout/fragment_account.xml @@ -57,6 +57,7 @@ android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="name" + android:text="Tester" android:inputType="text" app:layout_constraintStart_toStartOf="@id/password" app:layout_constraintTop_toBottomOf="@id/password" /> diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2dadb9d..ebd754f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ #Tue Jun 01 15:55:54 IST 2021 distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/library/build.gradle b/library/build.gradle index 9ae290e..998da2b 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,4 +1,3 @@ -import org.jetbrains.kotlin.config.KotlinCompilerVersion plugins { id("com.android.library") id("kotlin-android") @@ -20,12 +19,20 @@ ext { GITHUB_SCM_CONNECTION = 'scm:git:git://github.com/appwrite/sdk-for-android.git' } +version PUBLISH_VERSION + android { - compileSdkVersion(30) + namespace PUBLISH_GROUP_ID + + compileSdkVersion(34) + + buildFeatures { + buildConfig true + } defaultConfig { minSdkVersion(21) - targetSdkVersion(30) + targetSdkVersion(34) versionCode = 1 versionName = "1.0" buildConfigField "String", "SDK_VERSION", "\"${PUBLISH_VERSION}\"" @@ -42,39 +49,32 @@ android { ) } } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } kotlinOptions { jvmTarget = "1.8" } } dependencies { - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${KotlinCompilerVersion.VERSION}") - api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1") - api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0") + implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1") + api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1") - api(platform("com.squareup.okhttp3:okhttp-bom:4.9.0")) - api("com.squareup.okhttp3:okhttp") - implementation("com.squareup.okhttp3:okhttp-urlconnection") - implementation("com.squareup.okhttp3:logging-interceptor") - implementation("com.google.code.gson:gson:2.8.7") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.google.code.gson:gson:2.10.1") - implementation("net.gotev:cookie-store:1.3.5") - implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.3.1") - implementation("androidx.lifecycle:lifecycle-common-java8:2.3.1") - implementation("androidx.appcompat:appcompat:1.3.1") - implementation("androidx.fragment:fragment-ktx:1.3.6") - implementation("androidx.activity:activity-ktx:1.3.1") - implementation("androidx.browser:browser:1.3.0") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0") + implementation("androidx.lifecycle:lifecycle-common-java8:2.7.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("androidx.fragment:fragment-ktx:1.6.2") + implementation("androidx.activity:activity-ktx:1.8.2") + implementation("androidx.browser:browser:1.7.0") + implementation("androidx.core:core-ktx:1.12.0") - testImplementation 'junit:junit:4.+' - testImplementation "androidx.test.ext:junit-ktx:1.1.3" - testImplementation "androidx.test:core-ktx:1.4.0" - testImplementation "org.robolectric:robolectric:4.5.1" - testApi("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.1") + testImplementation("junit:junit:4.13.2") + testImplementation("androidx.test.ext:junit-ktx:1.1.5") + testImplementation("androidx.test:core-ktx:1.5.0") + testImplementation("org.robolectric:robolectric:4.11.1") + testApi("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.1") } -apply from: "${rootProject.projectDir}/scripts/publish-module.gradle" \ No newline at end of file +apply from: "${rootProject.projectDir}/scripts/publish-module.gradle" diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml index b0ab63a..899321d 100644 --- a/library/src/main/AndroidManifest.xml +++ b/library/src/main/AndroidManifest.xml @@ -1,8 +1,7 @@ - + - + + \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/Client.kt b/library/src/main/java/io/appwrite/Client.kt index 0e55ec7..10f9255 100644 --- a/library/src/main/java/io/appwrite/Client.kt +++ b/library/src/main/java/io/appwrite/Client.kt @@ -1,30 +1,35 @@ package io.appwrite import android.content.Context +import android.content.Intent import android.content.pm.PackageManager -import com.google.gson.Gson -import io.appwrite.appwrite.BuildConfig +import io.appwrite.cookies.ListenableCookieJar +import io.appwrite.cookies.stores.SharedPreferencesCookieStore import io.appwrite.exceptions.AppwriteException import io.appwrite.extensions.fromJson +import io.appwrite.extensions.toJson +import io.appwrite.models.InputFile +import io.appwrite.models.UploadProgress import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.suspendCancellableCoroutine -import net.gotev.cookiestore.SharedPreferencesCookieStore import okhttp3.* import okhttp3.Headers.Companion.toHeaders import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody +import java.io.BufferedInputStream import java.io.BufferedReader import java.io.File +import java.io.RandomAccessFile import java.io.IOException +import java.lang.IllegalArgumentException import java.net.CookieManager import java.net.CookiePolicy import java.security.SecureRandom import java.security.cert.X509Certificate -import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager @@ -34,26 +39,35 @@ import kotlin.coroutines.resume class Client @JvmOverloads constructor( context: Context, - var endPoint: String = "https://appwrite.io/v1", - var endPointRealtime: String? = null, + var endpoint: String = "https://cloud.appwrite.io/v1", + var endpointRealtime: String? = null, private var selfSigned: Boolean = false ) : CoroutineScope { + companion object { + /** + * The size for chunked uploads in bytes. + */ + internal const val CHUNK_SIZE = 5*1024*1024; // 5MB + internal const val GLOBAL_PREFS = "io.appwrite" + internal const val COOKIE_PREFS = "myCookie" + } + override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private val job = Job() - lateinit var http: OkHttpClient + internal lateinit var http: OkHttpClient + + internal val headers: MutableMap - private val headers: MutableMap - val config: MutableMap - private val cookieJar = CookieManager( - SharedPreferencesCookieStore(context, "myCookie"), + internal val cookieJar = ListenableCookieJar(CookieManager( + SharedPreferencesCookieStore(context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE)), CookiePolicy.ACCEPT_ALL - ) + )) private val appVersion by lazy { try { @@ -70,11 +84,14 @@ class Client @JvmOverloads constructor( "content-type" to "application/json", "origin" to "appwrite-android://${context.packageName}", "user-agent" to "${context.packageName}/${appVersion}, ${System.getProperty("http.agent")}", - "x-sdk-version" to "appwrite:android:${BuildConfig.SDK_VERSION}", - "x-appwrite-response-format" to "0.10.0" + "x-sdk-name" to "Android", + "x-sdk-platform" to "client", + "x-sdk-language" to "android", + "x-sdk-version" to "9.0.0", + "x-appwrite-response-format" to "1.8.0" ) config = mutableMapOf() - + setSelfSigned(selfSigned) } @@ -121,19 +138,49 @@ class Client @JvmOverloads constructor( return this } + /** + * Set Session + * + * The user session to authenticate with + * + * @param {string} session + * + * @return this + */ + fun setSession(value: String): Client { + config["session"] = value + addHeader("x-appwrite-session", value) + return this + } + + /** + * Set DevKey + * + * Your secret dev API key + * + * @param {string} devkey + * + * @return this + */ + fun setDevKey(value: String): Client { + config["devKey"] = value + addHeader("x-appwrite-dev-key", value) + return this + } + /** * Set self Signed - * + * * @param status * - * @return this + * @return this */ fun setSelfSigned(status: Boolean): Client { selfSigned = status val builder = OkHttpClient() .newBuilder() - .cookieJar(JavaNetCookieJar(cookieJar)) + .cookieJar(cookieJar) if (!selfSigned) { http = builder.build() @@ -143,9 +190,12 @@ class Client @JvmOverloads constructor( try { // Create a trust manager that does not validate certificate chains val trustAllCerts = arrayOf( + @Suppress("CustomX509TrustManager") object : X509TrustManager { + @Suppress("TrustAllX509TrustManager") override fun checkClientTrusted(chain: Array, authType: String) { } + @Suppress("TrustAllX509TrustManager") override fun checkServerTrusted(chain: Array, authType: String) { } override fun getAcceptedIssuers(): Array { @@ -160,7 +210,7 @@ class Client @JvmOverloads constructor( // Create an ssl socket factory with our all-trusting manager val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager) - builder.hostnameVerifier(HostnameVerifier { _, _ -> true }) + builder.hostnameVerifier { _, _ -> true } http = builder.build() } catch (e: Exception) { @@ -172,71 +222,98 @@ class Client @JvmOverloads constructor( /** * Set endpoint and realtime endpoint. - * + * * @param endpoint * - * @return this + * @return this */ - fun setEndpoint(endPoint: String): Client { - this.endPoint = endPoint - - if (this.endPointRealtime == null && endPoint.startsWith("http")) { - this.endPointRealtime = endPoint.replaceFirst("http", "ws") + @Throws(IllegalArgumentException::class) + fun setEndpoint(endpoint: String): Client { + require(endpoint.startsWith("http://") || endpoint.startsWith("https://")) { + "Invalid endpoint URL: $endpoint" } + this.endpoint = endpoint + this.endpointRealtime = endpoint.replaceFirst("http", "ws") + return this } /** - * Set realtime endpoint - * - * @param endpoint - * - * @return this - */ - fun setEndpointRealtime(endPoint: String): Client { - this.endPointRealtime = endPoint + * Set realtime endpoint + * + * @param endpoint + * + * @return this + */ + @Throws(IllegalArgumentException::class) + fun setEndpointRealtime(endpoint: String): Client { + require(endpoint.startsWith("ws://") || endpoint.startsWith("wss://")) { + "Invalid realtime endpoint URL: $endpoint" + } + + this.endpointRealtime = endpoint return this } /** * Add Header - * + * * @param key * @param value * - * @return this + * @return this */ fun addHeader(key: String, value: String): Client { headers[key] = value return this } + /** + * Sends a "ping" request to Appwrite to verify connectivity. + * + * @return String + */ + suspend fun ping(): String { + val apiPath = "/ping" + val apiParams = mutableMapOf() + val apiHeaders = mutableMapOf("content-type" to "application/json") + + return call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = String::class.java + ) + } + /** * Send the HTTP request - * + * * @param method * @param path * @param headers * @param params * - * @return [Response] + * @return [T] */ @Throws(AppwriteException::class) - suspend fun call( - method: String, - path: String, - headers: Map = mapOf(), - params: Map = mapOf() - ): Response { - + suspend fun call( + method: String, + path: String, + headers: Map = mapOf(), + params: Map = mapOf(), + responseType: Class, + converter: ((Any) -> T)? = null + ): T { val filteredParams = params.filterValues { it != null } val requestHeaders = this.headers.toHeaders().newBuilder() .addAll(headers.toHeaders()) .build() - val httpBuilder = (endPoint + path).toHttpUrl().newBuilder() + val httpBuilder = (endpoint + path).toHttpUrl().newBuilder() if ("GET" == method) { filteredParams.forEach { @@ -264,7 +341,7 @@ class Client @JvmOverloads constructor( .get() .build() - return awaitResponse(request) + return awaitResponse(request, responseType, converter) } val body = if (MultipartBody.FORM.toString() == headers["content-type"]) { @@ -273,8 +350,7 @@ class Client @JvmOverloads constructor( filteredParams.forEach { when { it.key == "file" -> { - val file = it.value as File - builder.addFormDataPart(it.key, file.name, file.asRequestBody()) + builder.addPart(it.value as MultipartBody.Part) } it.value is List<*> -> { val list = it.value as List<*> @@ -292,7 +368,8 @@ class Client @JvmOverloads constructor( } builder.build() } else { - Gson().toJson(filteredParams) + filteredParams + .toJson() .toRequestBody("application/json".toMediaType()) } @@ -302,21 +379,149 @@ class Client @JvmOverloads constructor( .method(method, body) .build() - return awaitResponse(request) + return awaitResponse(request, responseType, converter) } /** - * Await Response - * - * @param method + * Upload a file in chunks + * * @param path * @param headers * @param params * - * @return [Response] + * @return [T] */ @Throws(AppwriteException::class) - private suspend fun awaitResponse(request: Request) = suspendCancellableCoroutine { + suspend fun chunkedUpload( + path: String, + headers: MutableMap, + params: MutableMap, + responseType: Class, + converter: ((Any) -> T), + paramName: String, + idParamName: String? = null, + onProgress: ((UploadProgress) -> Unit)? = null, + ): T { + var file: RandomAccessFile? = null + val input = params[paramName] as InputFile + val size: Long = when(input.sourceType) { + "path", "file" -> { + file = RandomAccessFile(input.path, "r") + file.length() + } + "bytes" -> { + (input.data as ByteArray).size.toLong() + } + else -> throw UnsupportedOperationException() + } + + if (size < CHUNK_SIZE) { + val data = when(input.sourceType) { + "file", "path" -> File(input.path).asRequestBody() + "bytes" -> (input.data as ByteArray).toRequestBody(input.mimeType.toMediaType()) + else -> throw UnsupportedOperationException() + } + params[paramName] = MultipartBody.Part.createFormData( + paramName, + input.filename, + data + ) + return call( + method = "POST", + path, + headers, + params, + responseType, + converter + ) + } + + val buffer = ByteArray(CHUNK_SIZE) + var offset = 0L + var result: Map<*, *>? = null + + if (idParamName?.isNotEmpty() == true) { + // Make a request to check if a file already exists + val current = call( + method = "GET", + path = "$path/${params[idParamName]}", + headers = headers, + params = emptyMap(), + responseType = Map::class.java, + ) + val chunksUploaded = current["chunksUploaded"] as Long + offset = chunksUploaded * CHUNK_SIZE + } + + while (offset < size) { + when(input.sourceType) { + "file", "path" -> { + file!!.seek(offset) + file!!.read(buffer) + } + "bytes" -> { + val end = if (offset + CHUNK_SIZE < size) { + offset + CHUNK_SIZE - 1 + } else { + size - 1 + } + (input.data as ByteArray).copyInto( + buffer, + startIndex = offset.toInt(), + endIndex = end.toInt() + ) + } + else -> throw UnsupportedOperationException() + } + + params[paramName] = MultipartBody.Part.createFormData( + paramName, + input.filename, + buffer.toRequestBody() + ) + + headers["Content-Range"] = + "bytes $offset-${((offset + CHUNK_SIZE) - 1).coerceAtMost(size - 1)}/$size" + + result = call( + method = "POST", + path, + headers, + params, + responseType = Map::class.java + ) + + offset += CHUNK_SIZE + headers["x-appwrite-id"] = result["\$id"].toString() + onProgress?.invoke( + UploadProgress( + id = result["\$id"].toString(), + progress = offset.coerceAtMost(size).toDouble() / size * 100, + sizeUploaded = offset.coerceAtMost(size), + chunksTotal = result["chunksTotal"].toString().toInt(), + chunksUploaded = result["chunksUploaded"].toString().toInt(), + ) + ) + } + + return converter(result as Map) + } + + /** + * Await Response + * + * @param request + * @param responseType + * @param converter + * + * @return [T] + */ + @Throws(AppwriteException::class) + private suspend fun awaitResponse( + request: Request, + responseType: Class, + converter: ((Any) -> T)? = null + ) = suspendCancellableCoroutine { http.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { if (it.isCancelled) { @@ -325,28 +530,78 @@ class Client @JvmOverloads constructor( it.cancel(e) } + @Suppress("UNCHECKED_CAST") override fun onResponse(call: Call, response: Response) { - if (response.code >= 400) { - val bodyString = response.body - ?.charStream() - ?.buffered() - ?.use(BufferedReader::readText) ?: "" - - val contentType: String = response.headers["content-type"] ?: "" - val error = if (contentType.contains("application/json", ignoreCase = true)) { - bodyString.fromJson() + if (!response.isSuccessful) { + val body = response.body!! + .charStream() + .buffered() + .use(BufferedReader::readText) + + val error = if (response.headers["content-type"]?.contains("application/json") == true) { + val map = body.fromJson>() + + AppwriteException( + map["message"] as? String ?: "", + (map["code"] as Number).toInt(), + map["type"] as? String ?: "", + body + ) } else { - AppwriteException(bodyString, response.code) + AppwriteException(body, response.code, "", body) + } + it.cancel(error) + return + } + + val warnings = response.headers["x-appwrite-warning"] + if (warnings != null) { + warnings.split(";").forEach { warning -> + println("Warning: $warning") } + } - it.cancel(AppwriteException( - error.message, - error.code, - bodyString - )) + when { + responseType == Boolean::class.java -> { + it.resume(true as T) + return + } + responseType == String::class.java -> { + val body = response.body!! + .charStream() + .buffered() + .use(BufferedReader::readText) + it.resume(body as T) + return + } + responseType == ByteArray::class.java -> { + it.resume(response.body!! + .byteStream() + .buffered() + .use(BufferedInputStream::readBytes) as T + ) + return + } + response.body == null -> { + it.resume(true as T) + return + } + } + val body = response.body!! + .charStream() + .buffered() + .use(BufferedReader::readText) + if (body.isEmpty()) { + it.resume(true as T) + return } - it.resume(response) + + val map = body.fromJson() + + it.resume( + converter?.invoke(map) ?: map as T + ) } }) } -} \ No newline at end of file +} diff --git a/library/src/main/java/io/appwrite/ID.kt b/library/src/main/java/io/appwrite/ID.kt new file mode 100644 index 0000000..b89957b --- /dev/null +++ b/library/src/main/java/io/appwrite/ID.kt @@ -0,0 +1,42 @@ +package io.appwrite + +import java.time.Instant +import kotlin.math.floor +import kotlin.random.Random + +/** + * Helper class to generate ID strings for resources. + */ +class ID { + companion object { + // Generate an hex ID based on timestamp + // Recreated from https://www.php.net/manual/en/function.uniqid.php + private fun hexTimestamp(): String { + val now = Instant.now() + val sec = now.epochSecond + val usec = (System.nanoTime() / 1000) % 1000 + + val hexTimestamp = "%08x%05x".format(sec, usec) + + return hexTimestamp + } + + fun custom(id: String): String + = id + + /** + * Generate a unique ID with padding to have a longer ID + * + * @param padding The number of characters to add to the ID + * @returns The unique ID + */ + fun unique(padding: Int = 7): String { + val baseId = hexTimestamp() + val randomPadding = (1..padding) + .map { Random.nextInt(0, 16).toString(16) } + .joinToString("") + + return baseId + randomPadding + } + } +} diff --git a/library/src/main/java/io/appwrite/Permission.kt b/library/src/main/java/io/appwrite/Permission.kt new file mode 100644 index 0000000..462b8e4 --- /dev/null +++ b/library/src/main/java/io/appwrite/Permission.kt @@ -0,0 +1,62 @@ +package io.appwrite + +/** + * Helper class to generate permission strings for resources. + */ +class Permission { + companion object { + + /** + * Generate read permission string for the provided role. + * + * @param role The role for which to generate the permission. + * @returns The read permission string. + */ + fun read(role: String): String { + return "read(\"${role}\")" + } + + /** + * Generate write permission string for the provided role. + * + * This is an alias of update, delete, and possibly create. + * Don't use write in combination with update, delete, or create. + * + * @param role The role for which to generate the permission. + * @returns The write permission string. + */ + fun write(role: String): String { + return "write(\"${role}\")" + } + + /** + * Generate create permission string for the provided role. + * + * @param role The role for which to generate the permission. + * @returns The create permission string. + */ + fun create(role: String): String { + return "create(\"${role}\")" + } + + /** + * Generate update permission string for the provided role. + * + * @param role The role for which to generate the permission. + * @returns The update permission string. + */ + fun update(role: String): String { + return "update(\"${role}\")" + } + + /** + * Generate delete permission string for the provided role. + * + * @param role The role for which to generate the permission. + * @returns The delete permission string. + */ + fun delete(role: String): String { + return "delete(\"${role}\")" + } + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/Query.kt b/library/src/main/java/io/appwrite/Query.kt new file mode 100644 index 0000000..39798f3 --- /dev/null +++ b/library/src/main/java/io/appwrite/Query.kt @@ -0,0 +1,302 @@ +package io.appwrite + +import io.appwrite.extensions.toJson +import io.appwrite.extensions.fromJson + +/** + * Helper class to generate query strings. + */ +class Query( + val method: String, + val attribute: String? = null, + val values: List? = null, +) { + /** + * Convert the query object to a JSON string. + * + * @returns The JSON string representation of the query object. + */ + override fun toString() = this.toJson() + + companion object { + + /** + * Filter resources where attribute is equal to value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun equal(attribute: String, value: Any) = Query("equal", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute is not equal to value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun notEqual(attribute: String, value: Any) = Query("notEqual", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute is less than value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun lessThan(attribute: String, value: Any) = Query("lessThan", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute is less than or equal to value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun lessThanEqual(attribute: String, value: Any) = Query("lessThanEqual", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute is greater than value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun greaterThan(attribute: String, value: Any) = Query("greaterThan", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute is greater than or equal to value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun greaterThanEqual(attribute: String, value: Any) = Query("greaterThanEqual", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute matches the search value. + * + * @param attribute The attribute to filter on. + * @param value The search value to match against. + * @returns The query string. + */ + fun search(attribute: String, value: String) = Query("search", attribute, listOf(value)).toJson() + + /** + * Filter resources where attribute is null. + * + * @param attribute The attribute to filter on. + * @returns The query string. + */ + fun isNull(attribute: String) = Query("isNull", attribute).toJson() + + /** + * Filter resources where attribute is not null. + * + * @param attribute The attribute to filter on. + * @returns The query string. + */ + fun isNotNull(attribute: String) = Query("isNotNull", attribute).toJson() + + /** + * Filter resources where attribute is between start and end (inclusive). + * + * @param attribute The attribute to filter on. + * @param start The start value of the range. + * @param end The end value of the range. + * @returns The query string. + */ + fun between(attribute: String, start: Any, end: Any) = Query("between", attribute, listOf(start, end)).toJson() + + /** + * Filter resources where attribute starts with value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun startsWith(attribute: String, value: String) = Query("startsWith", attribute, listOf(value)).toJson() + + /** + * Filter resources where attribute ends with value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun endsWith(attribute: String, value: String) = Query("endsWith", attribute, listOf(value)).toJson() + + /** + * Specify which attributes should be returned by the API call. + * + * @param attributes The list of attributes to select. + * @returns The query string. + */ + fun select(attributes: List) = Query("select", null, attributes).toJson() + + /** + * Sort results by attribute ascending. + * + * @param attribute The attribute to sort by. + * @returns The query string. + */ + fun orderAsc(attribute: String) = Query("orderAsc", attribute).toJson() + + /** + * Sort results by attribute descending. + * + * @param attribute The attribute to sort by. + * @returns The query string. + */ + fun orderDesc(attribute: String) = Query("orderDesc", attribute).toJson() + + /** + * Return results before documentId. + * + * @param documentId The document ID to use as cursor. + * @returns The query string. + */ + fun cursorBefore(documentId: String) = Query("cursorBefore", null, listOf(documentId)).toJson() + + /** + * Return results after documentId. + * + * @param documentId The document ID to use as cursor. + * @returns The query string. + */ + fun cursorAfter(documentId: String) = Query("cursorAfter", null, listOf(documentId)).toJson() + + /** + * Return only limit results. + * + * @param limit The number of results to return. + * @returns The query string. + */ + fun limit(limit: Int) = Query("limit", null, listOf(limit)).toJson() + + /** + * Filter resources by skipping the first offset results. + * + * @param offset The number of results to skip. + * @returns The query string. + */ + fun offset(offset: Int) = Query("offset", null, listOf(offset)).toJson() + + /** + * Filter resources where attribute contains the specified value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun contains(attribute: String, value: Any) = Query("contains", attribute, parseValue(value)).toJson() + + /** + * Filter resources where attribute does not contain the specified value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun notContains(attribute: String, value: Any) = Query("notContains", attribute, parseValue(value)).toJson() + + /** + * Filter resources by searching attribute for value (inverse of search). + * + * @param attribute The attribute to filter on. + * @param value The search value to match against. + * @returns The query string. + */ + fun notSearch(attribute: String, value: String) = Query("notSearch", attribute, listOf(value)).toJson() + + /** + * Filter resources where attribute is not between start and end (exclusive). + * + * @param attribute The attribute to filter on. + * @param start The start value of the range. + * @param end The end value of the range. + * @returns The query string. + */ + fun notBetween(attribute: String, start: Any, end: Any) = Query("notBetween", attribute, listOf(start, end)).toJson() + + /** + * Filter resources where attribute does not start with value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun notStartsWith(attribute: String, value: String) = Query("notStartsWith", attribute, listOf(value)).toJson() + + /** + * Filter resources where attribute does not end with value. + * + * @param attribute The attribute to filter on. + * @param value The value to compare against. + * @returns The query string. + */ + fun notEndsWith(attribute: String, value: String) = Query("notEndsWith", attribute, listOf(value)).toJson() + + /** + * Filter resources where document was created before date. + * + * @param value The date value to compare against. + * @returns The query string. + */ + fun createdBefore(value: String) = Query("createdBefore", null, listOf(value)).toJson() + + /** + * Filter resources where document was created after date. + * + * @param value The date value to compare against. + * @returns The query string. + */ + fun createdAfter(value: String) = Query("createdAfter", null, listOf(value)).toJson() + + /** + * Filter resources where document was updated before date. + * + * @param value The date value to compare against. + * @returns The query string. + */ + fun updatedBefore(value: String) = Query("updatedBefore", null, listOf(value)).toJson() + + /** + * Filter resources where document was updated after date. + * + * @param value The date value to compare against. + * @returns The query string. + */ + fun updatedAfter(value: String) = Query("updatedAfter", null, listOf(value)).toJson() + + /** + * Combine multiple queries using logical OR operator. + * + * @param queries The list of query strings to combine. + * @returns The query string. + */ + fun or(queries: List) = Query("or", null, queries.map { it.fromJson() }).toJson() + + /** + * Combine multiple queries using logical AND operator. + * + * @param queries The list of query strings to combine. + * @returns The query string. + */ + fun and(queries: List) = Query("and", null, queries.map { it.fromJson() }).toJson() + + /** + * Parse the value to a list of values. + * + * @param value The value to parse. + * @returns The list of parsed values. + */ + private fun parseValue(value: Any): List { + return when (value) { + is List<*> -> value as List + else -> listOf(value) + } + } + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/Role.kt b/library/src/main/java/io/appwrite/Role.kt new file mode 100644 index 0000000..da9ccb1 --- /dev/null +++ b/library/src/main/java/io/appwrite/Role.kt @@ -0,0 +1,72 @@ +package io.appwrite + +/** + * Helper class to generate role strings for [Permission]. + */ +class Role { + companion object { + + /** + * Grants access to anyone. + * + * This includes authenticated and unauthenticated users. + */ + fun any(): String = "any" + + /** + * Grants access to a specific user by user ID. + * + * You can optionally pass verified or unverified for + * [status] to target specific types of users. + */ + fun user(id: String, status: String = ""): String = if(status.isEmpty()) { + "user:$id" + } else { + "user:$id/$status" + } + + /** + * Grants access to any authenticated or anonymous user. + * + * You can optionally pass verified or unverified for + * [status] to target specific types of users. + */ + fun users(status: String = ""): String = if(status.isEmpty()) { + "users" + } else { + "users/$status" + } + + /** + * Grants access to any guest user without a session. + * + * Authenticated users don't have access to this role. + */ + fun guests(): String = "guests" + + /** + * Grants access to a team by team ID. + * + * You can optionally pass a role for [role] to target + * team members with the specified role. + */ + fun team(id: String, role: String = ""): String = if(role.isEmpty()) { + "team:$id" + } else { + "team:$id/$role" + } + + /** + * Grants access to a specific member of a team. + * + * When the member is removed from the team, they will + * no longer have access. + */ + fun member(id: String): String = "member:$id" + + /** + * Grants access to a user with the specified label. + */ + fun label(name: String): String = "label:$name" + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/Service.kt b/library/src/main/java/io/appwrite/Service.kt new file mode 100644 index 0000000..7a01b4b --- /dev/null +++ b/library/src/main/java/io/appwrite/Service.kt @@ -0,0 +1,10 @@ +package io.appwrite + +import io.appwrite.Client + +/** + * Abstract class for services. + * + * @param client The Appwrite client. + */ +abstract class Service(val client: Client) diff --git a/library/src/main/java/io/appwrite/cookies/Extensions.kt b/library/src/main/java/io/appwrite/cookies/Extensions.kt new file mode 100644 index 0000000..257c904 --- /dev/null +++ b/library/src/main/java/io/appwrite/cookies/Extensions.kt @@ -0,0 +1,53 @@ +package io.appwrite.cookies + +import android.os.Build +import java.net.CookieStore +import java.net.HttpCookie +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Locale +import java.util.TimeZone + +fun HttpCookie.toSetCookieString(): String { + val expires = if (maxAge != -1L) { + val dateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK).apply { + timeZone = TimeZone.getTimeZone("GMT") + } + + val calendar = Calendar.getInstance(Locale.UK).apply { set(Calendar.SECOND, maxAge.toInt()) } + + "; expires=${dateFormat.format(calendar.time)}" + } else { + "" + } + + val path = if (path != null) "; path=$path" else "" + val domain = if (domain != null) "; domain=$domain" else "" + val secure = if (secure) "; secure" else "" + val httpOnly = if (Build.VERSION.SDK_INT >= 24) { + if (isHttpOnly) "; httponly" else "" + } else { + "" + } + + return "$name=$value$expires$path$domain$secure$httpOnly" +} + +@Synchronized +fun CookieStore.syncToWebKitCookieManager() { + val webKitCookieManager = android.webkit.CookieManager.getInstance() + + cookies.forEach { + val hostUrl = "${if (it.secure) "https" else "http"}://${it.domain}" + webKitCookieManager.setCookie(hostUrl, it.toSetCookieString()) + } + + webKitCookieManager.flush() +} + +@Synchronized +@Suppress("DEPRECATION") +fun android.webkit.CookieManager.removeAll() { + removeAllCookies(null) + flush() +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/cookies/InternalCookie.kt b/library/src/main/java/io/appwrite/cookies/InternalCookie.kt new file mode 100644 index 0000000..c4ea22a --- /dev/null +++ b/library/src/main/java/io/appwrite/cookies/InternalCookie.kt @@ -0,0 +1,49 @@ +package io.appwrite.cookies + +import android.os.Build +import java.net.HttpCookie + +data class InternalCookie( + val comment: String?, + val commentURL: String?, + val discard: Boolean?, + val domain: String, + val maxAge: Long?, + val name: String, + val path: String?, + val portlist: String?, + val secure: Boolean?, + val value: String, + val version: Int?, + var httpOnly: Boolean? = null +) { + constructor(cookie: HttpCookie) : this( + cookie.comment, + cookie.commentURL, + cookie.discard, + cookie.domain, + cookie.maxAge, + cookie.name, + cookie.path, + cookie.portlist, + cookie.secure, + cookie.value, + cookie.version + ) + + fun toHttpCookie() = HttpCookie(name, value).apply { + comment = this@InternalCookie.comment + commentURL = this@InternalCookie.commentURL + discard = this@InternalCookie.discard == true + domain = this@InternalCookie.domain + maxAge = this@InternalCookie.maxAge ?: 0 + path = this@InternalCookie.path + portlist = this@InternalCookie.portlist + secure = this@InternalCookie.secure == true + version = this@InternalCookie.version ?: 0 + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + isHttpOnly = (this@InternalCookie.httpOnly == true) + } + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/cookies/ListenableCookieJar.kt b/library/src/main/java/io/appwrite/cookies/ListenableCookieJar.kt new file mode 100644 index 0000000..863eb42 --- /dev/null +++ b/library/src/main/java/io/appwrite/cookies/ListenableCookieJar.kt @@ -0,0 +1,119 @@ +package io.appwrite.cookies + +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.HttpUrl +import okhttp3.internal.cookieToString +import okhttp3.internal.delimiterOffset +import okhttp3.internal.platform.Platform +import okhttp3.internal.trimSubstring +import java.io.IOException +import java.net.CookieHandler +import java.net.HttpCookie +import java.util.Collections + +typealias CookieListener = (existing: List, new: List) -> Unit + +class ListenableCookieJar(private val cookieHandler: CookieHandler) : CookieJar { + + private val listeners: MutableMap = mutableMapOf() + + fun onSave(key: String, listener: CookieListener) { + listeners[key.hashCode()] = listener + } + + override fun saveFromResponse(url: HttpUrl, cookies: List) { + val existingCookies = loadForRequest(url) + + listeners.values.forEach { it(existingCookies, cookies) } + + val cookieStrings = mutableListOf() + for (cookie in cookies) { + cookieStrings.add(cookieToString(cookie, true)) + } + val multimap = mapOf("Set-Cookie" to cookieStrings) + try { + cookieHandler.put(url.toUri(), multimap) + } catch (e: IOException) { + Platform.get().log( + "Saving cookies failed for " + url.resolve("/...")!!, + Platform.WARN, e + ) + } + } + + override fun loadForRequest(url: HttpUrl): List { + val cookieHeaders = try { + cookieHandler.get(url.toUri(), emptyMap>()) + } catch (e: IOException) { + Platform.get().log( + "Loading cookies failed for " + url.resolve("/...")!!, + Platform.WARN, e + ) + return emptyList() + } + + var cookies: MutableList? = null + for ((key, value) in cookieHeaders) { + if (("Cookie".equals(key, ignoreCase = true) || "Cookie2".equals( + key, + ignoreCase = true + )) && + value.isNotEmpty() + ) { + for (header in value) { + if (cookies == null) cookies = mutableListOf() + cookies.addAll(decodeHeaderAsJavaNetCookies(url, header)) + } + } + } + + return if (cookies != null) { + Collections.unmodifiableList(cookies) + } else { + emptyList() + } + } + + /** + * Convert a request header to OkHttp's cookies via [HttpCookie]. That extra step handles + * multiple cookies in a single request header, which [Cookie.parse] doesn't support. + */ + private fun decodeHeaderAsJavaNetCookies(url: HttpUrl, header: String): List { + val result = mutableListOf() + var pos = 0 + val limit = header.length + var pairEnd: Int + while (pos < limit) { + pairEnd = header.delimiterOffset(";,", pos, limit) + val equalsSign = header.delimiterOffset('=', pos, pairEnd) + val name = header.trimSubstring(pos, equalsSign) + if (name.startsWith("$")) { + pos = pairEnd + 1 + continue + } + + // We have either name=value or just a name. + var value = if (equalsSign < pairEnd) { + header.trimSubstring(equalsSign + 1, pairEnd) + } else { + "" + } + + // If the value is "quoted", drop the quotes. + if (value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length - 1) + } + + result.add( + Cookie.Builder() + .name(name) + .value(value) + .domain(url.host) + .build() + ) + pos = pairEnd + 1 + } + return result + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/cookies/stores/InMemoryCookieStore.kt b/library/src/main/java/io/appwrite/cookies/stores/InMemoryCookieStore.kt new file mode 100644 index 0000000..1f2b536 --- /dev/null +++ b/library/src/main/java/io/appwrite/cookies/stores/InMemoryCookieStore.kt @@ -0,0 +1,268 @@ +package io.appwrite.cookies.stores + +import android.os.Build +import android.util.Log +import java.net.CookieStore +import java.net.HttpCookie +import java.net.URI +import java.net.URISyntaxException +import java.util.concurrent.locks.ReentrantLock + +open class InMemoryCookieStore : CookieStore { + + internal val uriIndex = mutableMapOf>() + private val lock = ReentrantLock(false) + + override fun removeAll(): Boolean { + lock.lock() + + return try { + uriIndex.clear() + uriIndex.isEmpty() + } finally { + lock.unlock() + } + } + + override fun add(uri: URI?, cookie: HttpCookie?) { + if (cookie == null) { + Log.i( + javaClass.simpleName, + "Tried to add null cookie in cookie store. Doing nothing." + ) + return + } + + if (uri == null) { + Log.i( + javaClass.simpleName, + "Tried to add null URI in cookie store. Doing nothing." + ) + return + } + + lock.lock() + try { + addIndex(getEffectiveURI(uri), cookie) + } finally { + lock.unlock() + } + } + + override fun getCookies(): List { + val cookies = mutableListOf() + + lock.lock() + try { + for (list in uriIndex.values) { + val it = list.iterator() + while (it.hasNext()) { + val cookie = it.next() + if (cookie.hasExpired()) { + it.remove() + } else if (!cookies.contains(cookie)) { + cookies.add(cookie) + } + } + } + } finally { + lock.unlock() + } + + return cookies + } + + override fun getURIs(): List { + val uris = mutableListOf() + + lock.lock() + return try { + uriIndex.keys.toList() + } finally { + uris.addAll(uriIndex.keys) + lock.unlock() + } + } + + override fun remove(uri: URI?, cookie: HttpCookie?): Boolean { + if (cookie == null) { + Log.i( + javaClass.simpleName, + "Tried to remove null cookie from cookie store. Doing nothing." + ) + return true + } + + if (uri == null) { + Log.i( + javaClass.simpleName, + "Tried to remove null URI from cookie store. Doing nothing." + ) + return true + } + + lock.lock() + + return try { + val lintedURI = getEffectiveURI(uri) + + if (uriIndex[lintedURI] == null) { + false + } else { + val cookies = uriIndex[lintedURI] + cookies?.remove(cookie) ?: false + } + } finally { + lock.unlock() + } + } + + override fun get(uri: URI?): List { + if (uri == null) { + Log.i( + javaClass.simpleName, + "Getting cookies from cookie store for null URI results in empty list" + ) + return emptyList() + } + + val cookies = arrayListOf() + + lock.lock() + try { + uri.host?.let { cookies.addAll(getInternal1(it)) } + val internal2 = getInternal2(getEffectiveURI(uri)).filter { !cookies.contains(it) } + cookies.addAll(internal2) + } finally { + lock.unlock() + } + + return cookies + } + + internal fun getEffectiveURI(uri: URI): URI { + return try { + URI(uri.scheme ?: "http", uri.host, null, null, null) + } catch (ignored: URISyntaxException) { + uri + } + } + + private fun addIndex(index: URI, cookie: HttpCookie) { + val cookies = uriIndex[index] + + if (cookies != null) { + cookies.remove(cookie) + cookies.add(cookie) + } else { + val newCookies = mutableListOf() + newCookies.add(cookie) + uriIndex[index] = newCookies + } + } + + private fun netscapeDomainMatches(domain: String?, host: String?): Boolean { + if (domain == null || host == null) { + return false + } + + // If there's no embedded dot in domain and domain is not .local + val isLocalDomain = ".local".equals(domain, ignoreCase = true) + var embeddedDotInDomain = domain.indexOf('.') + if (embeddedDotInDomain == 0) { + embeddedDotInDomain = domain.indexOf('.', 1) + } + if (!isLocalDomain && (embeddedDotInDomain == -1 || embeddedDotInDomain == domain.length - 1)) { + return false + } + + // If the host name contains no dot and the domain name is .local + val firstDotInHost = host.indexOf('.') + if (firstDotInHost == -1 && isLocalDomain) { + return true + } + + val domainLength = domain.length + val lengthDiff = host.length - domainLength + if (lengthDiff == 0) { + // If the host name and the domain name are just string-compare euqal + return host.equals(domain, ignoreCase = true) + } else if (lengthDiff > 0) { + // need to check H & D component + val D = host.substring(lengthDiff) + + // Android-changed: b/26456024 targetSdkVersion based compatibility for domain matching + // Android M and earlier: Cookies with domain "foo.com" would not match "bar.foo.com". + // The RFC dictates that the user agent must treat those domains as if they had a + // leading period and must therefore match "bar.foo.com". + return if (Build.VERSION.SDK_INT <= 23 && !domain.startsWith(".")) { + false + } else D.equals(domain, ignoreCase = true) + } else if (lengthDiff == -1) { + // if domain is actually .host + return domain[0] == '.' && host.equals(domain.substring(1), ignoreCase = true) + } + + return false + } + + private fun getInternal1(host: String): List { + // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https) + // Use a separate list to handle cookies that need to be removed so + // that there is no conflict with iterators. + val toRemove = mutableListOf() + val cookies = mutableListOf() + + for ((_, lst) in uriIndex) { + for (c in lst) { + val domain = c.domain + if (c.version == 0 && netscapeDomainMatches( + domain, + host + ) || c.version == 1 && HttpCookie.domainMatches(domain, host) + ) { + if (!c.hasExpired()) { + if (!cookies.contains(c)) { + cookies.add(c) + } + } else { + toRemove.add(c) + } + } + } + // Clean up the cookies that need to be removed + for (c in toRemove) { + lst.remove(c) + } + toRemove.clear() + } + return cookies + } + + private fun getInternal2(comparator: URI): List { + // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https) + // Removed cookieJar + val cookies = mutableListOf() + + for (index in uriIndex.keys) { + if (index === comparator || comparator.compareTo(index) == 0) { + val indexedCookies = uriIndex[index] + // Check the list of cookies associated with this domain + if (indexedCookies != null) { + val it = indexedCookies.iterator() + while (it.hasNext()) { + val ck = it.next() + if (!ck.hasExpired()) { + if (!cookies.contains(ck)) + cookies.add(ck) + } else { + it.remove() + } + } + } + } + } + + return cookies + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/cookies/stores/SharedPreferencesCookieStore.kt b/library/src/main/java/io/appwrite/cookies/stores/SharedPreferencesCookieStore.kt new file mode 100644 index 0000000..0c0b760 --- /dev/null +++ b/library/src/main/java/io/appwrite/cookies/stores/SharedPreferencesCookieStore.kt @@ -0,0 +1,97 @@ +package io.appwrite.cookies.stores + +import io.appwrite.cookies.InternalCookie +import android.content.SharedPreferences +import android.os.Build +import android.util.Log +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import java.net.HttpCookie +import java.net.URI + +open class SharedPreferencesCookieStore( + private val preferences: SharedPreferences, +) : InMemoryCookieStore() { + + private val gson = Gson() + + init { + synchronized(SharedPreferencesCookieStore::class.java) { + preferences.all.forEach { (key, value) -> + try { + val index = URI.create(key) + val listType = object : TypeToken>() {}.type + val internalCookies = + gson.fromJson>(value.toString(), listType) + val cookies = internalCookies.map { it.toHttpCookie() }.toMutableList() + uriIndex[index] = cookies + } catch (exception: Throwable) { + Log.e( + javaClass.simpleName, + "Error while loading key = $key, value = $value from cookie store", + exception + ) + } + } + } + } + + override fun removeAll(): Boolean = + synchronized(SharedPreferencesCookieStore::class.java) { + super.removeAll() + preferences.edit().clear().apply() + true + } + + override fun add(uri: URI?, cookie: HttpCookie?) = + synchronized(SharedPreferencesCookieStore::class.java) { + uri ?: return@synchronized + + super.add(uri, cookie) + val index = getEffectiveURI(uri) + val cookies = uriIndex[index] ?: return@synchronized + + val internalCookies = cookies.map { + InternalCookie(it).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + httpOnly = it.isHttpOnly + } + } + } + + val listType = object : TypeToken>() {}.type + val json = gson.toJson(internalCookies, listType) + + preferences + .edit() + .putString(index.toString(), json) + .apply() + } + + override fun remove(uri: URI?, cookie: HttpCookie?): Boolean = + synchronized(SharedPreferencesCookieStore::class.java) { + uri ?: return false + + val result = super.remove(uri, cookie) + val index = getEffectiveURI(uri) + val cookies = uriIndex[index] + val internalCookies = cookies?.map { + InternalCookie(it).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + httpOnly = it.isHttpOnly + } + } + } + val listType = object : TypeToken>() {}.type + val json = gson.toJson(internalCookies, listType) + + preferences.edit().apply { + when (cookies) { + null -> remove(index.toString()) + else -> putString(index.toString(), json) + } + }.apply() + + return result + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/coroutines/Callback.kt b/library/src/main/java/io/appwrite/coroutines/Callback.kt new file mode 100644 index 0000000..baa30fe --- /dev/null +++ b/library/src/main/java/io/appwrite/coroutines/Callback.kt @@ -0,0 +1,18 @@ +package io.appwrite.coroutines + +import kotlinx.coroutines.Dispatchers +import kotlin.coroutines.Continuation +import kotlin.coroutines.CoroutineContext + +interface Callback { + fun onComplete(result: T?, error: Throwable?) +} + +class CoroutineCallback @JvmOverloads constructor( + private val callback: Callback, + override val context: CoroutineContext = Dispatchers.Default +) : Continuation { + override fun resumeWith(result: Result) { + callback.onComplete(result.getOrNull(), result.exceptionOrNull()) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/AuthenticationFactor.kt b/library/src/main/java/io/appwrite/enums/AuthenticationFactor.kt new file mode 100644 index 0000000..cf294ca --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/AuthenticationFactor.kt @@ -0,0 +1,16 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class AuthenticationFactor(val value: String) { + @SerializedName("email") + EMAIL("email"), + @SerializedName("phone") + PHONE("phone"), + @SerializedName("totp") + TOTP("totp"), + @SerializedName("recoverycode") + RECOVERYCODE("recoverycode"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/AuthenticatorType.kt b/library/src/main/java/io/appwrite/enums/AuthenticatorType.kt new file mode 100644 index 0000000..a7d37ae --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/AuthenticatorType.kt @@ -0,0 +1,10 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class AuthenticatorType(val value: String) { + @SerializedName("totp") + TOTP("totp"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/Browser.kt b/library/src/main/java/io/appwrite/enums/Browser.kt new file mode 100644 index 0000000..9800111 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/Browser.kt @@ -0,0 +1,36 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class Browser(val value: String) { + @SerializedName("aa") + AVANT_BROWSER("aa"), + @SerializedName("an") + ANDROID_WEBVIEW_BETA("an"), + @SerializedName("ch") + GOOGLE_CHROME("ch"), + @SerializedName("ci") + GOOGLE_CHROME_IOS("ci"), + @SerializedName("cm") + GOOGLE_CHROME_MOBILE("cm"), + @SerializedName("cr") + CHROMIUM("cr"), + @SerializedName("ff") + MOZILLA_FIREFOX("ff"), + @SerializedName("sf") + SAFARI("sf"), + @SerializedName("mf") + MOBILE_SAFARI("mf"), + @SerializedName("ps") + MICROSOFT_EDGE("ps"), + @SerializedName("oi") + MICROSOFT_EDGE_IOS("oi"), + @SerializedName("om") + OPERA_MINI("om"), + @SerializedName("op") + OPERA("op"), + @SerializedName("on") + OPERA_NEXT("on"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/CreditCard.kt b/library/src/main/java/io/appwrite/enums/CreditCard.kt new file mode 100644 index 0000000..1826304 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/CreditCard.kt @@ -0,0 +1,42 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class CreditCard(val value: String) { + @SerializedName("amex") + AMERICAN_EXPRESS("amex"), + @SerializedName("argencard") + ARGENCARD("argencard"), + @SerializedName("cabal") + CABAL("cabal"), + @SerializedName("cencosud") + CENCOSUD("cencosud"), + @SerializedName("diners") + DINERS_CLUB("diners"), + @SerializedName("discover") + DISCOVER("discover"), + @SerializedName("elo") + ELO("elo"), + @SerializedName("hipercard") + HIPERCARD("hipercard"), + @SerializedName("jcb") + JCB("jcb"), + @SerializedName("mastercard") + MASTERCARD("mastercard"), + @SerializedName("naranja") + NARANJA("naranja"), + @SerializedName("targeta-shopping") + TARJETA_SHOPPING("targeta-shopping"), + @SerializedName("union-china-pay") + UNION_CHINA_PAY("union-china-pay"), + @SerializedName("visa") + VISA("visa"), + @SerializedName("mir") + MIR("mir"), + @SerializedName("maestro") + MAESTRO("maestro"), + @SerializedName("rupay") + RUPAY("rupay"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/ExecutionMethod.kt b/library/src/main/java/io/appwrite/enums/ExecutionMethod.kt new file mode 100644 index 0000000..946fdb3 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/ExecutionMethod.kt @@ -0,0 +1,20 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class ExecutionMethod(val value: String) { + @SerializedName("GET") + GET("GET"), + @SerializedName("POST") + POST("POST"), + @SerializedName("PUT") + PUT("PUT"), + @SerializedName("PATCH") + PATCH("PATCH"), + @SerializedName("DELETE") + DELETE("DELETE"), + @SerializedName("OPTIONS") + OPTIONS("OPTIONS"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/Flag.kt b/library/src/main/java/io/appwrite/enums/Flag.kt new file mode 100644 index 0000000..e4be0b8 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/Flag.kt @@ -0,0 +1,398 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class Flag(val value: String) { + @SerializedName("af") + AFGHANISTAN("af"), + @SerializedName("ao") + ANGOLA("ao"), + @SerializedName("al") + ALBANIA("al"), + @SerializedName("ad") + ANDORRA("ad"), + @SerializedName("ae") + UNITED_ARAB_EMIRATES("ae"), + @SerializedName("ar") + ARGENTINA("ar"), + @SerializedName("am") + ARMENIA("am"), + @SerializedName("ag") + ANTIGUA_AND_BARBUDA("ag"), + @SerializedName("au") + AUSTRALIA("au"), + @SerializedName("at") + AUSTRIA("at"), + @SerializedName("az") + AZERBAIJAN("az"), + @SerializedName("bi") + BURUNDI("bi"), + @SerializedName("be") + BELGIUM("be"), + @SerializedName("bj") + BENIN("bj"), + @SerializedName("bf") + BURKINA_FASO("bf"), + @SerializedName("bd") + BANGLADESH("bd"), + @SerializedName("bg") + BULGARIA("bg"), + @SerializedName("bh") + BAHRAIN("bh"), + @SerializedName("bs") + BAHAMAS("bs"), + @SerializedName("ba") + BOSNIA_AND_HERZEGOVINA("ba"), + @SerializedName("by") + BELARUS("by"), + @SerializedName("bz") + BELIZE("bz"), + @SerializedName("bo") + BOLIVIA("bo"), + @SerializedName("br") + BRAZIL("br"), + @SerializedName("bb") + BARBADOS("bb"), + @SerializedName("bn") + BRUNEI_DARUSSALAM("bn"), + @SerializedName("bt") + BHUTAN("bt"), + @SerializedName("bw") + BOTSWANA("bw"), + @SerializedName("cf") + CENTRAL_AFRICAN_REPUBLIC("cf"), + @SerializedName("ca") + CANADA("ca"), + @SerializedName("ch") + SWITZERLAND("ch"), + @SerializedName("cl") + CHILE("cl"), + @SerializedName("cn") + CHINA("cn"), + @SerializedName("ci") + COTE_DIVOIRE("ci"), + @SerializedName("cm") + CAMEROON("cm"), + @SerializedName("cd") + DEMOCRATIC_REPUBLIC_OF_THE_CONGO("cd"), + @SerializedName("cg") + REPUBLIC_OF_THE_CONGO("cg"), + @SerializedName("co") + COLOMBIA("co"), + @SerializedName("km") + COMOROS("km"), + @SerializedName("cv") + CAPE_VERDE("cv"), + @SerializedName("cr") + COSTA_RICA("cr"), + @SerializedName("cu") + CUBA("cu"), + @SerializedName("cy") + CYPRUS("cy"), + @SerializedName("cz") + CZECH_REPUBLIC("cz"), + @SerializedName("de") + GERMANY("de"), + @SerializedName("dj") + DJIBOUTI("dj"), + @SerializedName("dm") + DOMINICA("dm"), + @SerializedName("dk") + DENMARK("dk"), + @SerializedName("do") + DOMINICAN_REPUBLIC("do"), + @SerializedName("dz") + ALGERIA("dz"), + @SerializedName("ec") + ECUADOR("ec"), + @SerializedName("eg") + EGYPT("eg"), + @SerializedName("er") + ERITREA("er"), + @SerializedName("es") + SPAIN("es"), + @SerializedName("ee") + ESTONIA("ee"), + @SerializedName("et") + ETHIOPIA("et"), + @SerializedName("fi") + FINLAND("fi"), + @SerializedName("fj") + FIJI("fj"), + @SerializedName("fr") + FRANCE("fr"), + @SerializedName("fm") + MICRONESIA_FEDERATED_STATES_OF("fm"), + @SerializedName("ga") + GABON("ga"), + @SerializedName("gb") + UNITED_KINGDOM("gb"), + @SerializedName("ge") + GEORGIA("ge"), + @SerializedName("gh") + GHANA("gh"), + @SerializedName("gn") + GUINEA("gn"), + @SerializedName("gm") + GAMBIA("gm"), + @SerializedName("gw") + GUINEA_BISSAU("gw"), + @SerializedName("gq") + EQUATORIAL_GUINEA("gq"), + @SerializedName("gr") + GREECE("gr"), + @SerializedName("gd") + GRENADA("gd"), + @SerializedName("gt") + GUATEMALA("gt"), + @SerializedName("gy") + GUYANA("gy"), + @SerializedName("hn") + HONDURAS("hn"), + @SerializedName("hr") + CROATIA("hr"), + @SerializedName("ht") + HAITI("ht"), + @SerializedName("hu") + HUNGARY("hu"), + @SerializedName("id") + INDONESIA("id"), + @SerializedName("in") + INDIA("in"), + @SerializedName("ie") + IRELAND("ie"), + @SerializedName("ir") + IRAN_ISLAMIC_REPUBLIC_OF("ir"), + @SerializedName("iq") + IRAQ("iq"), + @SerializedName("is") + ICELAND("is"), + @SerializedName("il") + ISRAEL("il"), + @SerializedName("it") + ITALY("it"), + @SerializedName("jm") + JAMAICA("jm"), + @SerializedName("jo") + JORDAN("jo"), + @SerializedName("jp") + JAPAN("jp"), + @SerializedName("kz") + KAZAKHSTAN("kz"), + @SerializedName("ke") + KENYA("ke"), + @SerializedName("kg") + KYRGYZSTAN("kg"), + @SerializedName("kh") + CAMBODIA("kh"), + @SerializedName("ki") + KIRIBATI("ki"), + @SerializedName("kn") + SAINT_KITTS_AND_NEVIS("kn"), + @SerializedName("kr") + SOUTH_KOREA("kr"), + @SerializedName("kw") + KUWAIT("kw"), + @SerializedName("la") + LAO_PEOPLES_DEMOCRATIC_REPUBLIC("la"), + @SerializedName("lb") + LEBANON("lb"), + @SerializedName("lr") + LIBERIA("lr"), + @SerializedName("ly") + LIBYA("ly"), + @SerializedName("lc") + SAINT_LUCIA("lc"), + @SerializedName("li") + LIECHTENSTEIN("li"), + @SerializedName("lk") + SRI_LANKA("lk"), + @SerializedName("ls") + LESOTHO("ls"), + @SerializedName("lt") + LITHUANIA("lt"), + @SerializedName("lu") + LUXEMBOURG("lu"), + @SerializedName("lv") + LATVIA("lv"), + @SerializedName("ma") + MOROCCO("ma"), + @SerializedName("mc") + MONACO("mc"), + @SerializedName("md") + MOLDOVA("md"), + @SerializedName("mg") + MADAGASCAR("mg"), + @SerializedName("mv") + MALDIVES("mv"), + @SerializedName("mx") + MEXICO("mx"), + @SerializedName("mh") + MARSHALL_ISLANDS("mh"), + @SerializedName("mk") + NORTH_MACEDONIA("mk"), + @SerializedName("ml") + MALI("ml"), + @SerializedName("mt") + MALTA("mt"), + @SerializedName("mm") + MYANMAR("mm"), + @SerializedName("me") + MONTENEGRO("me"), + @SerializedName("mn") + MONGOLIA("mn"), + @SerializedName("mz") + MOZAMBIQUE("mz"), + @SerializedName("mr") + MAURITANIA("mr"), + @SerializedName("mu") + MAURITIUS("mu"), + @SerializedName("mw") + MALAWI("mw"), + @SerializedName("my") + MALAYSIA("my"), + @SerializedName("na") + NAMIBIA("na"), + @SerializedName("ne") + NIGER("ne"), + @SerializedName("ng") + NIGERIA("ng"), + @SerializedName("ni") + NICARAGUA("ni"), + @SerializedName("nl") + NETHERLANDS("nl"), + @SerializedName("no") + NORWAY("no"), + @SerializedName("np") + NEPAL("np"), + @SerializedName("nr") + NAURU("nr"), + @SerializedName("nz") + NEW_ZEALAND("nz"), + @SerializedName("om") + OMAN("om"), + @SerializedName("pk") + PAKISTAN("pk"), + @SerializedName("pa") + PANAMA("pa"), + @SerializedName("pe") + PERU("pe"), + @SerializedName("ph") + PHILIPPINES("ph"), + @SerializedName("pw") + PALAU("pw"), + @SerializedName("pg") + PAPUA_NEW_GUINEA("pg"), + @SerializedName("pl") + POLAND("pl"), + @SerializedName("pf") + FRENCH_POLYNESIA("pf"), + @SerializedName("kp") + NORTH_KOREA("kp"), + @SerializedName("pt") + PORTUGAL("pt"), + @SerializedName("py") + PARAGUAY("py"), + @SerializedName("qa") + QATAR("qa"), + @SerializedName("ro") + ROMANIA("ro"), + @SerializedName("ru") + RUSSIA("ru"), + @SerializedName("rw") + RWANDA("rw"), + @SerializedName("sa") + SAUDI_ARABIA("sa"), + @SerializedName("sd") + SUDAN("sd"), + @SerializedName("sn") + SENEGAL("sn"), + @SerializedName("sg") + SINGAPORE("sg"), + @SerializedName("sb") + SOLOMON_ISLANDS("sb"), + @SerializedName("sl") + SIERRA_LEONE("sl"), + @SerializedName("sv") + EL_SALVADOR("sv"), + @SerializedName("sm") + SAN_MARINO("sm"), + @SerializedName("so") + SOMALIA("so"), + @SerializedName("rs") + SERBIA("rs"), + @SerializedName("ss") + SOUTH_SUDAN("ss"), + @SerializedName("st") + SAO_TOME_AND_PRINCIPE("st"), + @SerializedName("sr") + SURINAME("sr"), + @SerializedName("sk") + SLOVAKIA("sk"), + @SerializedName("si") + SLOVENIA("si"), + @SerializedName("se") + SWEDEN("se"), + @SerializedName("sz") + ESWATINI("sz"), + @SerializedName("sc") + SEYCHELLES("sc"), + @SerializedName("sy") + SYRIA("sy"), + @SerializedName("td") + CHAD("td"), + @SerializedName("tg") + TOGO("tg"), + @SerializedName("th") + THAILAND("th"), + @SerializedName("tj") + TAJIKISTAN("tj"), + @SerializedName("tm") + TURKMENISTAN("tm"), + @SerializedName("tl") + TIMOR_LESTE("tl"), + @SerializedName("to") + TONGA("to"), + @SerializedName("tt") + TRINIDAD_AND_TOBAGO("tt"), + @SerializedName("tn") + TUNISIA("tn"), + @SerializedName("tr") + TURKEY("tr"), + @SerializedName("tv") + TUVALU("tv"), + @SerializedName("tz") + TANZANIA("tz"), + @SerializedName("ug") + UGANDA("ug"), + @SerializedName("ua") + UKRAINE("ua"), + @SerializedName("uy") + URUGUAY("uy"), + @SerializedName("us") + UNITED_STATES("us"), + @SerializedName("uz") + UZBEKISTAN("uz"), + @SerializedName("va") + VATICAN_CITY("va"), + @SerializedName("vc") + SAINT_VINCENT_AND_THE_GRENADINES("vc"), + @SerializedName("ve") + VENEZUELA("ve"), + @SerializedName("vn") + VIETNAM("vn"), + @SerializedName("vu") + VANUATU("vu"), + @SerializedName("ws") + SAMOA("ws"), + @SerializedName("ye") + YEMEN("ye"), + @SerializedName("za") + SOUTH_AFRICA("za"), + @SerializedName("zm") + ZAMBIA("zm"), + @SerializedName("zw") + ZIMBABWE("zw"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/ImageFormat.kt b/library/src/main/java/io/appwrite/enums/ImageFormat.kt new file mode 100644 index 0000000..8e74806 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/ImageFormat.kt @@ -0,0 +1,22 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class ImageFormat(val value: String) { + @SerializedName("jpg") + JPG("jpg"), + @SerializedName("jpeg") + JPEG("jpeg"), + @SerializedName("png") + PNG("png"), + @SerializedName("webp") + WEBP("webp"), + @SerializedName("heic") + HEIC("heic"), + @SerializedName("avif") + AVIF("avif"), + @SerializedName("gif") + GIF("gif"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/ImageGravity.kt b/library/src/main/java/io/appwrite/enums/ImageGravity.kt new file mode 100644 index 0000000..45f8d88 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/ImageGravity.kt @@ -0,0 +1,26 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class ImageGravity(val value: String) { + @SerializedName("center") + CENTER("center"), + @SerializedName("top-left") + TOP_LEFT("top-left"), + @SerializedName("top") + TOP("top"), + @SerializedName("top-right") + TOP_RIGHT("top-right"), + @SerializedName("left") + LEFT("left"), + @SerializedName("right") + RIGHT("right"), + @SerializedName("bottom-left") + BOTTOM_LEFT("bottom-left"), + @SerializedName("bottom") + BOTTOM("bottom"), + @SerializedName("bottom-right") + BOTTOM_RIGHT("bottom-right"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/enums/OAuthProvider.kt b/library/src/main/java/io/appwrite/enums/OAuthProvider.kt new file mode 100644 index 0000000..b0cff85 --- /dev/null +++ b/library/src/main/java/io/appwrite/enums/OAuthProvider.kt @@ -0,0 +1,88 @@ +package io.appwrite.enums + +import com.google.gson.annotations.SerializedName + +enum class OAuthProvider(val value: String) { + @SerializedName("amazon") + AMAZON("amazon"), + @SerializedName("apple") + APPLE("apple"), + @SerializedName("auth0") + AUTH0("auth0"), + @SerializedName("authentik") + AUTHENTIK("authentik"), + @SerializedName("autodesk") + AUTODESK("autodesk"), + @SerializedName("bitbucket") + BITBUCKET("bitbucket"), + @SerializedName("bitly") + BITLY("bitly"), + @SerializedName("box") + BOX("box"), + @SerializedName("dailymotion") + DAILYMOTION("dailymotion"), + @SerializedName("discord") + DISCORD("discord"), + @SerializedName("disqus") + DISQUS("disqus"), + @SerializedName("dropbox") + DROPBOX("dropbox"), + @SerializedName("etsy") + ETSY("etsy"), + @SerializedName("facebook") + FACEBOOK("facebook"), + @SerializedName("figma") + FIGMA("figma"), + @SerializedName("github") + GITHUB("github"), + @SerializedName("gitlab") + GITLAB("gitlab"), + @SerializedName("google") + GOOGLE("google"), + @SerializedName("linkedin") + LINKEDIN("linkedin"), + @SerializedName("microsoft") + MICROSOFT("microsoft"), + @SerializedName("notion") + NOTION("notion"), + @SerializedName("oidc") + OIDC("oidc"), + @SerializedName("okta") + OKTA("okta"), + @SerializedName("paypal") + PAYPAL("paypal"), + @SerializedName("paypalSandbox") + PAYPALSANDBOX("paypalSandbox"), + @SerializedName("podio") + PODIO("podio"), + @SerializedName("salesforce") + SALESFORCE("salesforce"), + @SerializedName("slack") + SLACK("slack"), + @SerializedName("spotify") + SPOTIFY("spotify"), + @SerializedName("stripe") + STRIPE("stripe"), + @SerializedName("tradeshift") + TRADESHIFT("tradeshift"), + @SerializedName("tradeshiftBox") + TRADESHIFTBOX("tradeshiftBox"), + @SerializedName("twitch") + TWITCH("twitch"), + @SerializedName("wordpress") + WORDPRESS("wordpress"), + @SerializedName("yahoo") + YAHOO("yahoo"), + @SerializedName("yammer") + YAMMER("yammer"), + @SerializedName("yandex") + YANDEX("yandex"), + @SerializedName("zoho") + ZOHO("zoho"), + @SerializedName("zoom") + ZOOM("zoom"), + @SerializedName("mock") + MOCK("mock"); + + override fun toString() = value +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/exceptions/AppwriteException.kt b/library/src/main/java/io/appwrite/exceptions/AppwriteException.kt index d7d4fbc..105f5ee 100644 --- a/library/src/main/java/io/appwrite/exceptions/AppwriteException.kt +++ b/library/src/main/java/io/appwrite/exceptions/AppwriteException.kt @@ -3,7 +3,8 @@ package io.appwrite.exceptions import java.lang.Exception class AppwriteException( - message: String? = null, + override val message: String? = null, val code: Int? = null, + val type: String? = null, val response: String? = null ) : Exception(message) \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/extensions/JsonExtensions.kt b/library/src/main/java/io/appwrite/extensions/JsonExtensions.kt index 444a77d..06d9940 100644 --- a/library/src/main/java/io/appwrite/extensions/JsonExtensions.kt +++ b/library/src/main/java/io/appwrite/extensions/JsonExtensions.kt @@ -1,8 +1,14 @@ package io.appwrite.extensions import com.google.gson.Gson - -val gson = Gson() +import com.google.gson.GsonBuilder +import com.google.gson.ToNumberPolicy +import com.google.gson.reflect.TypeToken + +val gson: Gson = GsonBuilder() + .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) + .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) + .create() fun Any.toJson(): String = gson.toJson(this) diff --git a/library/src/main/java/io/appwrite/extensions/TypeExtensions.kt b/library/src/main/java/io/appwrite/extensions/TypeExtensions.kt new file mode 100644 index 0000000..e699a54 --- /dev/null +++ b/library/src/main/java/io/appwrite/extensions/TypeExtensions.kt @@ -0,0 +1,9 @@ +package io.appwrite.extensions + +import kotlin.reflect.KClass +import kotlin.reflect.typeOf + +inline fun classOf(): Class { + @Suppress("UNCHECKED_CAST") + return (typeOf().classifier!! as KClass).java +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoArgon2.kt b/library/src/main/java/io/appwrite/models/AlgoArgon2.kt new file mode 100644 index 0000000..6230248 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoArgon2.kt @@ -0,0 +1,54 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoArgon2 + */ +data class AlgoArgon2( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + + /** + * Memory used to compute hash. + */ + @SerializedName("memoryCost") + val memoryCost: Long, + + /** + * Amount of time consumed to compute hash + */ + @SerializedName("timeCost") + val timeCost: Long, + + /** + * Number of threads used to compute hash. + */ + @SerializedName("threads") + val threads: Long, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + "memoryCost" to memoryCost as Any, + "timeCost" to timeCost as Any, + "threads" to threads as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoArgon2( + type = map["type"] as String, + memoryCost = (map["memoryCost"] as Number).toLong(), + timeCost = (map["timeCost"] as Number).toLong(), + threads = (map["threads"] as Number).toLong(), + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoBcrypt.kt b/library/src/main/java/io/appwrite/models/AlgoBcrypt.kt new file mode 100644 index 0000000..24e74b8 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoBcrypt.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoBcrypt + */ +data class AlgoBcrypt( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoBcrypt( + type = map["type"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoMd5.kt b/library/src/main/java/io/appwrite/models/AlgoMd5.kt new file mode 100644 index 0000000..71baf51 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoMd5.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoMD5 + */ +data class AlgoMd5( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoMd5( + type = map["type"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoPhpass.kt b/library/src/main/java/io/appwrite/models/AlgoPhpass.kt new file mode 100644 index 0000000..d89b8cf --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoPhpass.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoPHPass + */ +data class AlgoPhpass( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoPhpass( + type = map["type"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoScrypt.kt b/library/src/main/java/io/appwrite/models/AlgoScrypt.kt new file mode 100644 index 0000000..2e4ae1e --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoScrypt.kt @@ -0,0 +1,62 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoScrypt + */ +data class AlgoScrypt( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + + /** + * CPU complexity of computed hash. + */ + @SerializedName("costCpu") + val costCpu: Long, + + /** + * Memory complexity of computed hash. + */ + @SerializedName("costMemory") + val costMemory: Long, + + /** + * Parallelization of computed hash. + */ + @SerializedName("costParallel") + val costParallel: Long, + + /** + * Length used to compute hash. + */ + @SerializedName("length") + val length: Long, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + "costCpu" to costCpu as Any, + "costMemory" to costMemory as Any, + "costParallel" to costParallel as Any, + "length" to length as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoScrypt( + type = map["type"] as String, + costCpu = (map["costCpu"] as Number).toLong(), + costMemory = (map["costMemory"] as Number).toLong(), + costParallel = (map["costParallel"] as Number).toLong(), + length = (map["length"] as Number).toLong(), + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoScryptModified.kt b/library/src/main/java/io/appwrite/models/AlgoScryptModified.kt new file mode 100644 index 0000000..3807d6d --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoScryptModified.kt @@ -0,0 +1,54 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoScryptModified + */ +data class AlgoScryptModified( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + + /** + * Salt used to compute hash. + */ + @SerializedName("salt") + val salt: String, + + /** + * Separator used to compute hash. + */ + @SerializedName("saltSeparator") + val saltSeparator: String, + + /** + * Key used to compute hash. + */ + @SerializedName("signerKey") + val signerKey: String, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + "salt" to salt as Any, + "saltSeparator" to saltSeparator as Any, + "signerKey" to signerKey as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoScryptModified( + type = map["type"] as String, + salt = map["salt"] as String, + saltSeparator = map["saltSeparator"] as String, + signerKey = map["signerKey"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/AlgoSha.kt b/library/src/main/java/io/appwrite/models/AlgoSha.kt new file mode 100644 index 0000000..4209a0e --- /dev/null +++ b/library/src/main/java/io/appwrite/models/AlgoSha.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * AlgoSHA + */ +data class AlgoSha( + /** + * Algo type. + */ + @SerializedName("type") + val type: String, + +) { + fun toMap(): Map = mapOf( + "type" to type as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = AlgoSha( + type = map["type"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Continent.kt b/library/src/main/java/io/appwrite/models/Continent.kt new file mode 100644 index 0000000..818c15b --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Continent.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Continent + */ +data class Continent( + /** + * Continent name. + */ + @SerializedName("name") + val name: String, + + /** + * Continent two letter code. + */ + @SerializedName("code") + val code: String, + +) { + fun toMap(): Map = mapOf( + "name" to name as Any, + "code" to code as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Continent( + name = map["name"] as String, + code = map["code"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/ContinentList.kt b/library/src/main/java/io/appwrite/models/ContinentList.kt new file mode 100644 index 0000000..789acff --- /dev/null +++ b/library/src/main/java/io/appwrite/models/ContinentList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Continents List + */ +data class ContinentList( + /** + * Total number of continents that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of continents. + */ + @SerializedName("continents") + val continents: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "continents" to continents.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = ContinentList( + total = (map["total"] as Number).toLong(), + continents = (map["continents"] as List>).map { Continent.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Country.kt b/library/src/main/java/io/appwrite/models/Country.kt new file mode 100644 index 0000000..92ab89a --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Country.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Country + */ +data class Country( + /** + * Country name. + */ + @SerializedName("name") + val name: String, + + /** + * Country two-character ISO 3166-1 alpha code. + */ + @SerializedName("code") + val code: String, + +) { + fun toMap(): Map = mapOf( + "name" to name as Any, + "code" to code as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Country( + name = map["name"] as String, + code = map["code"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/CountryList.kt b/library/src/main/java/io/appwrite/models/CountryList.kt new file mode 100644 index 0000000..47c0e72 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/CountryList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Countries List + */ +data class CountryList( + /** + * Total number of countries that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of countries. + */ + @SerializedName("countries") + val countries: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "countries" to countries.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = CountryList( + total = (map["total"] as Number).toLong(), + countries = (map["countries"] as List>).map { Country.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Currency.kt b/library/src/main/java/io/appwrite/models/Currency.kt new file mode 100644 index 0000000..96b65d0 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Currency.kt @@ -0,0 +1,78 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Currency + */ +data class Currency( + /** + * Currency symbol. + */ + @SerializedName("symbol") + val symbol: String, + + /** + * Currency name. + */ + @SerializedName("name") + val name: String, + + /** + * Currency native symbol. + */ + @SerializedName("symbolNative") + val symbolNative: String, + + /** + * Number of decimal digits. + */ + @SerializedName("decimalDigits") + val decimalDigits: Long, + + /** + * Currency digit rounding. + */ + @SerializedName("rounding") + val rounding: Double, + + /** + * Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + */ + @SerializedName("code") + val code: String, + + /** + * Currency plural name + */ + @SerializedName("namePlural") + val namePlural: String, + +) { + fun toMap(): Map = mapOf( + "symbol" to symbol as Any, + "name" to name as Any, + "symbolNative" to symbolNative as Any, + "decimalDigits" to decimalDigits as Any, + "rounding" to rounding as Any, + "code" to code as Any, + "namePlural" to namePlural as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Currency( + symbol = map["symbol"] as String, + name = map["name"] as String, + symbolNative = map["symbolNative"] as String, + decimalDigits = (map["decimalDigits"] as Number).toLong(), + rounding = (map["rounding"] as Number).toDouble(), + code = map["code"] as String, + namePlural = map["namePlural"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/CurrencyList.kt b/library/src/main/java/io/appwrite/models/CurrencyList.kt new file mode 100644 index 0000000..5a57a02 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/CurrencyList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Currencies List + */ +data class CurrencyList( + /** + * Total number of currencies that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of currencies. + */ + @SerializedName("currencies") + val currencies: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "currencies" to currencies.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = CurrencyList( + total = (map["total"] as Number).toLong(), + currencies = (map["currencies"] as List>).map { Currency.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Document.kt b/library/src/main/java/io/appwrite/models/Document.kt new file mode 100644 index 0000000..c0dfe61 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Document.kt @@ -0,0 +1,105 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Document + */ +data class Document( + /** + * Document ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Document automatically incrementing ID. + */ + @SerializedName("\$sequence") + val sequence: Long, + + /** + * Collection ID. + */ + @SerializedName("\$collectionId") + val collectionId: String, + + /** + * Database ID. + */ + @SerializedName("\$databaseId") + val databaseId: String, + + /** + * Document creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Document update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + */ + @SerializedName("\$permissions") + val permissions: List, + + /** + * Additional properties + */ + @SerializedName("data") + val data: T +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$sequence" to sequence as Any, + "\$collectionId" to collectionId as Any, + "\$databaseId" to databaseId as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "\$permissions" to permissions as Any, + "data" to data!!.jsonCast(to = Map::class.java) + ) + + companion object { + operator fun invoke( + id: String, + sequence: Long, + collectionId: String, + databaseId: String, + createdAt: String, + updatedAt: String, + permissions: List, + data: Map + ) = Document>( + id, + sequence, + collectionId, + databaseId, + createdAt, + updatedAt, + permissions, + data + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = Document( + id = map["\$id"] as String, + sequence = (map["\$sequence"] as Number).toLong(), + collectionId = map["\$collectionId"] as String, + databaseId = map["\$databaseId"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + permissions = map["\$permissions"] as List, + data = map.jsonCast(to = nestedType) + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/DocumentList.kt b/library/src/main/java/io/appwrite/models/DocumentList.kt new file mode 100644 index 0000000..c26cd26 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/DocumentList.kt @@ -0,0 +1,46 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Documents List + */ +data class DocumentList( + /** + * Total number of documents that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of documents. + */ + @SerializedName("documents") + val documents: List>, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "documents" to documents.map { it.toMap() } as Any, + ) + + companion object { + operator fun invoke( + total: Long, + documents: List>>, + ) = DocumentList>( + total, + documents, + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = DocumentList( + total = (map["total"] as Number).toLong(), + documents = (map["documents"] as List>).map { Document.from(map = it, nestedType) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Execution.kt b/library/src/main/java/io/appwrite/models/Execution.kt new file mode 100644 index 0000000..8b395c6 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Execution.kt @@ -0,0 +1,166 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Execution + */ +data class Execution( + /** + * Execution ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Execution creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Execution update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Execution roles. + */ + @SerializedName("\$permissions") + val permissions: List, + + /** + * Function ID. + */ + @SerializedName("functionId") + val functionId: String, + + /** + * Function's deployment ID used to create the execution. + */ + @SerializedName("deploymentId") + val deploymentId: String, + + /** + * The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + */ + @SerializedName("trigger") + val trigger: String, + + /** + * The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + */ + @SerializedName("status") + val status: String, + + /** + * HTTP request method type. + */ + @SerializedName("requestMethod") + val requestMethod: String, + + /** + * HTTP request path and query. + */ + @SerializedName("requestPath") + val requestPath: String, + + /** + * HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + */ + @SerializedName("requestHeaders") + val requestHeaders: List, + + /** + * HTTP response status code. + */ + @SerializedName("responseStatusCode") + val responseStatusCode: Long, + + /** + * HTTP response body. This will return empty unless execution is created as synchronous. + */ + @SerializedName("responseBody") + val responseBody: String, + + /** + * HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + */ + @SerializedName("responseHeaders") + val responseHeaders: List, + + /** + * 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. + */ + @SerializedName("logs") + val logs: String, + + /** + * 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. + */ + @SerializedName("errors") + val errors: String, + + /** + * Resource(function/site) execution duration in seconds. + */ + @SerializedName("duration") + val duration: Double, + + /** + * The scheduled time for execution. If left empty, execution will be queued immediately. + */ + @SerializedName("scheduledAt") + var scheduledAt: String?, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "\$permissions" to permissions as Any, + "functionId" to functionId as Any, + "deploymentId" to deploymentId as Any, + "trigger" to trigger as Any, + "status" to status as Any, + "requestMethod" to requestMethod as Any, + "requestPath" to requestPath as Any, + "requestHeaders" to requestHeaders.map { it.toMap() } as Any, + "responseStatusCode" to responseStatusCode as Any, + "responseBody" to responseBody as Any, + "responseHeaders" to responseHeaders.map { it.toMap() } as Any, + "logs" to logs as Any, + "errors" to errors as Any, + "duration" to duration as Any, + "scheduledAt" to scheduledAt as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Execution( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + permissions = map["\$permissions"] as List, + functionId = map["functionId"] as String, + deploymentId = map["deploymentId"] as String, + trigger = map["trigger"] as String, + status = map["status"] as String, + requestMethod = map["requestMethod"] as String, + requestPath = map["requestPath"] as String, + requestHeaders = (map["requestHeaders"] as List>).map { Headers.from(map = it) }, + responseStatusCode = (map["responseStatusCode"] as Number).toLong(), + responseBody = map["responseBody"] as String, + responseHeaders = (map["responseHeaders"] as List>).map { Headers.from(map = it) }, + logs = map["logs"] as String, + errors = map["errors"] as String, + duration = (map["duration"] as Number).toDouble(), + scheduledAt = map["scheduledAt"] as? String?, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/ExecutionList.kt b/library/src/main/java/io/appwrite/models/ExecutionList.kt new file mode 100644 index 0000000..a976e78 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/ExecutionList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Executions List + */ +data class ExecutionList( + /** + * Total number of executions that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of executions. + */ + @SerializedName("executions") + val executions: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "executions" to executions.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = ExecutionList( + total = (map["total"] as Number).toLong(), + executions = (map["executions"] as List>).map { Execution.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/File.kt b/library/src/main/java/io/appwrite/models/File.kt new file mode 100644 index 0000000..897fc4a --- /dev/null +++ b/library/src/main/java/io/appwrite/models/File.kt @@ -0,0 +1,110 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * File + */ +data class File( + /** + * File ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Bucket ID. + */ + @SerializedName("bucketId") + val bucketId: String, + + /** + * File creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * File update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + */ + @SerializedName("\$permissions") + val permissions: List, + + /** + * File name. + */ + @SerializedName("name") + val name: String, + + /** + * File MD5 signature. + */ + @SerializedName("signature") + val signature: String, + + /** + * File mime type. + */ + @SerializedName("mimeType") + val mimeType: String, + + /** + * File original size in bytes. + */ + @SerializedName("sizeOriginal") + val sizeOriginal: Long, + + /** + * Total number of chunks available + */ + @SerializedName("chunksTotal") + val chunksTotal: Long, + + /** + * Total number of chunks uploaded + */ + @SerializedName("chunksUploaded") + val chunksUploaded: Long, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "bucketId" to bucketId as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "\$permissions" to permissions as Any, + "name" to name as Any, + "signature" to signature as Any, + "mimeType" to mimeType as Any, + "sizeOriginal" to sizeOriginal as Any, + "chunksTotal" to chunksTotal as Any, + "chunksUploaded" to chunksUploaded as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = File( + id = map["\$id"] as String, + bucketId = map["bucketId"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + permissions = map["\$permissions"] as List, + name = map["name"] as String, + signature = map["signature"] as String, + mimeType = map["mimeType"] as String, + sizeOriginal = (map["sizeOriginal"] as Number).toLong(), + chunksTotal = (map["chunksTotal"] as Number).toLong(), + chunksUploaded = (map["chunksUploaded"] as Number).toLong(), + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/FileList.kt b/library/src/main/java/io/appwrite/models/FileList.kt new file mode 100644 index 0000000..dfdd212 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/FileList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Files List + */ +data class FileList( + /** + * Total number of files that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of files. + */ + @SerializedName("files") + val files: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "files" to files.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = FileList( + total = (map["total"] as Number).toLong(), + files = (map["files"] as List>).map { File.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Headers.kt b/library/src/main/java/io/appwrite/models/Headers.kt new file mode 100644 index 0000000..230d6a6 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Headers.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Headers + */ +data class Headers( + /** + * Header name. + */ + @SerializedName("name") + val name: String, + + /** + * Header value. + */ + @SerializedName("value") + val value: String, + +) { + fun toMap(): Map = mapOf( + "name" to name as Any, + "value" to value as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Headers( + name = map["name"] as String, + value = map["value"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Identity.kt b/library/src/main/java/io/appwrite/models/Identity.kt new file mode 100644 index 0000000..70ff5ea --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Identity.kt @@ -0,0 +1,102 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Identity + */ +data class Identity( + /** + * Identity ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Identity creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Identity update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * Identity Provider. + */ + @SerializedName("provider") + val provider: String, + + /** + * ID of the User in the Identity Provider. + */ + @SerializedName("providerUid") + val providerUid: String, + + /** + * Email of the User in the Identity Provider. + */ + @SerializedName("providerEmail") + val providerEmail: String, + + /** + * Identity Provider Access Token. + */ + @SerializedName("providerAccessToken") + val providerAccessToken: String, + + /** + * The date of when the access token expires in ISO 8601 format. + */ + @SerializedName("providerAccessTokenExpiry") + val providerAccessTokenExpiry: String, + + /** + * Identity Provider Refresh Token. + */ + @SerializedName("providerRefreshToken") + val providerRefreshToken: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "userId" to userId as Any, + "provider" to provider as Any, + "providerUid" to providerUid as Any, + "providerEmail" to providerEmail as Any, + "providerAccessToken" to providerAccessToken as Any, + "providerAccessTokenExpiry" to providerAccessTokenExpiry as Any, + "providerRefreshToken" to providerRefreshToken as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Identity( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + userId = map["userId"] as String, + provider = map["provider"] as String, + providerUid = map["providerUid"] as String, + providerEmail = map["providerEmail"] as String, + providerAccessToken = map["providerAccessToken"] as String, + providerAccessTokenExpiry = map["providerAccessTokenExpiry"] as String, + providerRefreshToken = map["providerRefreshToken"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/IdentityList.kt b/library/src/main/java/io/appwrite/models/IdentityList.kt new file mode 100644 index 0000000..49c3346 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/IdentityList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Identities List + */ +data class IdentityList( + /** + * Total number of identities that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of identities. + */ + @SerializedName("identities") + val identities: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "identities" to identities.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = IdentityList( + total = (map["total"] as Number).toLong(), + identities = (map["identities"] as List>).map { Identity.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/InputFile.kt b/library/src/main/java/io/appwrite/models/InputFile.kt new file mode 100644 index 0000000..afbb2e9 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/InputFile.kt @@ -0,0 +1,37 @@ +package io.appwrite.models + +import java.io.File +import java.net.URLConnection +import java.nio.file.Files +import java.nio.file.Paths + +class InputFile private constructor() { + + lateinit var path: String + lateinit var filename: String + lateinit var mimeType: String + lateinit var sourceType: String + lateinit var data: Any + + companion object { + fun fromFile(file: File) = InputFile().apply { + path = file.canonicalPath + filename = file.name + mimeType = Files.probeContentType(Paths.get(file.canonicalPath)) + ?: URLConnection.guessContentTypeFromName(filename) + ?: "" + sourceType = "file" + } + + fun fromPath(path: String): InputFile = fromFile(File(path)).apply { + sourceType = "path" + } + + fun fromBytes(bytes: ByteArray, filename: String = "", mimeType: String = "") = InputFile().apply { + this.filename = filename + this.mimeType = mimeType + data = bytes + sourceType = "bytes" + } + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Jwt.kt b/library/src/main/java/io/appwrite/models/Jwt.kt new file mode 100644 index 0000000..f55c103 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Jwt.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * JWT + */ +data class Jwt( + /** + * JWT encoded string. + */ + @SerializedName("jwt") + val jwt: String, + +) { + fun toMap(): Map = mapOf( + "jwt" to jwt as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Jwt( + jwt = map["jwt"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Language.kt b/library/src/main/java/io/appwrite/models/Language.kt new file mode 100644 index 0000000..8860aad --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Language.kt @@ -0,0 +1,46 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Language + */ +data class Language( + /** + * Language name. + */ + @SerializedName("name") + val name: String, + + /** + * Language two-character ISO 639-1 codes. + */ + @SerializedName("code") + val code: String, + + /** + * Language native name. + */ + @SerializedName("nativeName") + val nativeName: String, + +) { + fun toMap(): Map = mapOf( + "name" to name as Any, + "code" to code as Any, + "nativeName" to nativeName as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Language( + name = map["name"] as String, + code = map["code"] as String, + nativeName = map["nativeName"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/LanguageList.kt b/library/src/main/java/io/appwrite/models/LanguageList.kt new file mode 100644 index 0000000..1aac2f7 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/LanguageList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Languages List + */ +data class LanguageList( + /** + * Total number of languages that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of languages. + */ + @SerializedName("languages") + val languages: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "languages" to languages.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = LanguageList( + total = (map["total"] as Number).toLong(), + languages = (map["languages"] as List>).map { Language.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Locale.kt b/library/src/main/java/io/appwrite/models/Locale.kt new file mode 100644 index 0000000..93d28d4 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Locale.kt @@ -0,0 +1,78 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Locale + */ +data class Locale( + /** + * User IP address. + */ + @SerializedName("ip") + val ip: String, + + /** + * Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + */ + @SerializedName("countryCode") + val countryCode: String, + + /** + * Country name. This field support localization. + */ + @SerializedName("country") + val country: String, + + /** + * 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. + */ + @SerializedName("continentCode") + val continentCode: String, + + /** + * Continent name. This field support localization. + */ + @SerializedName("continent") + val continent: String, + + /** + * True if country is part of the European Union. + */ + @SerializedName("eu") + val eu: Boolean, + + /** + * Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + */ + @SerializedName("currency") + val currency: String, + +) { + fun toMap(): Map = mapOf( + "ip" to ip as Any, + "countryCode" to countryCode as Any, + "country" to country as Any, + "continentCode" to continentCode as Any, + "continent" to continent as Any, + "eu" to eu as Any, + "currency" to currency as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Locale( + ip = map["ip"] as String, + countryCode = map["countryCode"] as String, + country = map["country"] as String, + continentCode = map["continentCode"] as String, + continent = map["continent"] as String, + eu = map["eu"] as Boolean, + currency = map["currency"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/LocaleCode.kt b/library/src/main/java/io/appwrite/models/LocaleCode.kt new file mode 100644 index 0000000..ed886b7 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/LocaleCode.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * LocaleCode + */ +data class LocaleCode( + /** + * Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + */ + @SerializedName("code") + val code: String, + + /** + * Locale name + */ + @SerializedName("name") + val name: String, + +) { + fun toMap(): Map = mapOf( + "code" to code as Any, + "name" to name as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = LocaleCode( + code = map["code"] as String, + name = map["name"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/LocaleCodeList.kt b/library/src/main/java/io/appwrite/models/LocaleCodeList.kt new file mode 100644 index 0000000..7949b57 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/LocaleCodeList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Locale codes list + */ +data class LocaleCodeList( + /** + * Total number of localeCodes that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of localeCodes. + */ + @SerializedName("localeCodes") + val localeCodes: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "localeCodes" to localeCodes.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = LocaleCodeList( + total = (map["total"] as Number).toLong(), + localeCodes = (map["localeCodes"] as List>).map { LocaleCode.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Log.kt b/library/src/main/java/io/appwrite/models/Log.kt new file mode 100644 index 0000000..c2df960 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Log.kt @@ -0,0 +1,190 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Log + */ +data class Log( + /** + * Event name. + */ + @SerializedName("event") + val event: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * User Email. + */ + @SerializedName("userEmail") + val userEmail: String, + + /** + * User Name. + */ + @SerializedName("userName") + val userName: String, + + /** + * API mode when event triggered. + */ + @SerializedName("mode") + val mode: String, + + /** + * IP session in use when the session was created. + */ + @SerializedName("ip") + val ip: String, + + /** + * Log creation date in ISO 8601 format. + */ + @SerializedName("time") + val time: String, + + /** + * Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + */ + @SerializedName("osCode") + val osCode: String, + + /** + * Operating system name. + */ + @SerializedName("osName") + val osName: String, + + /** + * Operating system version. + */ + @SerializedName("osVersion") + val osVersion: String, + + /** + * Client type. + */ + @SerializedName("clientType") + val clientType: String, + + /** + * Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + */ + @SerializedName("clientCode") + val clientCode: String, + + /** + * Client name. + */ + @SerializedName("clientName") + val clientName: String, + + /** + * Client version. + */ + @SerializedName("clientVersion") + val clientVersion: String, + + /** + * Client engine name. + */ + @SerializedName("clientEngine") + val clientEngine: String, + + /** + * Client engine name. + */ + @SerializedName("clientEngineVersion") + val clientEngineVersion: String, + + /** + * Device name. + */ + @SerializedName("deviceName") + val deviceName: String, + + /** + * Device brand name. + */ + @SerializedName("deviceBrand") + val deviceBrand: String, + + /** + * Device model name. + */ + @SerializedName("deviceModel") + val deviceModel: String, + + /** + * Country two-character ISO 3166-1 alpha code. + */ + @SerializedName("countryCode") + val countryCode: String, + + /** + * Country name. + */ + @SerializedName("countryName") + val countryName: String, + +) { + fun toMap(): Map = mapOf( + "event" to event as Any, + "userId" to userId as Any, + "userEmail" to userEmail as Any, + "userName" to userName as Any, + "mode" to mode as Any, + "ip" to ip as Any, + "time" to time as Any, + "osCode" to osCode as Any, + "osName" to osName as Any, + "osVersion" to osVersion as Any, + "clientType" to clientType as Any, + "clientCode" to clientCode as Any, + "clientName" to clientName as Any, + "clientVersion" to clientVersion as Any, + "clientEngine" to clientEngine as Any, + "clientEngineVersion" to clientEngineVersion as Any, + "deviceName" to deviceName as Any, + "deviceBrand" to deviceBrand as Any, + "deviceModel" to deviceModel as Any, + "countryCode" to countryCode as Any, + "countryName" to countryName as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Log( + event = map["event"] as String, + userId = map["userId"] as String, + userEmail = map["userEmail"] as String, + userName = map["userName"] as String, + mode = map["mode"] as String, + ip = map["ip"] as String, + time = map["time"] as String, + osCode = map["osCode"] as String, + osName = map["osName"] as String, + osVersion = map["osVersion"] as String, + clientType = map["clientType"] as String, + clientCode = map["clientCode"] as String, + clientName = map["clientName"] as String, + clientVersion = map["clientVersion"] as String, + clientEngine = map["clientEngine"] as String, + clientEngineVersion = map["clientEngineVersion"] as String, + deviceName = map["deviceName"] as String, + deviceBrand = map["deviceBrand"] as String, + deviceModel = map["deviceModel"] as String, + countryCode = map["countryCode"] as String, + countryName = map["countryName"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/LogList.kt b/library/src/main/java/io/appwrite/models/LogList.kt new file mode 100644 index 0000000..c88451c --- /dev/null +++ b/library/src/main/java/io/appwrite/models/LogList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Logs List + */ +data class LogList( + /** + * Total number of logs that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of logs. + */ + @SerializedName("logs") + val logs: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "logs" to logs.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = LogList( + total = (map["total"] as Number).toLong(), + logs = (map["logs"] as List>).map { Log.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Membership.kt b/library/src/main/java/io/appwrite/models/Membership.kt new file mode 100644 index 0000000..4a899ee --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Membership.kt @@ -0,0 +1,126 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Membership + */ +data class Membership( + /** + * Membership ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Membership creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Membership update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * User name. Hide this attribute by toggling membership privacy in the Console. + */ + @SerializedName("userName") + val userName: String, + + /** + * User email address. Hide this attribute by toggling membership privacy in the Console. + */ + @SerializedName("userEmail") + val userEmail: String, + + /** + * Team ID. + */ + @SerializedName("teamId") + val teamId: String, + + /** + * Team name. + */ + @SerializedName("teamName") + val teamName: String, + + /** + * Date, the user has been invited to join the team in ISO 8601 format. + */ + @SerializedName("invited") + val invited: String, + + /** + * Date, the user has accepted the invitation to join the team in ISO 8601 format. + */ + @SerializedName("joined") + val joined: String, + + /** + * User confirmation status, true if the user has joined the team or false otherwise. + */ + @SerializedName("confirm") + val confirm: Boolean, + + /** + * Multi factor authentication status, true if the user has MFA enabled or false otherwise. Hide this attribute by toggling membership privacy in the Console. + */ + @SerializedName("mfa") + val mfa: Boolean, + + /** + * User list of roles + */ + @SerializedName("roles") + val roles: List, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "userId" to userId as Any, + "userName" to userName as Any, + "userEmail" to userEmail as Any, + "teamId" to teamId as Any, + "teamName" to teamName as Any, + "invited" to invited as Any, + "joined" to joined as Any, + "confirm" to confirm as Any, + "mfa" to mfa as Any, + "roles" to roles as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Membership( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + userId = map["userId"] as String, + userName = map["userName"] as String, + userEmail = map["userEmail"] as String, + teamId = map["teamId"] as String, + teamName = map["teamName"] as String, + invited = map["invited"] as String, + joined = map["joined"] as String, + confirm = map["confirm"] as Boolean, + mfa = map["mfa"] as Boolean, + roles = map["roles"] as List, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/MembershipList.kt b/library/src/main/java/io/appwrite/models/MembershipList.kt new file mode 100644 index 0000000..b2bea4e --- /dev/null +++ b/library/src/main/java/io/appwrite/models/MembershipList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Memberships List + */ +data class MembershipList( + /** + * Total number of memberships that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of memberships. + */ + @SerializedName("memberships") + val memberships: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "memberships" to memberships.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = MembershipList( + total = (map["total"] as Number).toLong(), + memberships = (map["memberships"] as List>).map { Membership.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/MfaChallenge.kt b/library/src/main/java/io/appwrite/models/MfaChallenge.kt new file mode 100644 index 0000000..82b1d18 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/MfaChallenge.kt @@ -0,0 +1,54 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * MFA Challenge + */ +data class MfaChallenge( + /** + * Token ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Token creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * Token expiration date in ISO 8601 format. + */ + @SerializedName("expire") + val expire: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "userId" to userId as Any, + "expire" to expire as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = MfaChallenge( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + userId = map["userId"] as String, + expire = map["expire"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/MfaFactors.kt b/library/src/main/java/io/appwrite/models/MfaFactors.kt new file mode 100644 index 0000000..ddde40c --- /dev/null +++ b/library/src/main/java/io/appwrite/models/MfaFactors.kt @@ -0,0 +1,54 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * MFAFactors + */ +data class MfaFactors( + /** + * Can TOTP be used for MFA challenge for this account. + */ + @SerializedName("totp") + val totp: Boolean, + + /** + * Can phone (SMS) be used for MFA challenge for this account. + */ + @SerializedName("phone") + val phone: Boolean, + + /** + * Can email be used for MFA challenge for this account. + */ + @SerializedName("email") + val email: Boolean, + + /** + * Can recovery code be used for MFA challenge for this account. + */ + @SerializedName("recoveryCode") + val recoveryCode: Boolean, + +) { + fun toMap(): Map = mapOf( + "totp" to totp as Any, + "phone" to phone as Any, + "email" to email as Any, + "recoveryCode" to recoveryCode as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = MfaFactors( + totp = map["totp"] as Boolean, + phone = map["phone"] as Boolean, + email = map["email"] as Boolean, + recoveryCode = map["recoveryCode"] as Boolean, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/MfaRecoveryCodes.kt b/library/src/main/java/io/appwrite/models/MfaRecoveryCodes.kt new file mode 100644 index 0000000..3fab41a --- /dev/null +++ b/library/src/main/java/io/appwrite/models/MfaRecoveryCodes.kt @@ -0,0 +1,30 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * MFA Recovery Codes + */ +data class MfaRecoveryCodes( + /** + * Recovery codes. + */ + @SerializedName("recoveryCodes") + val recoveryCodes: List, + +) { + fun toMap(): Map = mapOf( + "recoveryCodes" to recoveryCodes as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = MfaRecoveryCodes( + recoveryCodes = map["recoveryCodes"] as List, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/MfaType.kt b/library/src/main/java/io/appwrite/models/MfaType.kt new file mode 100644 index 0000000..9c784a9 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/MfaType.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * MFAType + */ +data class MfaType( + /** + * Secret token used for TOTP factor. + */ + @SerializedName("secret") + val secret: String, + + /** + * URI for authenticator apps. + */ + @SerializedName("uri") + val uri: String, + +) { + fun toMap(): Map = mapOf( + "secret" to secret as Any, + "uri" to uri as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = MfaType( + secret = map["secret"] as String, + uri = map["uri"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Phone.kt b/library/src/main/java/io/appwrite/models/Phone.kt new file mode 100644 index 0000000..28aea2d --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Phone.kt @@ -0,0 +1,46 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Phone + */ +data class Phone( + /** + * Phone code. + */ + @SerializedName("code") + val code: String, + + /** + * Country two-character ISO 3166-1 alpha code. + */ + @SerializedName("countryCode") + val countryCode: String, + + /** + * Country name. + */ + @SerializedName("countryName") + val countryName: String, + +) { + fun toMap(): Map = mapOf( + "code" to code as Any, + "countryCode" to countryCode as Any, + "countryName" to countryName as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Phone( + code = map["code"] as String, + countryCode = map["countryCode"] as String, + countryName = map["countryName"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/PhoneList.kt b/library/src/main/java/io/appwrite/models/PhoneList.kt new file mode 100644 index 0000000..5f7c22f --- /dev/null +++ b/library/src/main/java/io/appwrite/models/PhoneList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Phones List + */ +data class PhoneList( + /** + * Total number of phones that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of phones. + */ + @SerializedName("phones") + val phones: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "phones" to phones.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = PhoneList( + total = (map["total"] as Number).toLong(), + phones = (map["phones"] as List>).map { Phone.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Preferences.kt b/library/src/main/java/io/appwrite/models/Preferences.kt new file mode 100644 index 0000000..309fb98 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Preferences.kt @@ -0,0 +1,35 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Preferences + */ +data class Preferences( + /** + * Additional properties + */ + @SerializedName("data") + val data: T +) { + fun toMap(): Map = mapOf( + "data" to data!!.jsonCast(to = Map::class.java) + ) + + companion object { + operator fun invoke( + data: Map + ) = Preferences>( + data + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = Preferences( + data = map.jsonCast(to = nestedType) + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/RealtimeModels.kt b/library/src/main/java/io/appwrite/models/RealtimeModels.kt index b4990c8..cc1af63 100644 --- a/library/src/main/java/io/appwrite/models/RealtimeModels.kt +++ b/library/src/main/java/io/appwrite/models/RealtimeModels.kt @@ -1,5 +1,6 @@ package io.appwrite.models +import kotlin.collections.Collection import java.io.Closeable data class RealtimeSubscription( @@ -9,19 +10,20 @@ data class RealtimeSubscription( } data class RealtimeCallback( + val channels: Collection, val payloadClass: Class<*>, val callback: (RealtimeResponseEvent<*>) -> Unit ) open class RealtimeResponse( val type: String, - val data: Any + val data: Any? ) data class RealtimeResponseEvent( - val event: String, + val events: Collection, val channels: Collection, - val timestamp: Long, + val timestamp: String, var payload: T ) diff --git a/library/src/main/java/io/appwrite/models/Row.kt b/library/src/main/java/io/appwrite/models/Row.kt new file mode 100644 index 0000000..bb5c14f --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Row.kt @@ -0,0 +1,105 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Row + */ +data class Row( + /** + * Row ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Row automatically incrementing ID. + */ + @SerializedName("\$sequence") + val sequence: Long, + + /** + * Table ID. + */ + @SerializedName("\$tableId") + val tableId: String, + + /** + * Database ID. + */ + @SerializedName("\$databaseId") + val databaseId: String, + + /** + * Row creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Row update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + */ + @SerializedName("\$permissions") + val permissions: List, + + /** + * Additional properties + */ + @SerializedName("data") + val data: T +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$sequence" to sequence as Any, + "\$tableId" to tableId as Any, + "\$databaseId" to databaseId as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "\$permissions" to permissions as Any, + "data" to data!!.jsonCast(to = Map::class.java) + ) + + companion object { + operator fun invoke( + id: String, + sequence: Long, + tableId: String, + databaseId: String, + createdAt: String, + updatedAt: String, + permissions: List, + data: Map + ) = Row>( + id, + sequence, + tableId, + databaseId, + createdAt, + updatedAt, + permissions, + data + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = Row( + id = map["\$id"] as String, + sequence = (map["\$sequence"] as Number).toLong(), + tableId = map["\$tableId"] as String, + databaseId = map["\$databaseId"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + permissions = map["\$permissions"] as List, + data = map.jsonCast(to = nestedType) + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/RowList.kt b/library/src/main/java/io/appwrite/models/RowList.kt new file mode 100644 index 0000000..5e99cd7 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/RowList.kt @@ -0,0 +1,46 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Rows List + */ +data class RowList( + /** + * Total number of rows that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of rows. + */ + @SerializedName("rows") + val rows: List>, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "rows" to rows.map { it.toMap() } as Any, + ) + + companion object { + operator fun invoke( + total: Long, + rows: List>>, + ) = RowList>( + total, + rows, + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = RowList( + total = (map["total"] as Number).toLong(), + rows = (map["rows"] as List>).map { Row.from(map = it, nestedType) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Session.kt b/library/src/main/java/io/appwrite/models/Session.kt new file mode 100644 index 0000000..02dbb28 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Session.kt @@ -0,0 +1,254 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Session + */ +data class Session( + /** + * Session ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Session creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Session update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * Session expiration date in ISO 8601 format. + */ + @SerializedName("expire") + val expire: String, + + /** + * Session Provider. + */ + @SerializedName("provider") + val provider: String, + + /** + * Session Provider User ID. + */ + @SerializedName("providerUid") + val providerUid: String, + + /** + * Session Provider Access Token. + */ + @SerializedName("providerAccessToken") + val providerAccessToken: String, + + /** + * The date of when the access token expires in ISO 8601 format. + */ + @SerializedName("providerAccessTokenExpiry") + val providerAccessTokenExpiry: String, + + /** + * Session Provider Refresh Token. + */ + @SerializedName("providerRefreshToken") + val providerRefreshToken: String, + + /** + * IP in use when the session was created. + */ + @SerializedName("ip") + val ip: String, + + /** + * Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + */ + @SerializedName("osCode") + val osCode: String, + + /** + * Operating system name. + */ + @SerializedName("osName") + val osName: String, + + /** + * Operating system version. + */ + @SerializedName("osVersion") + val osVersion: String, + + /** + * Client type. + */ + @SerializedName("clientType") + val clientType: String, + + /** + * Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + */ + @SerializedName("clientCode") + val clientCode: String, + + /** + * Client name. + */ + @SerializedName("clientName") + val clientName: String, + + /** + * Client version. + */ + @SerializedName("clientVersion") + val clientVersion: String, + + /** + * Client engine name. + */ + @SerializedName("clientEngine") + val clientEngine: String, + + /** + * Client engine name. + */ + @SerializedName("clientEngineVersion") + val clientEngineVersion: String, + + /** + * Device name. + */ + @SerializedName("deviceName") + val deviceName: String, + + /** + * Device brand name. + */ + @SerializedName("deviceBrand") + val deviceBrand: String, + + /** + * Device model name. + */ + @SerializedName("deviceModel") + val deviceModel: String, + + /** + * Country two-character ISO 3166-1 alpha code. + */ + @SerializedName("countryCode") + val countryCode: String, + + /** + * Country name. + */ + @SerializedName("countryName") + val countryName: String, + + /** + * Returns true if this the current user session. + */ + @SerializedName("current") + val current: Boolean, + + /** + * Returns a list of active session factors. + */ + @SerializedName("factors") + val factors: List, + + /** + * Secret used to authenticate the user. Only included if the request was made with an API key + */ + @SerializedName("secret") + val secret: String, + + /** + * Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + */ + @SerializedName("mfaUpdatedAt") + val mfaUpdatedAt: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "userId" to userId as Any, + "expire" to expire as Any, + "provider" to provider as Any, + "providerUid" to providerUid as Any, + "providerAccessToken" to providerAccessToken as Any, + "providerAccessTokenExpiry" to providerAccessTokenExpiry as Any, + "providerRefreshToken" to providerRefreshToken as Any, + "ip" to ip as Any, + "osCode" to osCode as Any, + "osName" to osName as Any, + "osVersion" to osVersion as Any, + "clientType" to clientType as Any, + "clientCode" to clientCode as Any, + "clientName" to clientName as Any, + "clientVersion" to clientVersion as Any, + "clientEngine" to clientEngine as Any, + "clientEngineVersion" to clientEngineVersion as Any, + "deviceName" to deviceName as Any, + "deviceBrand" to deviceBrand as Any, + "deviceModel" to deviceModel as Any, + "countryCode" to countryCode as Any, + "countryName" to countryName as Any, + "current" to current as Any, + "factors" to factors as Any, + "secret" to secret as Any, + "mfaUpdatedAt" to mfaUpdatedAt as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Session( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + userId = map["userId"] as String, + expire = map["expire"] as String, + provider = map["provider"] as String, + providerUid = map["providerUid"] as String, + providerAccessToken = map["providerAccessToken"] as String, + providerAccessTokenExpiry = map["providerAccessTokenExpiry"] as String, + providerRefreshToken = map["providerRefreshToken"] as String, + ip = map["ip"] as String, + osCode = map["osCode"] as String, + osName = map["osName"] as String, + osVersion = map["osVersion"] as String, + clientType = map["clientType"] as String, + clientCode = map["clientCode"] as String, + clientName = map["clientName"] as String, + clientVersion = map["clientVersion"] as String, + clientEngine = map["clientEngine"] as String, + clientEngineVersion = map["clientEngineVersion"] as String, + deviceName = map["deviceName"] as String, + deviceBrand = map["deviceBrand"] as String, + deviceModel = map["deviceModel"] as String, + countryCode = map["countryCode"] as String, + countryName = map["countryName"] as String, + current = map["current"] as Boolean, + factors = map["factors"] as List, + secret = map["secret"] as String, + mfaUpdatedAt = map["mfaUpdatedAt"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/SessionList.kt b/library/src/main/java/io/appwrite/models/SessionList.kt new file mode 100644 index 0000000..22fba69 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/SessionList.kt @@ -0,0 +1,38 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Sessions List + */ +data class SessionList( + /** + * Total number of sessions that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of sessions. + */ + @SerializedName("sessions") + val sessions: List, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "sessions" to sessions.map { it.toMap() } as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = SessionList( + total = (map["total"] as Number).toLong(), + sessions = (map["sessions"] as List>).map { Session.from(map = it) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Subscriber.kt b/library/src/main/java/io/appwrite/models/Subscriber.kt new file mode 100644 index 0000000..1920691 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Subscriber.kt @@ -0,0 +1,94 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Subscriber + */ +data class Subscriber( + /** + * Subscriber ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Subscriber creation time in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Subscriber update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Target ID. + */ + @SerializedName("targetId") + val targetId: String, + + /** + * Target. + */ + @SerializedName("target") + val target: Target, + + /** + * Topic ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * User Name. + */ + @SerializedName("userName") + val userName: String, + + /** + * Topic ID. + */ + @SerializedName("topicId") + val topicId: String, + + /** + * The target provider type. Can be one of the following: `email`, `sms` or `push`. + */ + @SerializedName("providerType") + val providerType: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "targetId" to targetId as Any, + "target" to target.toMap() as Any, + "userId" to userId as Any, + "userName" to userName as Any, + "topicId" to topicId as Any, + "providerType" to providerType as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Subscriber( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + targetId = map["targetId"] as String, + target = Target.from(map = map["target"] as Map), + userId = map["userId"] as String, + userName = map["userName"] as String, + topicId = map["topicId"] as String, + providerType = map["providerType"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Target.kt b/library/src/main/java/io/appwrite/models/Target.kt new file mode 100644 index 0000000..54b4694 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Target.kt @@ -0,0 +1,94 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Target + */ +data class Target( + /** + * Target ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Target creation time in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Target update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Target Name. + */ + @SerializedName("name") + val name: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * Provider ID. + */ + @SerializedName("providerId") + var providerId: String?, + + /** + * The target provider type. Can be one of the following: `email`, `sms` or `push`. + */ + @SerializedName("providerType") + val providerType: String, + + /** + * The target identifier. + */ + @SerializedName("identifier") + val identifier: String, + + /** + * Is the target expired. + */ + @SerializedName("expired") + val expired: Boolean, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "name" to name as Any, + "userId" to userId as Any, + "providerId" to providerId as Any, + "providerType" to providerType as Any, + "identifier" to identifier as Any, + "expired" to expired as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Target( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + name = map["name"] as String, + userId = map["userId"] as String, + providerId = map["providerId"] as? String?, + providerType = map["providerType"] as String, + identifier = map["identifier"] as String, + expired = map["expired"] as Boolean, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Team.kt b/library/src/main/java/io/appwrite/models/Team.kt new file mode 100644 index 0000000..0723b90 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Team.kt @@ -0,0 +1,86 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Team + */ +data class Team( + /** + * Team ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Team creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Team update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Team name. + */ + @SerializedName("name") + val name: String, + + /** + * Total number of team members. + */ + @SerializedName("total") + val total: Long, + + /** + * Team preferences as a key-value object + */ + @SerializedName("prefs") + val prefs: Preferences, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "name" to name as Any, + "total" to total as Any, + "prefs" to prefs.toMap() as Any, + ) + + companion object { + operator fun invoke( + id: String, + createdAt: String, + updatedAt: String, + name: String, + total: Long, + prefs: Preferences>, + ) = Team>( + id, + createdAt, + updatedAt, + name, + total, + prefs, + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = Team( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + name = map["name"] as String, + total = (map["total"] as Number).toLong(), + prefs = Preferences.from(map = map["prefs"] as Map, nestedType), + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/TeamList.kt b/library/src/main/java/io/appwrite/models/TeamList.kt new file mode 100644 index 0000000..c95cc56 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/TeamList.kt @@ -0,0 +1,46 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Teams List + */ +data class TeamList( + /** + * Total number of teams that matched your query. + */ + @SerializedName("total") + val total: Long, + + /** + * List of teams. + */ + @SerializedName("teams") + val teams: List>, + +) { + fun toMap(): Map = mapOf( + "total" to total as Any, + "teams" to teams.map { it.toMap() } as Any, + ) + + companion object { + operator fun invoke( + total: Long, + teams: List>>, + ) = TeamList>( + total, + teams, + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = TeamList( + total = (map["total"] as Number).toLong(), + teams = (map["teams"] as List>).map { Team.from(map = it, nestedType) }, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/Token.kt b/library/src/main/java/io/appwrite/models/Token.kt new file mode 100644 index 0000000..e36d060 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Token.kt @@ -0,0 +1,70 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Token + */ +data class Token( + /** + * Token ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Token creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * User ID. + */ + @SerializedName("userId") + val userId: String, + + /** + * 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. + */ + @SerializedName("secret") + val secret: String, + + /** + * Token expiration date in ISO 8601 format. + */ + @SerializedName("expire") + val expire: String, + + /** + * 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. + */ + @SerializedName("phrase") + val phrase: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "userId" to userId as Any, + "secret" to secret as Any, + "expire" to expire as Any, + "phrase" to phrase as Any, + ) + + companion object { + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Token( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + userId = map["userId"] as String, + secret = map["secret"] as String, + expire = map["expire"] as String, + phrase = map["phrase"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/UploadProgress.kt b/library/src/main/java/io/appwrite/models/UploadProgress.kt new file mode 100644 index 0000000..4199694 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/UploadProgress.kt @@ -0,0 +1,9 @@ +package io.appwrite.models + +data class UploadProgress( + val id: String, + val progress: Double, + val sizeUploaded: Long, + val chunksTotal: Int, + val chunksUploaded: Int +) \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/models/User.kt b/library/src/main/java/io/appwrite/models/User.kt new file mode 100644 index 0000000..fd03fc2 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/User.kt @@ -0,0 +1,216 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * User + */ +data class User( + /** + * User ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * User creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * User update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * User name. + */ + @SerializedName("name") + val name: String, + + /** + * Hashed user password. + */ + @SerializedName("password") + var password: String?, + + /** + * Password hashing algorithm. + */ + @SerializedName("hash") + var hash: String?, + + /** + * Password hashing algorithm configuration. + */ + @SerializedName("hashOptions") + var hashOptions: Any?, + + /** + * User registration date in ISO 8601 format. + */ + @SerializedName("registration") + val registration: String, + + /** + * User status. Pass `true` for enabled and `false` for disabled. + */ + @SerializedName("status") + val status: Boolean, + + /** + * Labels for the user. + */ + @SerializedName("labels") + val labels: List, + + /** + * Password update time in ISO 8601 format. + */ + @SerializedName("passwordUpdate") + val passwordUpdate: String, + + /** + * User email address. + */ + @SerializedName("email") + val email: String, + + /** + * User phone number in E.164 format. + */ + @SerializedName("phone") + val phone: String, + + /** + * Email verification status. + */ + @SerializedName("emailVerification") + val emailVerification: Boolean, + + /** + * Phone verification status. + */ + @SerializedName("phoneVerification") + val phoneVerification: Boolean, + + /** + * Multi factor authentication status. + */ + @SerializedName("mfa") + val mfa: Boolean, + + /** + * User preferences as a key-value object + */ + @SerializedName("prefs") + val prefs: Preferences, + + /** + * 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. + */ + @SerializedName("targets") + val targets: List, + + /** + * Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + */ + @SerializedName("accessedAt") + val accessedAt: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "name" to name as Any, + "password" to password as Any, + "hash" to hash as Any, + "hashOptions" to hashOptions as Any, + "registration" to registration as Any, + "status" to status as Any, + "labels" to labels as Any, + "passwordUpdate" to passwordUpdate as Any, + "email" to email as Any, + "phone" to phone as Any, + "emailVerification" to emailVerification as Any, + "phoneVerification" to phoneVerification as Any, + "mfa" to mfa as Any, + "prefs" to prefs.toMap() as Any, + "targets" to targets.map { it.toMap() } as Any, + "accessedAt" to accessedAt as Any, + ) + + companion object { + operator fun invoke( + id: String, + createdAt: String, + updatedAt: String, + name: String, + password: String?, + hash: String?, + hashOptions: Any?, + registration: String, + status: Boolean, + labels: List, + passwordUpdate: String, + email: String, + phone: String, + emailVerification: Boolean, + phoneVerification: Boolean, + mfa: Boolean, + prefs: Preferences>, + targets: List, + accessedAt: String, + ) = User>( + id, + createdAt, + updatedAt, + name, + password, + hash, + hashOptions, + registration, + status, + labels, + passwordUpdate, + email, + phone, + emailVerification, + phoneVerification, + mfa, + prefs, + targets, + accessedAt, + ) + + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + nestedType: Class + ) = User( + id = map["\$id"] as String, + createdAt = map["\$createdAt"] as String, + updatedAt = map["\$updatedAt"] as String, + name = map["name"] as String, + password = map["password"] as? String?, + hash = map["hash"] as? String?, + hashOptions = map["hashOptions"] as? Any?, + registration = map["registration"] as String, + status = map["status"] as Boolean, + labels = map["labels"] as List, + passwordUpdate = map["passwordUpdate"] as String, + email = map["email"] as String, + phone = map["phone"] as String, + emailVerification = map["emailVerification"] as Boolean, + phoneVerification = map["phoneVerification"] as Boolean, + mfa = map["mfa"] as Boolean, + prefs = Preferences.from(map = map["prefs"] as Map, nestedType), + targets = (map["targets"] as List>).map { Target.from(map = it) }, + accessedAt = map["accessedAt"] as String, + ) + } +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Account.kt b/library/src/main/java/io/appwrite/services/Account.kt index 89206d3..d5ed63a 100644 --- a/library/src/main/java/io/appwrite/services/Account.kt +++ b/library/src/main/java/io/appwrite/services/Account.kt @@ -2,590 +2,1960 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* +import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import io.appwrite.WebAuthComponent import androidx.activity.ComponentActivity -import io.appwrite.exceptions.AppwriteException import okhttp3.Cookie -import okhttp3.Response import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import java.io.File -class Account(client: Client) : Service(client) { +/** + * The Account service allows you to authenticate and manage a user account. + */ +class Account(client: Client) : Service(client) { + + /** + * Get the currently logged in user. + * + * @return [io.appwrite.models.User] + */ + suspend fun get( + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get the currently logged in user. + * + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun get( + ): io.appwrite.models.User> = get( + nestedType = classOf(), + ) + + /** + * Use this endpoint to allow a new user to register a new account in your project. After the user registration completes successfully, you can use the [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) route to start verifying the user email address. To allow the new user to login to their new account, you need to create a new [account session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + * + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param email User email. + * @param password New user password. Must be between 8 and 256 chars. + * @param name User name. Max length: 128 chars. + * @return [io.appwrite.models.User] + */ + @JvmOverloads + suspend fun create( + userId: String, + email: String, + password: String, + name: String? = null, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account" + + val apiParams = mutableMapOf( + "userId" to userId, + "email" to email, + "password" to password, + "name" to name, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Use this endpoint to allow a new user to register a new account in your project. After the user registration completes successfully, you can use the [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) route to start verifying the user email address. To allow the new user to login to their new account, you need to create a new [account session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + * + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param email User email. + * @param password New user password. Must be between 8 and 256 chars. + * @param name User name. Max length: 128 chars. + * @return [io.appwrite.models.User] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun create( + userId: String, + email: String, + password: String, + name: String? = null, + ): io.appwrite.models.User> = create( + userId, + email, + password, + name, + nestedType = classOf(), + ) + + /** + * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. + * This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. + * + * + * @param email User email. + * @param password User password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + suspend fun updateEmail( + email: String, + password: String, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/email" + + val apiParams = mutableMapOf( + "email" to email, + "password" to password, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. + * This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. + * + * + * @param email User email. + * @param password User password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updateEmail( + email: String, + password: String, + ): io.appwrite.models.User> = updateEmail( + email, + password, + nestedType = classOf(), + ) + + /** + * Get the list of identities for the currently logged in user. + * + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry + * @return [io.appwrite.models.IdentityList] + */ + @JvmOverloads + suspend fun listIdentities( + queries: List? = null, + ): io.appwrite.models.IdentityList { + val apiPath = "/account/identities" + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.IdentityList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.IdentityList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.IdentityList::class.java, + converter, + ) + } + + + /** + * Delete an identity by its unique ID. + * + * @param identityId Identity ID. + * @return [Any] + */ + suspend fun deleteIdentity( + identityId: String, + ): Any { + val apiPath = "/account/identities/{identityId}" + .replace("{identityId}", identityId) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Use this endpoint to create a JSON Web Token. You can use the resulting JWT to authenticate on behalf of the current user when working with the Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes from its creation and will be invalid if the user will logout in that time frame. + * + * @return [io.appwrite.models.Jwt] + */ + suspend fun createJWT( + ): io.appwrite.models.Jwt { + val apiPath = "/account/jwts" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Jwt = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Jwt.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Jwt::class.java, + converter, + ) + } + + + /** + * 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. + * + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset + * @return [io.appwrite.models.LogList] + */ + @JvmOverloads + suspend fun listLogs( + queries: List? = null, + ): io.appwrite.models.LogList { + val apiPath = "/account/logs" + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.LogList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.LogList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.LogList::class.java, + converter, + ) + } + + + /** + * Enable or disable MFA on an account. + * + * @param mfa Enable or disable MFA. + * @return [io.appwrite.models.User] + */ + suspend fun updateMFA( + mfa: Boolean, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/mfa" + + val apiParams = mutableMapOf( + "mfa" to mfa, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Enable or disable MFA on an account. + * + * @param mfa Enable or disable MFA. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updateMFA( + mfa: Boolean, + ): io.appwrite.models.User> = updateMFA( + mfa, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param type Type of authenticator. Must be `totp` + * @return [io.appwrite.models.MfaType] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.createMFAAuthenticator") + ) + suspend fun createMfaAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + ): io.appwrite.models.MfaType { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaType = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaType.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaType::class.java, + converter, + ) + } + + + /** + * 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. + * + * @param type Type of authenticator. Must be `totp` + * @return [io.appwrite.models.MfaType] + */ + suspend fun createMFAAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + ): io.appwrite.models.MfaType { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaType = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaType.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaType::class.java, + converter, + ) + } + + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param type Type of authenticator. + * @param otp Valid verification token. + * @return [io.appwrite.models.User] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.updateMFAAuthenticator") + ) + suspend fun updateMfaAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + otp: String, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + "otp" to otp, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param type Type of authenticator. + * @param otp Valid verification token. + * @return [io.appwrite.models.User] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.updateMFAAuthenticator") + ) + @Throws(AppwriteException::class) + suspend fun updateMfaAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + otp: String, + ): io.appwrite.models.User> = updateMfaAuthenticator( + type, + otp, + nestedType = classOf(), + ) + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param type Type of authenticator. + * @param otp Valid verification token. + * @return [io.appwrite.models.User] + */ + suspend fun updateMFAAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + otp: String, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + "otp" to otp, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param type Type of authenticator. + * @param otp Valid verification token. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updateMFAAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + otp: String, + ): io.appwrite.models.User> = updateMFAAuthenticator( + type, + otp, + nestedType = classOf(), + ) + + /** + * Delete an authenticator for a user by ID. + * + * @param type Type of authenticator. + * @return [Any] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.deleteMFAAuthenticator") + ) + suspend fun deleteMfaAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + ): Any { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Delete an authenticator for a user by ID. + * + * @param type Type of authenticator. + * @return [Any] + */ + suspend fun deleteMFAAuthenticator( + type: io.appwrite.enums.AuthenticatorType, + ): Any { + val apiPath = "/account/mfa/authenticators/{type}" + .replace("{type}", type.value) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. + * + * @param factor Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. + * @return [io.appwrite.models.MfaChallenge] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.createMFAChallenge") + ) + suspend fun createMfaChallenge( + factor: io.appwrite.enums.AuthenticationFactor, + ): io.appwrite.models.MfaChallenge { + val apiPath = "/account/mfa/challenge" + + val apiParams = mutableMapOf( + "factor" to factor, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaChallenge = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaChallenge.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaChallenge::class.java, + converter, + ) + } + + + /** + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. + * + * @param factor Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. + * @return [io.appwrite.models.MfaChallenge] + */ + suspend fun createMFAChallenge( + factor: io.appwrite.enums.AuthenticationFactor, + ): io.appwrite.models.MfaChallenge { + val apiPath = "/account/mfa/challenge" + + val apiParams = mutableMapOf( + "factor" to factor, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaChallenge = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaChallenge.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaChallenge::class.java, + converter, + ) + } + + + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param challengeId ID of the challenge. + * @param otp Valid verification token. + * @return [io.appwrite.models.Session] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.updateMFAChallenge") + ) + suspend fun updateMfaChallenge( + challengeId: String, + otp: String, + ): io.appwrite.models.Session { + val apiPath = "/account/mfa/challenge" + + val apiParams = mutableMapOf( + "challengeId" to challengeId, + "otp" to otp, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + + + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param challengeId ID of the challenge. + * @param otp Valid verification token. + * @return [io.appwrite.models.Session] + */ + suspend fun updateMFAChallenge( + challengeId: String, + otp: String, + ): io.appwrite.models.Session { + val apiPath = "/account/mfa/challenge" + + val apiParams = mutableMapOf( + "challengeId" to challengeId, + "otp" to otp, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + + + /** + * List the factors available on the account to be used as a MFA challange. + * + * @return [io.appwrite.models.MfaFactors] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.listMFAFactors") + ) + suspend fun listMfaFactors( + ): io.appwrite.models.MfaFactors { + val apiPath = "/account/mfa/factors" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.MfaFactors = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaFactors.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaFactors::class.java, + converter, + ) + } + + + /** + * List the factors available on the account to be used as a MFA challange. + * + * @return [io.appwrite.models.MfaFactors] + */ + suspend fun listMFAFactors( + ): io.appwrite.models.MfaFactors { + val apiPath = "/account/mfa/factors" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.MfaFactors = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaFactors.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaFactors::class.java, + converter, + ) + } + + + /** + * 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. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.getMFARecoveryCodes") + ) + suspend fun getMfaRecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * 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. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + suspend fun getMFARecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * Generate recovery codes as backup for MFA flow. It's recommended to generate and show then immediately after user successfully adds their authehticator. Recovery codes can be used as a MFA verification type in [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.createMFARecoveryCodes") + ) + suspend fun createMfaRecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * Generate recovery codes as backup for MFA flow. It's recommended to generate and show then immediately after user successfully adds their authehticator. Recovery codes can be used as a MFA verification type in [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + suspend fun createMFARecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * 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. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.", + replaceWith = ReplaceWith("io.appwrite.services.Account.updateMFARecoveryCodes") + ) + suspend fun updateMfaRecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * 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. + * + * @return [io.appwrite.models.MfaRecoveryCodes] + */ + suspend fun updateMFARecoveryCodes( + ): io.appwrite.models.MfaRecoveryCodes { + val apiPath = "/account/mfa/recovery-codes" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.MfaRecoveryCodes = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MfaRecoveryCodes.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MfaRecoveryCodes::class.java, + converter, + ) + } + + + /** + * Update currently logged in user account name. + * + * @param name User name. Max length: 128 chars. + * @return [io.appwrite.models.User] + */ + suspend fun updateName( + name: String, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/name" + + val apiParams = mutableMapOf( + "name" to name, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Update currently logged in user account name. + * + * @param name User name. Max length: 128 chars. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updateName( + name: String, + ): io.appwrite.models.User> = updateName( + name, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param password New user password. Must be at least 8 chars. + * @param oldPassword Current user password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + @JvmOverloads + suspend fun updatePassword( + password: String, + oldPassword: String? = null, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/password" + + val apiParams = mutableMapOf( + "password" to password, + "oldPassword" to oldPassword, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * 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. + * + * @param password New user password. Must be at least 8 chars. + * @param oldPassword Current user password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun updatePassword( + password: String, + oldPassword: String? = null, + ): io.appwrite.models.User> = updatePassword( + password, + oldPassword, + nestedType = classOf(), + ) + + /** + * Update the currently logged in user's phone number. After updating the phone number, the phone verification status will be reset. A confirmation SMS is not sent automatically, however you can use the [POST /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) endpoint to send a confirmation SMS. + * + * @param phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param password User password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + suspend fun updatePhone( + phone: String, + password: String, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/phone" + + val apiParams = mutableMapOf( + "phone" to phone, + "password" to password, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Update the currently logged in user's phone number. After updating the phone number, the phone verification status will be reset. A confirmation SMS is not sent automatically, however you can use the [POST /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) endpoint to send a confirmation SMS. + * + * @param phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param password User password. Must be at least 8 chars. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updatePhone( + phone: String, + password: String, + ): io.appwrite.models.User> = updatePhone( + phone, + password, + nestedType = classOf(), + ) + + /** + * Get the preferences as a key-value object for the currently logged in user. + * + * @return [io.appwrite.models.Preferences] + */ + suspend fun getPrefs( + nestedType: Class, + ): io.appwrite.models.Preferences { + val apiPath = "/account/prefs" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Preferences = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Preferences.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get the preferences as a key-value object for the currently logged in user. + * + * @return [io.appwrite.models.Preferences] + */ + @Throws(AppwriteException::class) + suspend fun getPrefs( + ): io.appwrite.models.Preferences> = getPrefs( + nestedType = classOf(), + ) + + /** + * 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. + * + * @param prefs Prefs key-value JSON object. + * @return [io.appwrite.models.User] + */ + suspend fun updatePrefs( + prefs: Any, + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/prefs" + + val apiParams = mutableMapOf( + "prefs" to prefs, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * 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. + * + * @param prefs Prefs key-value JSON object. + * @return [io.appwrite.models.User] + */ + @Throws(AppwriteException::class) + suspend fun updatePrefs( + prefs: Any, + ): io.appwrite.models.User> = updatePrefs( + prefs, + nestedType = classOf(), + ) + + /** + * Sends the user an email with a temporary secret key for password reset. When the user clicks the confirmation link he is redirected back to your app password reset URL with the secret key and email address values attached to the URL query string. Use the query string params to submit a request to the [PUT /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) endpoint to complete the process. The verification link sent to the user's email address is valid for 1 hour. + * + * @param email User email. + * @param url URL to redirect the user back to your app from the recovery email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @return [io.appwrite.models.Token] + */ + suspend fun createRecovery( + email: String, + url: String, + ): io.appwrite.models.Token { + val apiPath = "/account/recovery" + + val apiParams = mutableMapOf( + "email" to email, + "url" to url, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, + ) + } + + + /** + * Use this endpoint to complete the user account password reset. Both the **userId** and **secret** arguments will be passed as query parameters to the redirect URL you have provided when sending your request to the [POST /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) endpoint. + * + * Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface. + * + * @param userId User ID. + * @param secret Valid reset token. + * @param password New user password. Must be between 8 and 256 chars. + * @return [io.appwrite.models.Token] + */ + suspend fun updateRecovery( + userId: String, + secret: String, + password: String, + ): io.appwrite.models.Token { + val apiPath = "/account/recovery" + + val apiParams = mutableMapOf( + "userId" to userId, + "secret" to secret, + "password" to password, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, + ) + } + + + /** + * Get the list of active sessions across different devices for the currently logged in user. + * + * @return [io.appwrite.models.SessionList] + */ + suspend fun listSessions( + ): io.appwrite.models.SessionList { + val apiPath = "/account/sessions" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.SessionList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.SessionList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.SessionList::class.java, + converter, + ) + } + + + /** + * Delete all sessions from the user account and remove any sessions cookies from the end client. + * + * @return [Any] + */ + suspend fun deleteSessions( + ): Any { + val apiPath = "/account/sessions" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Use this endpoint to allow a new user to register an anonymous account in your project. This route will also create a new session for the user. To allow the new user to convert an anonymous account to a normal account, you need to update its [email and password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) or create an [OAuth2 session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + * + * @return [io.appwrite.models.Session] + */ + suspend fun createAnonymousSession( + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/anonymous" + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + + + /** + * 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). + * + * @param email User email. + * @param password User password. Must be at least 8 chars. + * @return [io.appwrite.models.Session] + */ + suspend fun createEmailPasswordSession( + email: String, + password: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/email" + + val apiParams = mutableMapOf( + "email" to email, + "password" to password, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + + + /** + * 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. + * + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param secret Valid verification token. + * @return [io.appwrite.models.Session] + */ + @Deprecated( + message = "This API has been deprecated." + ) + suspend fun updateMagicURLSession( + userId: String, + secret: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/magic-url" + + val apiParams = mutableMapOf( + "userId" to userId, + "secret" to secret, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + + + /** + * 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). + * + * + * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. + */ + @JvmOverloads + suspend fun createOAuth2Session( + activity: ComponentActivity, + provider: io.appwrite.enums.OAuthProvider, + success: String? = null, + failure: String? = null, + scopes: List? = null, + ) { + val apiPath = "/account/sessions/oauth2/{provider}" + .replace("{provider}", provider.value) + + val apiParams = mutableMapOf( + "success" to success, + "failure" to failure, + "scopes" to scopes, + "project" to client.config["project"], + ) + val apiQuery = mutableListOf() + apiParams.forEach { + when (it.value) { + null -> { + return@forEach + } + is List<*> -> { + (it.value as List<*>).forEach { v -> + apiQuery.add("${it.key}[]=${v.toString()}") + } + } + else -> { + apiQuery.add("${it.key}=${it.value.toString()}") + } + } + } + + val apiUrl = Uri.parse("${client.endpoint}${apiPath}?${apiQuery.joinToString("&")}") + val callbackUrlScheme = "appwrite-callback-${client.config["project"]}" + + WebAuthComponent.authenticate(activity, apiUrl, callbackUrlScheme) { + if (it.isFailure) { + throw it.exceptionOrNull()!! + } + + val resultUrl = it.getOrNull()!! + val uri = Uri.parse(resultUrl) + val key = uri.getQueryParameter("key") + val secret = uri.getQueryParameter("secret") + if (key == null || secret == null) { + throw AppwriteException("Authentication cookie missing!") + } + val cookie = Cookie.Builder() + .name(key) + .value(secret) + .domain(Uri.parse(client.endpoint).host!!) + .httpOnly() + .build() + + client.http.cookieJar.saveFromResponse( + client.endpoint.toHttpUrl(), + listOf(cookie) + ) + } + } + /** - * Get Account + * 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. * - * Get currently logged in user data as JSON object. - * - * @return [Response] + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param secret Valid verification token. + * @return [io.appwrite.models.Session] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun get(): Response { - val path = "/account" - val params = mapOf( - ) + @Deprecated( + message = "This API has been deprecated." + ) + suspend fun updatePhoneSession( + userId: String, + secret: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/phone" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "userId" to userId, + "secret" to secret, ) - - return client.call("GET", path, headers, params) - } - - /** - * Create Account - * - * Use this endpoint to allow a new user to register a new account in your - * project. After the user registration completes successfully, you can use - * the [/account/verfication](/docs/client/account#accountCreateVerification) - * 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](/docs/client/account#accountCreateSession). - * - * @param email - * @param password - * @param name - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun create( - email: String, - password: String, - name: String? = null - ): Response { - val path = "/account" - val params = mapOf( - "email" to email, - "password" to password, - "name" to name + val apiHeaders = mutableMapOf( + "content-type" to "application/json", ) - - val headers = mapOf( - "content-type" to "application/json" + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - - /** - * Delete Account - * - * Delete a currently logged in user account. Behind the scene, the user - * record is not deleted but permanently blocked from any access. This is done - * to avoid deleted accounts being overtaken by new users with the same email - * address. Any user-related resources like documents or storage files should - * be deleted separately. - * - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun delete(): Response { - val path = "/account" - val params = mapOf( - ) - val headers = mapOf( - "content-type" to "application/json" - ) - return client.call("DELETE", path, headers, params) - } - /** - * Update Account Email - * - * Update currently logged in user account email address. After changing user - * address, user confirmation status is being reset and a new confirmation - * mail is sent. For security measures, user password is required to complete - * this request. - * This endpoint can also be used to convert an anonymous account to a normal - * one, by passing an email address and a new password. + * 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. * - * @param email - * @param password - * @return [Response] + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param secret Secret of a token generated by login methods. For example, the `createMagicURLToken` or `createPhoneToken` methods. + * @return [io.appwrite.models.Session] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateEmail( - email: String, - password: String - ): Response { - val path = "/account/email" - val params = mapOf( - "email" to email, - "password" to password - ) + suspend fun createSession( + userId: String, + secret: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/token" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "userId" to userId, + "secret" to secret, ) - - return client.call("PATCH", path, headers, params) - } - - /** - * Create Account JWT - * - * Use this endpoint to create a JSON Web Token. You can use the resulting JWT - * to authenticate on behalf of the current user when working with the - * Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - * from its creation and will be invalid if the user will logout in that time - * frame. - * - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createJWT(): Response { - val path = "/account/jwt" - val params = mapOf( + val apiHeaders = mutableMapOf( + "content-type" to "application/json", ) - - val headers = mapOf( - "content-type" to "application/json" + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - - /** - * Get Account Logs - * - * Get currently logged in user list of latest security activity logs. Each - * log returns user IP address, location and date and time of log. - * - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getLogs(): Response { - val path = "/account/logs" - val params = mapOf( - ) - val headers = mapOf( - "content-type" to "application/json" - ) - return client.call("GET", path, headers, params) - } - /** - * Update Account Name + * Use this endpoint to get a logged in user's session using a Session ID. Inputting 'current' will return the current session being used. * - * Update currently logged in user account name. - * - * @param name - * @return [Response] + * @param sessionId Session ID. Use the string 'current' to get the current device session. + * @return [io.appwrite.models.Session] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateName( - name: String - ): Response { - val path = "/account/name" - val params = mapOf( - "name" to name - ) + suspend fun getSession( + sessionId: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/{sessionId}" + .replace("{sessionId}", sessionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( ) - - return client.call("PATCH", path, headers, params) - } - - /** - * Update Account Password - * - * Update currently logged in user password. For validation, user is required - * to pass in the new password, and the old password. For users created with - * OAuth and Team Invites, oldPassword is optional. - * - * @param password - * @param oldPassword - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updatePassword( - password: String, - oldPassword: String? = null - ): Response { - val path = "/account/password" - val params = mapOf( - "password" to password, - "oldPassword" to oldPassword + val apiHeaders = mutableMapOf( ) - - val headers = mapOf( - "content-type" to "application/json" + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, ) - - return client.call("PATCH", path, headers, params) } - - /** - * Get Account Preferences - * - * Get currently logged in user preferences as a key-value object. - * - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getPrefs(): Response { - val path = "/account/prefs" - val params = mapOf( - ) - val headers = mapOf( - "content-type" to "application/json" - ) - return client.call("GET", path, headers, params) - } - /** - * Update Account Preferences - * - * Update currently logged in user account preferences. You can pass only the - * specific settings you wish to update. + * 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. * - * @param prefs - * @return [Response] + * @param sessionId Session ID. Use the string 'current' to update the current device session. + * @return [io.appwrite.models.Session] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updatePrefs( - prefs: Any - ): Response { - val path = "/account/prefs" - val params = mapOf( - "prefs" to prefs - ) + suspend fun updateSession( + sessionId: String, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/{sessionId}" + .replace("{sessionId}", sessionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, ) - - return client.call("PATCH", path, headers, params) } - + + /** - * Create Password Recovery + * Logout the user. Use 'current' as the session ID to logout on this device, use a session ID to logout on another device. If you're looking to logout the user on all devices, use [Delete Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) instead. * - * Sends the user an email with a temporary secret key for password reset. - * When the user clicks the confirmation link he is redirected back to your - * app password reset URL with the secret key and email address values - * attached to the URL query string. Use the query string params to submit a - * request to the [PUT - * /account/recovery](/docs/client/account#accountUpdateRecovery) endpoint to - * complete the process. The verification link sent to the user's email - * address is valid for 1 hour. - * - * @param email - * @param url - * @return [Response] + * @param sessionId Session ID. Use the string 'current' to delete the current device session. + * @return [Any] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createRecovery( - email: String, - url: String - ): Response { - val path = "/account/recovery" - val params = mapOf( - "email" to email, - "url" to url - ) + suspend fun deleteSession( + sessionId: String, + ): Any { + val apiPath = "/account/sessions/{sessionId}" + .replace("{sessionId}", sessionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, ) - - return client.call("POST", path, headers, params) } - + + /** - * Create Password Recovery (confirmation) + * Block the currently logged in user account. Behind the scene, the user record is not deleted but permanently blocked from any access. To completely delete a user, use the Users API instead. * - * Use this endpoint to complete the user account password reset. Both the - * **userId** and **secret** arguments will be passed as query parameters to - * the redirect URL you have provided when sending your request to the [POST - * /account/recovery](/docs/client/account#accountCreateRecovery) 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. - * - * @param userId - * @param secret - * @param password - * @param passwordAgain - * @return [Response] + * @return [io.appwrite.models.User] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateRecovery( - userId: String, - secret: String, - password: String, - passwordAgain: String - ): Response { - val path = "/account/recovery" - val params = mapOf( - "userId" to userId, - "secret" to secret, - "password" to password, - "passwordAgain" to passwordAgain - ) + suspend fun updateStatus( + nestedType: Class, + ): io.appwrite.models.User { + val apiPath = "/account/status" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.User = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.User.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, ) - - return client.call("PUT", path, headers, params) } - + /** - * Get Account Sessions + * Block the currently logged in user account. Behind the scene, the user record is not deleted but permanently blocked from any access. To completely delete a user, use the Users API instead. * - * Get currently logged in user list of active sessions across different - * devices. - * - * @return [Response] + * @return [io.appwrite.models.User] */ - @JvmOverloads @Throws(AppwriteException::class) - suspend fun getSessions(): Response { - val path = "/account/sessions" - val params = mapOf( - ) - - val headers = mapOf( - "content-type" to "application/json" - ) + suspend fun updateStatus( + ): io.appwrite.models.User> = updateStatus( + nestedType = classOf(), + ) - return client.call("GET", path, headers, params) - } - /** - * Create Account Session + * Use this endpoint to register a device for push notifications. Provide a 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. * - * 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. - * - * @param email - * @param password - * @return [Response] + * @param targetId Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param identifier The target identifier (token, email, phone etc.) + * @param providerId Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. + * @return [io.appwrite.models.Target] */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createSession( - email: String, - password: String - ): Response { - val path = "/account/sessions" - val params = mapOf( - "email" to email, - "password" to password - ) + suspend fun createPushTarget( + targetId: String, + identifier: String, + providerId: String? = null, + ): io.appwrite.models.Target { + val apiPath = "/account/targets/push" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "targetId" to targetId, + "identifier" to identifier, + "providerId" to providerId, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Target = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Target.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Target::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - + + /** - * Delete All Account Sessions - * - * Delete all sessions from the user account and remove any sessions cookies - * from the end client. + * Update the currently logged in user's push notification target. You can modify the target's identifier (device token) and provider ID (token, 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. * - * @return [Response] + * @param targetId Target ID. + * @param identifier The target identifier (token, email, phone etc.) + * @return [io.appwrite.models.Target] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun deleteSessions(): Response { - val path = "/account/sessions" - val params = mapOf( - ) + suspend fun updatePushTarget( + targetId: String, + identifier: String, + ): io.appwrite.models.Target { + val apiPath = "/account/targets/{targetId}/push" + .replace("{targetId}", targetId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "identifier" to identifier, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Target = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Target.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Target::class.java, + converter, ) - - return client.call("DELETE", path, headers, params) } - + + /** - * Create Anonymous Session - * - * Use this endpoint to allow a new user to register an anonymous account in - * your project. This route will also create a new session for the user. To - * allow the new user to convert an anonymous account to a normal account, you - * need to update its [email and - * password](/docs/client/account#accountUpdateEmail) or create an [OAuth2 - * session](/docs/client/account#accountCreateOAuth2Session). + * 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. * - * @return [Response] + * @param targetId Target ID. + * @return [Any] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createAnonymousSession(): Response { - val path = "/account/sessions/anonymous" - val params = mapOf( - ) + suspend fun deletePushTarget( + targetId: String, + ): Any { + val apiPath = "/account/targets/{targetId}/push" + .replace("{targetId}", targetId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, ) - - return client.call("POST", path, headers, params) } - + + /** - * Create Magic URL session - * - * Sends the user an email with a secret key for creating a session. When the - * user clicks the link in the email, the user is redirected back to the URL - * you provided with the secret key and userId values attached to the URL - * query string. Use the query string parameters to submit a request to the - * [PUT - * /account/sessions/magic-url](/docs/client/account#accountUpdateMagicURLSession) - * endpoint to complete the login process. The link sent to the user's email - * address is valid for 1 hour. If you are on a mobile device you can leave - * the URL parameter empty, so that the login completion will be handled by - * your Appwrite instance by default. + * Sends the user an email with a secret key for creating a session. If the email address has never been used, a **new account is created** using the provided `userId`. Otherwise, if the email address is already attached to an account, the **user ID is ignored**. Then, the user will receive an email with the one-time password. Use the returned user ID and secret and submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's email is valid for 15 minutes. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * * - * @param email - * @param url - * @return [Response] + * @param userId User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param email User email. + * @param phrase Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. + * @return [io.appwrite.models.Token] */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createMagicURLSession( - email: String, - url: String? = null - ): Response { - val path = "/account/sessions/magic-url" - val params = mapOf( + suspend fun createEmailToken( + userId: String, + email: String, + phrase: Boolean? = null, + ): io.appwrite.models.Token { + val apiPath = "/account/tokens/email" + + val apiParams = mutableMapOf( + "userId" to userId, "email" to email, - "url" to url + "phrase" to phrase, ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - + + /** - * Create Magic URL session (confirmation) - * - * Use this endpoint to complete creating the session with the Magic URL. Both - * the **userId** and **secret** arguments will be passed as query parameters - * to the redirect URL you have provided when sending your request to the - * [POST - * /account/sessions/magic-url](/docs/client/account#accountCreateMagicURLSession) - * endpoint. + * Sends the user an email with a secret key for creating a session. If the provided user ID has not been registered, a new user will be created. When the user clicks the link in the email, the user is redirected back to the URL you provided with the secret key and userId values attached to the URL query string. Use the query string parameters to submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The link sent to the user's email address is valid for 1 hour. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * 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. * - * @param userId - * @param secret - * @return [Response] + * @param userId Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param email User email. + * @param url URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param phrase Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. + * @return [io.appwrite.models.Token] */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateMagicURLSession( - userId: String, - secret: String - ): Response { - val path = "/account/sessions/magic-url" - val params = mapOf( + suspend fun createMagicURLToken( + userId: String, + email: String, + url: String? = null, + phrase: Boolean? = null, + ): io.appwrite.models.Token { + val apiPath = "/account/tokens/magic-url" + + val apiParams = mutableMapOf( "userId" to userId, - "secret" to secret + "email" to email, + "url" to url, + "phrase" to phrase, ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, ) - - return client.call("PUT", path, headers, params) } - + + /** - * Create Account Session with OAuth2 - * - * 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. + * 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.. + * 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). * - * @param provider - * @param success - * @param failure - * @param scopes - * + * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createOAuth2Session( - activity: ComponentActivity, - provider: String, - success: String? = null, - failure: String? = null, - scopes: List? = null - ) { - val path = "/account/sessions/oauth2/{provider}".replace("{provider}", provider) - val params = mapOf( + suspend fun createOAuth2Token( + activity: ComponentActivity, + provider: io.appwrite.enums.OAuthProvider, + success: String? = null, + failure: String? = null, + scopes: List? = null, + ) { + val apiPath = "/account/tokens/oauth2/{provider}" + .replace("{provider}", provider.value) + + val apiParams = mutableMapOf( "success" to success, "failure" to failure, "scopes" to scopes, - "project" to client.config["project"] + "project" to client.config["project"], ) - - val query = mutableListOf() - params.forEach { + val apiQuery = mutableListOf() + apiParams.forEach { when (it.value) { null -> { return@forEach } is List<*> -> { - query.add("${it.key}[]=${it.value.toString()}") + (it.value as List<*>).forEach { v -> + apiQuery.add("${it.key}[]=${v.toString()}") + } } else -> { - query.add("${it.key}=${it.value.toString()}") + apiQuery.add("${it.key}=${it.value.toString()}") } } } - val url = Uri.parse("${client.endPoint}${path}?${query.joinToString("&")}") + val apiUrl = Uri.parse("${client.endpoint}${apiPath}?${apiQuery.joinToString("&")}") val callbackUrlScheme = "appwrite-callback-${client.config["project"]}" - WebAuthComponent.authenticate(activity, url, callbackUrlScheme) { + WebAuthComponent.authenticate(activity, apiUrl, callbackUrlScheme) { if (it.isFailure) { throw it.exceptionOrNull()!! } @@ -600,137 +1970,187 @@ class Account(client: Client) : Service(client) { val cookie = Cookie.Builder() .name(key) .value(secret) - .domain(Uri.parse(client.endPoint).host!!) + .domain(Uri.parse(client.endpoint).host!!) .httpOnly() .build() client.http.cookieJar.saveFromResponse( - client.endPoint.toHttpUrl(), + client.endpoint.toHttpUrl(), listOf(cookie) ) } - } - - /** - * Get Session By ID - * - * Use this endpoint to get a logged in user's session using a Session ID. - * Inputting 'current' will return the current session being used. - * - * @param sessionId - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getSession( - sessionId: String - ): Response { - val path = "/account/sessions/{sessionId}".replace("{sessionId}", sessionId) - val params = mapOf( - ) - val headers = mapOf( - "content-type" to "application/json" - ) - return client.call("GET", path, headers, params) - } - /** - * Delete Account Session - * - * Use this endpoint to log out the currently logged in user from all their - * account sessions across all of their different devices. When using the - * option id argument, only the session unique ID provider will be deleted. + * Sends the user an SMS with a secret key for creating a session. If the provided user ID has not be registered, a new user will be created. Use the returned user ID and secret and submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's phone is valid for 15 minutes. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * @param sessionId - * @return [Response] + * @param userId Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored. + * @param phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @return [io.appwrite.models.Token] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun deleteSession( - sessionId: String - ): Response { - val path = "/account/sessions/{sessionId}".replace("{sessionId}", sessionId) - val params = mapOf( - ) + suspend fun createPhoneToken( + userId: String, + phone: String, + ): io.appwrite.models.Token { + val apiPath = "/account/tokens/phone" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "userId" to userId, + "phone" to phone, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, ) - - return client.call("DELETE", path, headers, params) } - + + /** - * Create Email Verification - * - * Use this endpoint to send a verification message to your user email address - * to confirm they are the valid owners of that address. Both the **userId** - * and **secret** arguments will be passed as query parameters to the URL you - * have provided to be attached to the verification email. The provided URL - * should redirect the user back to your app and allow you to complete the - * verification process by verifying both the **userId** and **secret** - * parameters. Learn more about how to [complete the verification - * process](/docs/client/account#accountUpdateVerification). The verification - * link sent to the user's email address is valid for 7 days. + * Use this endpoint to send a verification message to your user email address to confirm they are the valid owners of that address. Both the **userId** and **secret** arguments will be passed as query parameters to the URL you have provided to be attached to the verification email. The provided URL should redirect the user back to your app and allow you to complete the verification process by verifying both the **userId** and **secret** parameters. Learn more about how to [complete the verification process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). The verification link sent to the user's email address is valid for 7 days. * - * Please note that in order to avoid a [Redirect - * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - * the only valid redirect URLs are the ones from domains you have set when - * adding your platforms in the console interface. + * 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. * * - * @param url - * @return [Response] + * @param url URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @return [io.appwrite.models.Token] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun createVerification( - url: String - ): Response { - val path = "/account/verification" - val params = mapOf( - "url" to url - ) + url: String, + ): io.appwrite.models.Token { + val apiPath = "/account/verification" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "url" to url, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - + + /** - * Create Email Verification (confirmation) - * - * Use this endpoint to complete the user email verification process. Use both - * the **userId** and **secret** parameters that were attached to your app URL - * to verify the user email ownership. If confirmed this route will return a - * 200 status code. + * 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. * - * @param userId - * @param secret - * @return [Response] + * @param userId User ID. + * @param secret Valid verification token. + * @return [io.appwrite.models.Token] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun updateVerification( - userId: String, - secret: String - ): Response { - val path = "/account/verification" - val params = mapOf( + userId: String, + secret: String, + ): io.appwrite.models.Token { + val apiPath = "/account/verification" + + val apiParams = mutableMapOf( "userId" to userId, - "secret" to secret + "secret" to secret, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, ) + } + + + /** + * Use this endpoint to send a verification SMS to the currently logged in user. This endpoint is meant for use after updating a user's phone number using the [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) endpoint. Learn more about how to [complete the verification process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). The verification code sent to the user's phone number is valid for 15 minutes. + * + * @return [io.appwrite.models.Token] + */ + suspend fun createPhoneVerification( + ): io.appwrite.models.Token { + val apiPath = "/account/verification/phone" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, + ) + } + + + /** + * 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. + * + * @param userId User ID. + * @param secret Valid verification token. + * @return [io.appwrite.models.Token] + */ + suspend fun updatePhoneVerification( + userId: String, + secret: String, + ): io.appwrite.models.Token { + val apiPath = "/account/verification/phone" - return client.call("PUT", path, headers, params) + val apiParams = mutableMapOf( + "userId" to userId, + "secret" to secret, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Token = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Token.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Token::class.java, + converter, + ) } - + + } \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Avatars.kt b/library/src/main/java/io/appwrite/services/Avatars.kt index 3e0432f..ed7e7fa 100644 --- a/library/src/main/java/io/appwrite/services/Avatars.kt +++ b/library/src/main/java/io/appwrite/services/Avatars.kt @@ -2,240 +2,264 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import okhttp3.Cookie -import okhttp3.Response import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import java.io.File +/** + * The Avatars service aims to help you complete everyday tasks related to your app image, icons, and avatars. + */ class Avatars(client: Client) : Service(client) { /** - * Get Browser Icon - * - * You can use this endpoint to show different browser icons to your users. - * The code argument receives the browser code as it appears in your user - * /account/sessions endpoint. Use width, height and quality arguments to - * change the output settings. + * You can use this endpoint to show different browser icons to your users. The code argument receives the browser code as it appears in your user [GET /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) endpoint. Use width, height and quality arguments to change the output settings. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * - * @param code - * @param width - * @param height - * @param quality - * @return [Response] + * @param code Browser Code. + * @param width Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param height Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param quality Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getBrowser( - code: String, - width: Int? = null, - height: Int? = null, - quality: Int? = null - ): Response { - val path = "/avatars/browsers/{code}".replace("{code}", code) - val params = mapOf( + code: io.appwrite.enums.Browser, + width: Long? = null, + height: Long? = null, + quality: Long? = null, + ): ByteArray { + val apiPath = "/avatars/browsers/{code}" + .replace("{code}", code.value) + + val apiParams = mutableMapOf( "width" to width, "height" to height, "quality" to quality, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get Credit Card Icon - * - * The credit card endpoint will return you the icon of the credit card - * provider you need. Use width, height and quality arguments to change the - * output settings. + * 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. + * * - * @param code - * @param width - * @param height - * @param quality - * @return [Response] + * @param code Credit Card Code. Possible values: amex, argencard, cabal, cencosud, diners, discover, elo, hipercard, jcb, mastercard, naranja, targeta-shopping, union-china-pay, visa, mir, maestro, rupay. + * @param width Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param height Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param quality Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getCreditCard( - code: String, - width: Int? = null, - height: Int? = null, - quality: Int? = null - ): Response { - val path = "/avatars/credit-cards/{code}".replace("{code}", code) - val params = mapOf( + code: io.appwrite.enums.CreditCard, + width: Long? = null, + height: Long? = null, + quality: Long? = null, + ): ByteArray { + val apiPath = "/avatars/credit-cards/{code}" + .replace("{code}", code.value) + + val apiParams = mutableMapOf( "width" to width, "height" to height, "quality" to quality, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get Favicon - * - * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - * website URL. + * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote website URL. * + * This endpoint does not follow HTTP redirects. * - * @param url - * @return [Response] + * @param url Website URL which you want to fetch the favicon from. + * @return [ByteArray] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFavicon( - url: String - ): Response { - val path = "/avatars/favicon" - val params = mapOf( + url: String, + ): ByteArray { + val apiPath = "/avatars/favicon" + + val apiParams = mutableMapOf( "url" to url, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get Country Flag - * - * You can use this endpoint to show different country flags icons to your - * users. The code argument receives the 2 letter country code. Use width, - * height and quality arguments to change the output settings. + * 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. + * * - * @param code - * @param width - * @param height - * @param quality - * @return [Response] + * @param code Country Code. ISO Alpha-2 country code format. + * @param width Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param height Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param quality Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFlag( - code: String, - width: Int? = null, - height: Int? = null, - quality: Int? = null - ): Response { - val path = "/avatars/flags/{code}".replace("{code}", code) - val params = mapOf( + code: io.appwrite.enums.Flag, + width: Long? = null, + height: Long? = null, + quality: Long? = null, + ): ByteArray { + val apiPath = "/avatars/flags/{code}" + .replace("{code}", code.value) + + val apiParams = mutableMapOf( "width" to width, "height" to height, "quality" to quality, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get Image from URL - * - * Use this endpoint to fetch a remote image URL and crop it to any image size - * you want. This endpoint is very useful if you need to crop and display - * remote images in your app or in case you want to make sure a 3rd party - * image is properly served using a TLS protocol. + * 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. * - * @param url - * @param width - * @param height - * @return [Response] + * @param url Image URL which you want to crop. + * @param width Resize preview image width, Pass an integer between 0 to 2000. Defaults to 400. + * @param height Resize preview image height, Pass an integer between 0 to 2000. Defaults to 400. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getImage( - url: String, - width: Int? = null, - height: Int? = null - ): Response { - val path = "/avatars/image" - val params = mapOf( + url: String, + width: Long? = null, + height: Long? = null, + ): ByteArray { + val apiPath = "/avatars/image" + + val apiParams = mutableMapOf( "url" to url, "width" to width, "height" to height, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get User Initials - * - * Use this endpoint to show your user initials avatar icon on your website or - * app. By default, this route will try to print your logged-in user name or - * email initials. You can also overwrite the user name if you pass the 'name' - * parameter. If no name is given and no user is logged, an empty avatar will - * be returned. + * Use this endpoint to show your user initials avatar icon on your website or app. By default, this route will try to print your logged-in user name or email initials. You can also overwrite the user name if you pass the 'name' parameter. If no name is given and no user is logged, an empty avatar will be returned. + * + * You can use the color and background params to change the avatar colors. By default, a random theme will be selected. The random theme will persist for the user's initials when reloading the same theme will always return for the same initials. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * - * 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. * - * @param name - * @param width - * @param height - * @param color - * @param background - * @return [Response] + * @param name Full Name. When empty, current user name or email will be used. Max length: 128 chars. + * @param width Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param height Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param background Changes background color. By default a random color will be picked and stay will persistent to the given name. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getInitials( - name: String? = null, - width: Int? = null, - height: Int? = null, - color: String? = null, - background: String? = null - ): Response { - val path = "/avatars/initials" - val params = mapOf( + name: String? = null, + width: Long? = null, + height: Long? = null, + background: String? = null, + ): ByteArray { + val apiPath = "/avatars/initials" + + val apiParams = mutableMapOf( "name" to name, "width" to width, "height" to height, - "color" to color, "background" to background, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get QR Code - * - * Converts a given plain text to a QR code image. You can use the query - * parameters to change the size and style of the resulting image. + * 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. + * * - * @param text - * @param size - * @param margin - * @param download - * @return [Response] + * @param text Plain text to be converted to QR code image. + * @param size QR code size. Pass an integer between 1 to 1000. Defaults to 400. + * @param margin Margin from edge. Pass an integer between 0 to 10. Defaults to 1. + * @param download Return resulting image with 'Content-Disposition: attachment ' headers for the browser to start downloading it. Pass 0 for no header, or 1 for otherwise. Default value is set to 0. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getQR( - text: String, - size: Int? = null, - margin: Int? = null, - download: Boolean? = null - ): Response { - val path = "/avatars/qr" - val params = mapOf( + text: String, + size: Long? = null, + margin: Long? = null, + download: Boolean? = null, + ): ByteArray { + val apiPath = "/avatars/qr" + + val apiParams = mutableMapOf( "text" to text, "size" to size, "margin" to margin, "download" to download, - "project" to client.config["project"] + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + } \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Database.kt b/library/src/main/java/io/appwrite/services/Database.kt deleted file mode 100644 index 6333532..0000000 --- a/library/src/main/java/io/appwrite/services/Database.kt +++ /dev/null @@ -1,196 +0,0 @@ -package io.appwrite.services - -import android.net.Uri -import io.appwrite.Client -import io.appwrite.exceptions.AppwriteException -import okhttp3.Cookie -import okhttp3.Response -import java.io.File - -class Database(client: Client) : Service(client) { - - /** - * List Documents - * - * Get a list of all the user documents. You can use the query params to - * filter your results. On admin mode, this endpoint will return a list of all - * of the project's documents. [Learn more about different API - * modes](/docs/admin). - * - * @param collectionId - * @param filters - * @param limit - * @param offset - * @param orderField - * @param orderType - * @param orderCast - * @param search - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun listDocuments( - collectionId: String, - filters: List? = null, - limit: Int? = null, - offset: Int? = null, - orderField: String? = null, - orderType: String? = null, - orderCast: String? = null, - search: String? = null - ): Response { - val path = "/database/collections/{collectionId}/documents".replace("{collectionId}", collectionId) - val params = mapOf( - "filters" to filters, - "limit" to limit, - "offset" to offset, - "orderField" to orderField, - "orderType" to orderType, - "orderCast" to orderCast, - "search" to search - ) - - val headers = mapOf( - "content-type" to "application/json" - ) - - return client.call("GET", path, headers, params) - } - - /** - * Create Document - * - * Create a new Document. Before using this route, you should create a new - * collection resource using either a [server - * integration](/docs/server/database#databaseCreateCollection) API or - * directly from your database console. - * - * @param collectionId - * @param data - * @param read - * @param write - * @param parentDocument - * @param parentProperty - * @param parentPropertyType - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun createDocument( - collectionId: String, - data: Any, - read: List? = null, - write: List? = null, - parentDocument: String? = null, - parentProperty: String? = null, - parentPropertyType: String? = null - ): Response { - val path = "/database/collections/{collectionId}/documents".replace("{collectionId}", collectionId) - val params = mapOf( - "data" to data, - "read" to read, - "write" to write, - "parentDocument" to parentDocument, - "parentProperty" to parentProperty, - "parentPropertyType" to parentPropertyType - ) - - val headers = mapOf( - "content-type" to "application/json" - ) - - return client.call("POST", path, headers, params) - } - - /** - * Get Document - * - * Get a document by its unique ID. This endpoint response returns a JSON - * object with the document data. - * - * @param collectionId - * @param documentId - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getDocument( - collectionId: String, - documentId: String - ): Response { - val path = "/database/collections/{collectionId}/documents/{documentId}".replace("{collectionId}", collectionId).replace("{documentId}", documentId) - val params = mapOf( - ) - - val headers = mapOf( - "content-type" to "application/json" - ) - - return client.call("GET", path, headers, params) - } - - /** - * Update Document - * - * Update a document by its unique ID. Using the patch method you can pass - * only specific fields that will get updated. - * - * @param collectionId - * @param documentId - * @param data - * @param read - * @param write - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateDocument( - collectionId: String, - documentId: String, - data: Any, - read: List? = null, - write: List? = null - ): Response { - val path = "/database/collections/{collectionId}/documents/{documentId}".replace("{collectionId}", collectionId).replace("{documentId}", documentId) - val params = mapOf( - "data" to data, - "read" to read, - "write" to write - ) - - val headers = mapOf( - "content-type" to "application/json" - ) - - return client.call("PATCH", path, headers, params) - } - - /** - * Delete Document - * - * Delete a document by its unique ID. This endpoint deletes only the parent - * documents, its attributes and relations to other documents. Child documents - * **will not** be deleted. - * - * @param collectionId - * @param documentId - * @return [Response] - */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun deleteDocument( - collectionId: String, - documentId: String - ): Response { - val path = "/database/collections/{collectionId}/documents/{documentId}".replace("{collectionId}", collectionId).replace("{documentId}", documentId) - val params = mapOf( - ) - - val headers = mapOf( - "content-type" to "application/json" - ) - - return client.call("DELETE", path, headers, params) - } - -} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Databases.kt b/library/src/main/java/io/appwrite/services/Databases.kt new file mode 100644 index 0000000..9be75a3 --- /dev/null +++ b/library/src/main/java/io/appwrite/services/Databases.kt @@ -0,0 +1,607 @@ +package io.appwrite.services + +import android.net.Uri +import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* +import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf +import okhttp3.Cookie +import java.io.File + +/** + * The Databases service allows you to create structured collections of documents, query and filter lists of documents + */ +class Databases(client: Client) : Service(client) { + + /** + * Get a list of all the user's documents in a given collection. You can use the query params to filter your results. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.DocumentList] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.listRows") + ) + @JvmOverloads + suspend fun listDocuments( + databaseId: String, + collectionId: String, + queries: List? = null, + nestedType: Class, + ): io.appwrite.models.DocumentList { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.DocumentList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.DocumentList.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get a list of all the user's documents in a given collection. You can use the query params to filter your results. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.DocumentList] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.listRows") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun listDocuments( + databaseId: String, + collectionId: String, + queries: List? = null, + ): io.appwrite.models.DocumentList> = listDocuments( + databaseId, + collectionId, + queries, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. + * @param documentId Document ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param data Document data as JSON object. + * @param permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.createRow") + ) + @JvmOverloads + suspend fun createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + + val apiParams = mutableMapOf( + "documentId" to documentId, + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * 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. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. + * @param documentId Document ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param data Document data as JSON object. + * @param permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.createRow") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: List? = null, + ): io.appwrite.models.Document> = createDocument( + databaseId, + collectionId, + documentId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Get a document by its unique ID. This endpoint response returns a JSON object with the document data. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param documentId Document ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.getRow") + ) + @JvmOverloads + suspend fun getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: List? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get a document by its unique ID. This endpoint response returns a JSON object with the document data. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param documentId Document ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.getRow") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: List? = null, + ): io.appwrite.models.Document> = getDocument( + databaseId, + collectionId, + documentId, + queries, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param data Document data as JSON object. Include all required attributes of the document to be created or updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.upsertRow") + ) + @JvmOverloads + suspend fun upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + + val apiParams = mutableMapOf( + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * 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. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param data Document data as JSON object. Include all required attributes of the document to be created or updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.upsertRow") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: List? = null, + ): io.appwrite.models.Document> = upsertDocument( + databaseId, + collectionId, + documentId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Update a document by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param data Document data as JSON object. Include only attribute and value pairs to be updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.updateRow") + ) + @JvmOverloads + suspend fun updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = null, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + + val apiParams = mutableMapOf( + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Update a document by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param data Document data as JSON object. Include only attribute and value pairs to be updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.updateRow") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = null, + permissions: List? = null, + ): io.appwrite.models.Document> = updateDocument( + databaseId, + collectionId, + documentId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Delete a document by its unique ID. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param documentId Document ID. + * @return [Any] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.deleteRow") + ) + suspend fun deleteDocument( + databaseId: String, + collectionId: String, + documentId: String, + ): Any { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Decrement a specific attribute of a document by a given value. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param attribute Attribute key. + * @param value Value to increment the attribute by. The value must be a number. + * @param min Minimum value for the attribute. If the current value is lesser than this value, an exception will be thrown. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.decrementRowColumn") + ) + @JvmOverloads + suspend fun decrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = null, + min: Double? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + .replace("{attribute}", attribute) + + val apiParams = mutableMapOf( + "value" to value, + "min" to min, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Decrement a specific attribute of a document by a given value. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param attribute Attribute key. + * @param value Value to increment the attribute by. The value must be a number. + * @param min Minimum value for the attribute. If the current value is lesser than this value, an exception will be thrown. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.decrementRowColumn") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun decrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = null, + min: Double? = null, + ): io.appwrite.models.Document> = decrementDocumentAttribute( + databaseId, + collectionId, + documentId, + attribute, + value, + min, + nestedType = classOf(), + ) + + /** + * Increment a specific attribute of a document by a given value. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param attribute Attribute key. + * @param value Value to increment the attribute by. The value must be a number. + * @param max Maximum value for the attribute. If the current value is greater than this value, an error will be thrown. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.incrementRowColumn") + ) + @JvmOverloads + suspend fun incrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = null, + max: Double? = null, + nestedType: Class, + ): io.appwrite.models.Document { + val apiPath = "/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment" + .replace("{databaseId}", databaseId) + .replace("{collectionId}", collectionId) + .replace("{documentId}", documentId) + .replace("{attribute}", attribute) + + val apiParams = mutableMapOf( + "value" to value, + "max" to max, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Document = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Document.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Increment a specific attribute of a document by a given value. + * + * @param databaseId Database ID. + * @param collectionId Collection ID. + * @param documentId Document ID. + * @param attribute Attribute key. + * @param value Value to increment the attribute by. The value must be a number. + * @param max Maximum value for the attribute. If the current value is greater than this value, an error will be thrown. + * @return [io.appwrite.models.Document] + */ + @Deprecated( + message = "This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead.", + replaceWith = ReplaceWith("io.appwrite.services.TablesDB.incrementRowColumn") + ) + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun incrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = null, + max: Double? = null, + ): io.appwrite.models.Document> = incrementDocumentAttribute( + databaseId, + collectionId, + documentId, + attribute, + value, + max, + nestedType = classOf(), + ) + +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Functions.kt b/library/src/main/java/io/appwrite/services/Functions.kt index 95a915f..b938581 100644 --- a/library/src/main/java/io/appwrite/services/Functions.kt +++ b/library/src/main/java/io/appwrite/services/Functions.kt @@ -2,106 +2,137 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import okhttp3.Cookie -import okhttp3.Response import java.io.File +/** + * The Functions Service allows you view, create and manage your Cloud Functions. + */ class Functions(client: Client) : Service(client) { /** - * List Executions + * Get a list of all the current user function execution logs. You can use the query params to filter your results. * - * Get a list of all the current user function execution logs. You can use the - * query params to filter your results. On admin mode, this endpoint will - * return a list of all of the project's executions. [Learn more about - * different API modes](/docs/admin). - * - * @param functionId - * @param search - * @param limit - * @param offset - * @param orderType - * @return [Response] + * @param functionId Function ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId + * @return [io.appwrite.models.ExecutionList] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun listExecutions( - functionId: String, - search: String? = null, - limit: Int? = null, - offset: Int? = null, - orderType: String? = null - ): Response { - val path = "/functions/{functionId}/executions".replace("{functionId}", functionId) - val params = mapOf( - "search" to search, - "limit" to limit, - "offset" to offset, - "orderType" to orderType - ) + functionId: String, + queries: List? = null, + ): io.appwrite.models.ExecutionList { + val apiPath = "/functions/{functionId}/executions" + .replace("{functionId}", functionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.ExecutionList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.ExecutionList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.ExecutionList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * Create Execution - * - * Trigger a function execution. The returned object will return you the - * current execution status. You can ping the `Get Execution` endpoint to get - * updates on the current execution status. Once this endpoint is called, your - * function execution process will start asynchronously. + * 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. * - * @param functionId - * @param data - * @return [Response] + * @param functionId Function ID. + * @param body HTTP body of execution. Default value is empty string. + * @param async Execute code in the background. Default value is false. + * @param path HTTP path of execution. Path can include query params. Default value is / + * @param method HTTP method of execution. Default value is GET. + * @param headers HTTP headers of execution. Defaults to empty. + * @param scheduledAt Scheduled execution time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future with precision in minutes. + * @return [io.appwrite.models.Execution] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun createExecution( - functionId: String, - data: String? = null - ): Response { - val path = "/functions/{functionId}/executions".replace("{functionId}", functionId) - val params = mapOf( - "data" to data - ) + functionId: String, + body: String? = null, + async: Boolean? = null, + path: String? = null, + method: io.appwrite.enums.ExecutionMethod? = null, + headers: Any? = null, + scheduledAt: String? = null, + ): io.appwrite.models.Execution { + val apiPath = "/functions/{functionId}/executions" + .replace("{functionId}", functionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "body" to body, + "async" to async, + "path" to path, + "method" to method, + "headers" to headers, + "scheduledAt" to scheduledAt, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Execution = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Execution.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Execution::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - + + /** - * Get Execution - * * Get a function execution log by its unique ID. * - * @param functionId - * @param executionId - * @return [Response] + * @param functionId Function ID. + * @param executionId Execution ID. + * @return [io.appwrite.models.Execution] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun getExecution( - functionId: String, - executionId: String - ): Response { - val path = "/functions/{functionId}/executions/{executionId}".replace("{functionId}", functionId).replace("{executionId}", executionId) - val params = mapOf( - ) + functionId: String, + executionId: String, + ): io.appwrite.models.Execution { + val apiPath = "/functions/{functionId}/executions/{executionId}" + .replace("{functionId}", functionId) + .replace("{executionId}", executionId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Execution = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Execution.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Execution::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + } \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Graphql.kt b/library/src/main/java/io/appwrite/services/Graphql.kt new file mode 100644 index 0000000..895b9d6 --- /dev/null +++ b/library/src/main/java/io/appwrite/services/Graphql.kt @@ -0,0 +1,82 @@ +package io.appwrite.services + +import android.net.Uri +import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* +import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf +import okhttp3.Cookie +import java.io.File + +/** + * The GraphQL API allows you to query and mutate your Appwrite server using GraphQL. + */ +class Graphql(client: Client) : Service(client) { + + /** + * Execute a GraphQL mutation. + * + * @param query The query or queries to execute. + * @return [Any] + */ + suspend fun query( + query: Any, + ): Any { + val apiPath = "/graphql" + + val apiParams = mutableMapOf( + "query" to query, + ) + val apiHeaders = mutableMapOf( + "x-sdk-graphql" to "true", + "content-type" to "application/json", + ) + val converter: (Any) -> Any = { + it + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + converter, + ) + } + + + /** + * Execute a GraphQL mutation. + * + * @param query The query or queries to execute. + * @return [Any] + */ + suspend fun mutation( + query: Any, + ): Any { + val apiPath = "/graphql/mutation" + + val apiParams = mutableMapOf( + "query" to query, + ) + val apiHeaders = mutableMapOf( + "x-sdk-graphql" to "true", + "content-type" to "application/json", + ) + val converter: (Any) -> Any = { + it + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + converter, + ) + } + + +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Locale.kt b/library/src/main/java/io/appwrite/services/Locale.kt index 415df78..aecc83a 100644 --- a/library/src/main/java/io/appwrite/services/Locale.kt +++ b/library/src/main/java/io/appwrite/services/Locale.kt @@ -2,170 +2,243 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import okhttp3.Cookie -import okhttp3.Response import java.io.File +/** + * The Locale service allows you to customize your app based on your users' location. + */ class Locale(client: Client) : Service(client) { /** - * Get User Locale - * - * Get the current user location based on IP. Returns an object with user - * country code, country name, continent name, continent code, ip address and - * suggested currency. You can use the locale header to get the data in a - * supported language. + * Get the current user location based on IP. Returns an object with user country code, country name, continent name, continent code, ip address and suggested currency. You can use the locale header to get the data in a supported language. * * ([IP Geolocation by DB-IP](https://db-ip.com)) * - * @return [Response] + * @return [io.appwrite.models.Locale] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun get(): Response { - val path = "/locale" - val params = mapOf( - ) + suspend fun get( + ): io.appwrite.models.Locale { + val apiPath = "/locale" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Locale = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Locale.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Locale::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List Continents - * - * List of all continents. You can use the locale header to get the data in a - * supported language. + * List of all locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). * - * @return [Response] + * @return [io.appwrite.models.LocaleCodeList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getContinents(): Response { - val path = "/locale/continents" - val params = mapOf( - ) + suspend fun listCodes( + ): io.appwrite.models.LocaleCodeList { + val apiPath = "/locale/codes" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.LocaleCodeList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.LocaleCodeList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.LocaleCodeList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List Countries - * - * List of all countries. You can use the locale header to get the data in a - * supported language. + * List of all continents. You can use the locale header to get the data in a supported language. * - * @return [Response] + * @return [io.appwrite.models.ContinentList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getCountries(): Response { - val path = "/locale/countries" - val params = mapOf( - ) + suspend fun listContinents( + ): io.appwrite.models.ContinentList { + val apiPath = "/locale/continents" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.ContinentList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.ContinentList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.ContinentList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List EU Countries - * - * List of all countries that are currently members of the EU. You can use the - * locale header to get the data in a supported language. + * List of all countries. You can use the locale header to get the data in a supported language. * - * @return [Response] + * @return [io.appwrite.models.CountryList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getCountriesEU(): Response { - val path = "/locale/countries/eu" - val params = mapOf( - ) + suspend fun listCountries( + ): io.appwrite.models.CountryList { + val apiPath = "/locale/countries" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.CountryList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.CountryList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.CountryList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List Countries Phone Codes - * - * List of all countries phone codes. You can use the locale header to get the - * data in a supported language. + * 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. * - * @return [Response] + * @return [io.appwrite.models.CountryList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getCountriesPhones(): Response { - val path = "/locale/countries/phones" - val params = mapOf( - ) + suspend fun listCountriesEU( + ): io.appwrite.models.CountryList { + val apiPath = "/locale/countries/eu" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.CountryList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.CountryList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.CountryList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List Currencies - * - * List of all currencies, including currency symbol, name, plural, and - * decimal digits for all major and minor currencies. You can use the locale - * header to get the data in a supported language. + * List of all countries phone codes. You can use the locale header to get the data in a supported language. * - * @return [Response] + * @return [io.appwrite.models.PhoneList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getCurrencies(): Response { - val path = "/locale/currencies" - val params = mapOf( - ) + suspend fun listCountriesPhones( + ): io.appwrite.models.PhoneList { + val apiPath = "/locale/countries/phones" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.PhoneList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.PhoneList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.PhoneList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * List Languages - * - * List of all languages classified by ISO 639-1 including 2-letter code, name - * in English, and name in the respective language. + * 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. * - * @return [Response] + * @return [io.appwrite.models.CurrencyList] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getLanguages(): Response { - val path = "/locale/languages" - val params = mapOf( - ) + suspend fun listCurrencies( + ): io.appwrite.models.CurrencyList { + val apiPath = "/locale/currencies" - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( ) + val converter: (Any) -> io.appwrite.models.CurrencyList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.CurrencyList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.CurrencyList::class.java, + converter, + ) + } + + + /** + * List of all languages classified by ISO 639-1 including 2-letter code, name in English, and name in the respective language. + * + * @return [io.appwrite.models.LanguageList] + */ + suspend fun listLanguages( + ): io.appwrite.models.LanguageList { + val apiPath = "/locale/languages" - return client.call("GET", path, headers, params) + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.LanguageList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.LanguageList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.LanguageList::class.java, + converter, + ) } - + + } \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Messaging.kt b/library/src/main/java/io/appwrite/services/Messaging.kt new file mode 100644 index 0000000..148618e --- /dev/null +++ b/library/src/main/java/io/appwrite/services/Messaging.kt @@ -0,0 +1,86 @@ +package io.appwrite.services + +import android.net.Uri +import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* +import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf +import okhttp3.Cookie +import java.io.File + +/** + * The Messaging service allows you to send messages to any provider type (SMTP, push notification, SMS, etc.). + */ +class Messaging(client: Client) : Service(client) { + + /** + * Create a new subscriber. + * + * @param topicId Topic ID. The topic ID to subscribe to. + * @param subscriberId Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID. + * @param targetId Target ID. The target ID to link to the specified Topic ID. + * @return [io.appwrite.models.Subscriber] + */ + suspend fun createSubscriber( + topicId: String, + subscriberId: String, + targetId: String, + ): io.appwrite.models.Subscriber { + val apiPath = "/messaging/topics/{topicId}/subscribers" + .replace("{topicId}", topicId) + + val apiParams = mutableMapOf( + "subscriberId" to subscriberId, + "targetId" to targetId, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Subscriber = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Subscriber.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Subscriber::class.java, + converter, + ) + } + + + /** + * Delete a subscriber by its unique ID. + * + * @param topicId Topic ID. The topic ID subscribed to. + * @param subscriberId Subscriber ID. + * @return [Any] + */ + suspend fun deleteSubscriber( + topicId: String, + subscriberId: String, + ): Any { + val apiPath = "/messaging/topics/{topicId}/subscribers/{subscriberId}" + .replace("{topicId}", topicId) + .replace("{subscriberId}", subscriberId) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Realtime.kt b/library/src/main/java/io/appwrite/services/Realtime.kt index cec1dad..b06eacf 100644 --- a/library/src/main/java/io/appwrite/services/Realtime.kt +++ b/library/src/main/java/io/appwrite/services/Realtime.kt @@ -1,5 +1,6 @@ package io.appwrite.services +import io.appwrite.Service import io.appwrite.Client import io.appwrite.exceptions.AppwriteException import io.appwrite.extensions.forEachAsync @@ -15,6 +16,7 @@ import okhttp3.WebSocketListener import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.ws.RealWebSocket import java.util.* +import android.util.Log import kotlin.coroutines.CoroutineContext class Realtime(client: Client) : Service(client), CoroutineScope { @@ -27,30 +29,43 @@ class Realtime(client: Client) : Service(client), CoroutineScope { private companion object { private const val TYPE_ERROR = "error" private const val TYPE_EVENT = "event" + private const val TYPE_PONG = "pong" + private const val HEARTBEAT_INTERVAL = 20_000L // 20 seconds private const val DEBOUNCE_MILLIS = 1L private var socket: RealWebSocket? = null - private var channelCallbacks = mutableMapOf>() - private var errorCallbacks = mutableSetOf<(AppwriteException) -> Unit>() + private var activeChannels = mutableSetOf() + private var activeSubscriptions = mutableMapOf() private var subCallDepth = 0 + private var reconnectAttempts = 0 + private var subscriptionsCounter = 0 + private var reconnect = true + private var heartbeatJob: Job? = null } private fun createSocket() { + if (activeChannels.isEmpty()) { + reconnect = false + closeSocket() + return + } + val queryParamBuilder = StringBuilder() .append("project=${client.config["project"]}") - channelCallbacks.keys.forEach { + activeChannels.forEach { queryParamBuilder .append("&channels[]=$it") } val request = Request.Builder() - .url("${client.endPointRealtime}/realtime?$queryParamBuilder") + .url("${client.endpointRealtime}/realtime?$queryParamBuilder") .build() if (socket != null) { + reconnect = false closeSocket() } @@ -68,9 +83,32 @@ class Realtime(client: Client) : Service(client), CoroutineScope { } private fun closeSocket() { + stopHeartbeat() socket?.close(RealtimeCode.POLICY_VIOLATION.value, null) } + private fun startHeartbeat() { + stopHeartbeat() + heartbeatJob = launch { + while (isActive) { + delay(HEARTBEAT_INTERVAL) + socket?.send("""{"type":"ping"}""") + } + } + } + + private fun stopHeartbeat() { + heartbeatJob?.cancel() + heartbeatJob = null + } + + private fun getTimeout() = when { + reconnectAttempts < 5 -> 1000L + reconnectAttempts < 15 -> 5000L + reconnectAttempts < 100 -> 10000L + else -> 60000L + } + fun subscribe( vararg channels: String, callback: (RealtimeResponseEvent) -> Unit, @@ -85,20 +123,14 @@ class Realtime(client: Client) : Service(client), CoroutineScope { payloadType: Class, callback: (RealtimeResponseEvent) -> Unit, ): RealtimeSubscription { - channels.forEach { - if (!channelCallbacks.containsKey(it)) { - channelCallbacks[it] = mutableListOf( - RealtimeCallback( - payloadType, - callback as (RealtimeResponseEvent<*>) -> Unit - ) - ) - return@forEach - } - channelCallbacks[it]?.add( - RealtimeCallback(payloadType, callback as (RealtimeResponseEvent<*>) -> Unit) - ) - } + val counter = subscriptionsCounter++ + + activeChannels.addAll(channels) + activeSubscriptions[counter] = RealtimeCallback( + channels.toList(), + payloadType, + callback as (RealtimeResponseEvent<*>) -> Unit + ) launch { subCallDepth++ @@ -109,25 +141,32 @@ class Realtime(client: Client) : Service(client), CoroutineScope { subCallDepth-- } - return RealtimeSubscription { unsubscribe(*channels) } - } - - fun unsubscribe(vararg channels: String) { - channels.forEach { - channelCallbacks[it] = mutableListOf() - } - if (channelCallbacks.all { it.value.isEmpty() }) { - errorCallbacks = mutableSetOf() - closeSocket() + return RealtimeSubscription { + activeSubscriptions.remove(counter) + cleanUp(*channels) + createSocket() } } - fun doOnError(callback: (AppwriteException) -> Unit) { - errorCallbacks.add(callback) + private fun cleanUp(vararg channels: String) { + activeChannels.removeAll { channel -> + if (!channels.contains(channel)) { + return@removeAll false + } + activeSubscriptions.values.none { callback -> + callback.channels.contains(channel) + } + } } private inner class AppwriteWebSocketListener : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + super.onOpen(webSocket, response) + reconnectAttempts = 0 + startHeartbeat() + } + override fun onMessage(webSocket: WebSocket, text: String) { super.onMessage(webSocket, text) @@ -136,38 +175,57 @@ class Realtime(client: Client) : Service(client), CoroutineScope { when (message.type) { TYPE_ERROR -> handleResponseError(message) TYPE_EVENT -> handleResponseEvent(message) + TYPE_PONG -> {} } } } private fun handleResponseError(message: RealtimeResponse) { - val error = message.data.jsonCast() - errorCallbacks.forEach { it.invoke(error) } + throw message.data?.jsonCast() ?: RuntimeException("Data is not present") } private suspend fun handleResponseEvent(message: RealtimeResponse) { - val event = message.data.jsonCast>() - event.channels.forEachAsync { channel -> - channelCallbacks[channel]?.forEachAsync { callbackWrapper -> - event.payload = event.payload.jsonCast(callbackWrapper.payloadClass) - callbackWrapper.callback.invoke(event) + val event = message.data?.jsonCast>() ?: return + if (event.channels.isEmpty()) { + return + } + if (!event.channels.any { activeChannels.contains(it) }) { + return + } + activeSubscriptions.values.forEachAsync { subscription -> + if (event.channels.any { subscription.channels.contains(it) }) { + event.payload = event.payload.jsonCast(subscription.payloadClass) + subscription.callback(event) } } } override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { super.onClosing(webSocket, code, reason) - if (code == RealtimeCode.POLICY_VIOLATION.value) { + stopHeartbeat() + if (!reconnect || code == RealtimeCode.POLICY_VIOLATION.value) { + reconnect = true return } + + val timeout = getTimeout() + + Log.e( + this@Realtime::class.java.name, + "Realtime disconnected. Re-connecting in ${timeout / 1000} seconds.", + AppwriteException(reason, code) + ) + launch { - delay(1000) + delay(timeout) + reconnectAttempts++ createSocket() } } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { super.onFailure(webSocket, t, response) + stopHeartbeat() t.printStackTrace() } } diff --git a/library/src/main/java/io/appwrite/services/Service.kt b/library/src/main/java/io/appwrite/services/Service.kt deleted file mode 100644 index 6a00fb1..0000000 --- a/library/src/main/java/io/appwrite/services/Service.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.appwrite.services - -import io.appwrite.Client - -abstract class Service(val client: Client) diff --git a/library/src/main/java/io/appwrite/services/Storage.kt b/library/src/main/java/io/appwrite/services/Storage.kt index 777b759..daa79a4 100644 --- a/library/src/main/java/io/appwrite/services/Storage.kt +++ b/library/src/main/java/io/appwrite/services/Storage.kt @@ -2,228 +2,291 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import okhttp3.Cookie -import okhttp3.Response import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import java.io.File +/** + * The Storage service allows you to manage your project files. + */ class Storage(client: Client) : Service(client) { /** - * List Files + * Get a list of all the user files. You can use the query params to filter your results. * - * Get a list of all the user files. You can use the query params to filter - * your results. On admin mode, this endpoint will return a list of all of the - * project's files. [Learn more about different API modes](/docs/admin). - * - * @param search - * @param limit - * @param offset - * @param orderType - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, signature, mimeType, sizeOriginal, chunksTotal, chunksUploaded + * @param search Search term to filter your list results. Max length: 256 chars. + * @return [io.appwrite.models.FileList] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun listFiles( - search: String? = null, - limit: Int? = null, - offset: Int? = null, - orderType: String? = null - ): Response { - val path = "/storage/files" - val params = mapOf( + bucketId: String, + queries: List? = null, + search: String? = null, + ): io.appwrite.models.FileList { + val apiPath = "/storage/buckets/{bucketId}/files" + .replace("{bucketId}", bucketId) + + val apiParams = mutableMapOf( + "queries" to queries, "search" to search, - "limit" to limit, - "offset" to offset, - "orderType" to orderType ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.FileList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.FileList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.FileList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * Create File + * Create a new file. Before using this route, you should create a new bucket resource using either a [server integration](https://appwrite.io/docs/server/storage#storageCreateBucket) API or directly from your Appwrite console. + * + * Larger files should be uploaded using multiple requests with the [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) header to send a partial request with a maximum supported chunk of `5MB`. The `content-range` header values should always be in bytes. + * + * When the first request is sent, the server will return the **File** object, and the subsequent part request must include the file's **id** in `x-appwrite-id` header to allow the server to know that the partial upload is for the existing file and not for a new one. + * + * If you're creating a new file using one of the Appwrite SDKs, all the chunking logic will be managed by the SDK internally. + * * - * Create a new file. The user who creates the file will automatically be - * assigned to read and write access unless he has passed custom values for - * read and write arguments. - * - * @param file - * @param read - * @param write - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param file Binary file. Appwrite SDKs provide helpers to handle file input. [Learn about file input](https://appwrite.io/docs/products/storage/upload-download#input-file). + * @param permissions An array of permission strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.File] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun createFile( - file: File, - read: List? = null, - write: List? = null - ): Response { - val path = "/storage/files" - val params = mapOf( + bucketId: String, + fileId: String, + file: InputFile, + permissions: List? = null, + onProgress: ((UploadProgress) -> Unit)? = null + ): io.appwrite.models.File { + val apiPath = "/storage/buckets/{bucketId}/files" + .replace("{bucketId}", bucketId) + + val apiParams = mutableMapOf( + "fileId" to fileId, "file" to file, - "read" to read, - "write" to write + "permissions" to permissions, ) - - val headers = mapOf( - "content-type" to "multipart/form-data" + val apiHeaders = mutableMapOf( + "content-type" to "multipart/form-data", + ) + val converter: (Any) -> io.appwrite.models.File = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.File.from(map = it as Map) + } + val idParamName: String? = "fileId" + val paramName = "file" + return client.chunkedUpload( + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.File::class.java, + converter, + paramName, + idParamName, + onProgress, ) - - return client.call("POST", path, headers, params) } - + + /** - * Get File + * Get a file by its unique ID. This endpoint response returns a JSON object with the file metadata. * - * Get a file by its unique ID. This endpoint response returns a JSON object - * with the file metadata. - * - * @param fileId - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID. + * @return [io.appwrite.models.File] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFile( - fileId: String - ): Response { - val path = "/storage/files/{fileId}".replace("{fileId}", fileId) - val params = mapOf( - ) + bucketId: String, + fileId: String, + ): io.appwrite.models.File { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.File = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.File.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.File::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * Update File - * - * Update a file by its unique ID. Only users with write permissions have - * access to update this resource. + * Update a file by its unique ID. Only users with write permissions have access to update this resource. * - * @param fileId - * @param read - * @param write - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File unique ID. + * @param name Name of the file + * @param permissions An array of permission string. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.File] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun updateFile( - fileId: String, - read: List, - write: List - ): Response { - val path = "/storage/files/{fileId}".replace("{fileId}", fileId) - val params = mapOf( - "read" to read, - "write" to write - ) + bucketId: String, + fileId: String, + name: String? = null, + permissions: List? = null, + ): io.appwrite.models.File { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + "name" to name, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.File = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.File.from(map = it as Map) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.File::class.java, + converter, ) - - return client.call("PUT", path, headers, params) } - + + /** - * Delete File - * - * Delete a file by its unique ID. Only users with write permissions have - * access to delete this resource. + * Delete a file by its unique ID. Only users with write permissions have access to delete this resource. * - * @param fileId - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID. + * @return [Any] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun deleteFile( - fileId: String - ): Response { - val path = "/storage/files/{fileId}".replace("{fileId}", fileId) - val params = mapOf( - ) + bucketId: String, + fileId: String, + ): Any { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, ) - - return client.call("DELETE", path, headers, params) } - + + /** - * Get File for Download + * Get a file content by its unique ID. The endpoint response return with a 'Content-Disposition: attachment' header that tells the browser to start downloading the file to user downloads directory. * - * 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. - * - * @param fileId - * @return [Response] + * @param bucketId Storage bucket ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID. + * @param token File token for accessing this file. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFileDownload( - fileId: String - ): Response { - val path = "/storage/files/{fileId}/download".replace("{fileId}", fileId) - val params = mapOf( - "project" to client.config["project"] - ) + bucketId: String, + fileId: String, + token: String? = null, + ): ByteArray { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}/download" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) - return client.call("GET", path, params = params) + val apiParams = mutableMapOf( + "token" to token, + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java + ) } - + + /** - * Get File Preview - * - * Get a file preview image. Currently, this method supports preview for image - * files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - * and spreadsheets, will return the file icon image. You can also pass query - * string arguments for cutting and resizing your preview image. + * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Preview is supported only for image files smaller than 10MB. * - * @param fileId - * @param width - * @param height - * @param gravity - * @param quality - * @param borderWidth - * @param borderColor - * @param borderRadius - * @param opacity - * @param rotation - * @param background - * @param output - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID + * @param width Resize preview image width, Pass an integer between 0 to 4000. + * @param height Resize preview image height, Pass an integer between 0 to 4000. + * @param gravity Image crop gravity. Can be one of center,top-left,top,top-right,left,right,bottom-left,bottom,bottom-right + * @param quality Preview image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @param borderWidth Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0. + * @param borderColor Preview image border color. Use a valid HEX color, no # is needed for prefix. + * @param borderRadius Preview image border radius in pixels. Pass an integer between 0 to 4000. + * @param opacity Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. + * @param rotation Preview image rotation in degrees. Pass an integer between -360 and 360. + * @param background Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. + * @param output Output format type (jpeg, jpg, png, gif and webp). + * @param token File token for accessing this file. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFilePreview( - fileId: String, - width: Int? = null, - height: Int? = null, - gravity: String? = null, - quality: Int? = null, - borderWidth: Int? = null, - borderColor: String? = null, - borderRadius: Int? = null, - opacity: Double? = null, - rotation: Int? = null, - background: String? = null, - output: String? = null - ): Response { - val path = "/storage/files/{fileId}/preview".replace("{fileId}", fileId) - val params = mapOf( + bucketId: String, + fileId: String, + width: Long? = null, + height: Long? = null, + gravity: io.appwrite.enums.ImageGravity? = null, + quality: Long? = null, + borderWidth: Long? = null, + borderColor: String? = null, + borderRadius: Long? = null, + opacity: Double? = null, + rotation: Long? = null, + background: String? = null, + output: io.appwrite.enums.ImageFormat? = null, + token: String? = null, + ): ByteArray { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}/preview" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) + + val apiParams = mutableMapOf( "width" to width, "height" to height, "gravity" to gravity, @@ -235,33 +298,47 @@ class Storage(client: Client) : Service(client) { "rotation" to rotation, "background" to background, "output" to output, - "project" to client.config["project"] + "token" to token, + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java ) - - return client.call("GET", path, params = params) } - + + /** - * Get File for View + * Get a file content by its unique ID. This endpoint is similar to the download method but returns with no 'Content-Disposition: attachment' header. * - * Get a file content by its unique ID. This endpoint is similar to the - * download method but returns with no 'Content-Disposition: attachment' - * header. - * - * @param fileId - * @return [Response] + * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param fileId File ID. + * @param token File token for accessing this file. + * @return [ByteArray] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun getFileView( - fileId: String - ): Response { - val path = "/storage/files/{fileId}/view".replace("{fileId}", fileId) - val params = mapOf( - "project" to client.config["project"] - ) + bucketId: String, + fileId: String, + token: String? = null, + ): ByteArray { + val apiPath = "/storage/buckets/{bucketId}/files/{fileId}/view" + .replace("{bucketId}", bucketId) + .replace("{fileId}", fileId) - return client.call("GET", path, params = params) + val apiParams = mutableMapOf( + "token" to token, + "project" to client.config["project"], + ) + return client.call( + "GET", + apiPath, + params = apiParams, + responseType = ByteArray::class.java + ) } - + + } \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/TablesDb.kt b/library/src/main/java/io/appwrite/services/TablesDb.kt new file mode 100644 index 0000000..2cc40e3 --- /dev/null +++ b/library/src/main/java/io/appwrite/services/TablesDb.kt @@ -0,0 +1,547 @@ +package io.appwrite.services + +import android.net.Uri +import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* +import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf +import okhttp3.Cookie +import java.io.File + +/** + * + */ +class TablesDB(client: Client) : Service(client) { + + /** + * Get a list of all the user's rows in a given table. You can use the query params to filter your results. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the TableDB service [server integration](https://appwrite.io/docs/server/tablesdbdb#tablesdbCreate). + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.RowList] + */ + @JvmOverloads + suspend fun listRows( + databaseId: String, + tableId: String, + queries: List? = null, + nestedType: Class, + ): io.appwrite.models.RowList { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.RowList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.RowList.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get a list of all the user's rows in a given table. You can use the query params to filter your results. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the TableDB service [server integration](https://appwrite.io/docs/server/tablesdbdb#tablesdbCreate). + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.RowList] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun listRows( + databaseId: String, + tableId: String, + queries: List? = null, + ): io.appwrite.models.RowList> = listRows( + databaseId, + tableId, + queries, + nestedType = classOf(), + ) + + /** + * Create a new Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). Make sure to define columns before creating rows. + * @param rowId Row ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param data Row data as JSON object. + * @param permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun createRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + + val apiParams = mutableMapOf( + "rowId" to rowId, + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Create a new Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). Make sure to define columns before creating rows. + * @param rowId Row ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param data Row data as JSON object. + * @param permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun createRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any, + permissions: List? = null, + ): io.appwrite.models.Row> = createRow( + databaseId, + tableId, + rowId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Get a row by its unique ID. This endpoint response returns a JSON object with the row data. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param rowId Row ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun getRow( + databaseId: String, + tableId: String, + rowId: String, + queries: List? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + + val apiParams = mutableMapOf( + "queries" to queries, + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Get a row by its unique ID. This endpoint response returns a JSON object with the row data. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param rowId Row ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun getRow( + databaseId: String, + tableId: String, + rowId: String, + queries: List? = null, + ): io.appwrite.models.Row> = getRow( + databaseId, + tableId, + rowId, + queries, + nestedType = classOf(), + ) + + /** + * 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/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param data Row data as JSON object. Include all required columns of the row to be created or updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun upsertRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any? = null, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + + val apiParams = mutableMapOf( + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * 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/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param data Row data as JSON object. Include all required columns of the row to be created or updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun upsertRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any? = null, + permissions: List? = null, + ): io.appwrite.models.Row> = upsertRow( + databaseId, + tableId, + rowId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Update a row by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param data Row data as JSON object. Include only columns and value pairs to be updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun updateRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any? = null, + permissions: List? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + + val apiParams = mutableMapOf( + "data" to data, + "permissions" to permissions, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Update a row by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param data Row data as JSON object. Include only columns and value pairs to be updated. + * @param permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun updateRow( + databaseId: String, + tableId: String, + rowId: String, + data: Any? = null, + permissions: List? = null, + ): io.appwrite.models.Row> = updateRow( + databaseId, + tableId, + rowId, + data, + permissions, + nestedType = classOf(), + ) + + /** + * Delete a row by its unique ID. + * + * @param databaseId Database ID. + * @param tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param rowId Row ID. + * @return [Any] + */ + suspend fun deleteRow( + databaseId: String, + tableId: String, + rowId: String, + ): Any { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + + /** + * Decrement a specific column of a row by a given value. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param column Column key. + * @param value Value to increment the column by. The value must be a number. + * @param min Minimum value for the column. If the current value is lesser than this value, an exception will be thrown. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun decrementRowColumn( + databaseId: String, + tableId: String, + rowId: String, + column: String, + value: Double? = null, + min: Double? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + .replace("{column}", column) + + val apiParams = mutableMapOf( + "value" to value, + "min" to min, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Decrement a specific column of a row by a given value. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param column Column key. + * @param value Value to increment the column by. The value must be a number. + * @param min Minimum value for the column. If the current value is lesser than this value, an exception will be thrown. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun decrementRowColumn( + databaseId: String, + tableId: String, + rowId: String, + column: String, + value: Double? = null, + min: Double? = null, + ): io.appwrite.models.Row> = decrementRowColumn( + databaseId, + tableId, + rowId, + column, + value, + min, + nestedType = classOf(), + ) + + /** + * Increment a specific column of a row by a given value. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param column Column key. + * @param value Value to increment the column by. The value must be a number. + * @param max Maximum value for the column. If the current value is greater than this value, an error will be thrown. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + suspend fun incrementRowColumn( + databaseId: String, + tableId: String, + rowId: String, + column: String, + value: Double? = null, + max: Double? = null, + nestedType: Class, + ): io.appwrite.models.Row { + val apiPath = "/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment" + .replace("{databaseId}", databaseId) + .replace("{tableId}", tableId) + .replace("{rowId}", rowId) + .replace("{column}", column) + + val apiParams = mutableMapOf( + "value" to value, + "max" to max, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Row = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Row.from(map = it as Map, nestedType) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } + + /** + * Increment a specific column of a row by a given value. + * + * @param databaseId Database ID. + * @param tableId Table ID. + * @param rowId Row ID. + * @param column Column key. + * @param value Value to increment the column by. The value must be a number. + * @param max Maximum value for the column. If the current value is greater than this value, an error will be thrown. + * @return [io.appwrite.models.Row] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun incrementRowColumn( + databaseId: String, + tableId: String, + rowId: String, + column: String, + value: Double? = null, + max: Double? = null, + ): io.appwrite.models.Row> = incrementRowColumn( + databaseId, + tableId, + rowId, + column, + value, + max, + nestedType = classOf(), + ) + +} \ No newline at end of file diff --git a/library/src/main/java/io/appwrite/services/Teams.kt b/library/src/main/java/io/appwrite/services/Teams.kt index 741fd03..54dcc3b 100644 --- a/library/src/main/java/io/appwrite/services/Teams.kt +++ b/library/src/main/java/io/appwrite/services/Teams.kt @@ -2,334 +2,594 @@ package io.appwrite.services import android.net.Uri import io.appwrite.Client +import io.appwrite.Service +import io.appwrite.models.* +import io.appwrite.enums.* import io.appwrite.exceptions.AppwriteException +import io.appwrite.extensions.classOf import okhttp3.Cookie -import okhttp3.Response import java.io.File +/** + * 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(client: Client) : Service(client) { /** - * List Teams + * Get a list of all the teams in which the current user is a member. You can use the parameters to filter your results. * - * Get a list of all the current user teams. You can use the query params to - * filter your results. On admin mode, this endpoint will return a list of all - * of the project's teams. [Learn more about different API - * modes](/docs/admin). - * - * @param search - * @param limit - * @param offset - * @param orderType - * @return [Response] + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan + * @param search Search term to filter your list results. Max length: 256 chars. + * @return [io.appwrite.models.TeamList] */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun list( - search: String? = null, - limit: Int? = null, - offset: Int? = null, - orderType: String? = null - ): Response { - val path = "/teams" - val params = mapOf( + suspend fun list( + queries: List? = null, + search: String? = null, + nestedType: Class, + ): io.appwrite.models.TeamList { + val apiPath = "/teams" + + val apiParams = mutableMapOf( + "queries" to queries, "search" to search, - "limit" to limit, - "offset" to offset, - "orderType" to orderType ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.TeamList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.TeamList.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, ) - - return client.call("GET", path, headers, params) } - + /** - * Create Team - * - * Create a new team. The user who creates the team will automatically be - * assigned as the owner of the team. The team owner can invite new members, - * who will be able add new owners and update or delete the team from your - * project. + * Get a list of all the teams in which the current user is a member. You can use the parameters to filter your results. * - * @param name - * @param roles - * @return [Response] + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan + * @param search Search term to filter your list results. Max length: 256 chars. + * @return [io.appwrite.models.TeamList] */ @JvmOverloads @Throws(AppwriteException::class) - suspend fun create( - name: String, - roles: List? = null - ): Response { - val path = "/teams" - val params = mapOf( + suspend fun list( + queries: List? = null, + search: String? = null, + ): io.appwrite.models.TeamList> = list( + queries, + search, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param teamId Team ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param name Team name. Max length: 128 chars. + * @param roles Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @return [io.appwrite.models.Team] + */ + @JvmOverloads + suspend fun create( + teamId: String, + name: String, + roles: List? = null, + nestedType: Class, + ): io.appwrite.models.Team { + val apiPath = "/teams" + + val apiParams = mutableMapOf( + "teamId" to teamId, "name" to name, - "roles" to roles + "roles" to roles, ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Team = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Team.from(map = it as Map, nestedType) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, ) - - return client.call("POST", path, headers, params) } - + /** - * Get Team - * - * Get a team by its unique ID. All team members have read access for this - * resource. + * 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. * - * @param teamId - * @return [Response] + * @param teamId Team ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param name Team name. Max length: 128 chars. + * @param roles Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @return [io.appwrite.models.Team] */ @JvmOverloads @Throws(AppwriteException::class) - suspend fun get( - teamId: String - ): Response { - val path = "/teams/{teamId}".replace("{teamId}", teamId) - val params = mapOf( - ) + suspend fun create( + teamId: String, + name: String, + roles: List? = null, + ): io.appwrite.models.Team> = create( + teamId, + name, + roles, + nestedType = classOf(), + ) - val headers = mapOf( - "content-type" to "application/json" - ) + /** + * Get a team by its ID. All team members have read access for this resource. + * + * @param teamId Team ID. + * @return [io.appwrite.models.Team] + */ + suspend fun get( + teamId: String, + nestedType: Class, + ): io.appwrite.models.Team { + val apiPath = "/teams/{teamId}" + .replace("{teamId}", teamId) - return client.call("GET", path, headers, params) + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Team = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Team.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) } - + /** - * Update Team + * Get a team by its ID. All team members have read access for this resource. * - * Update a team by its unique ID. Only team owners have write access for this - * resource. - * - * @param teamId - * @param name - * @return [Response] + * @param teamId Team ID. + * @return [io.appwrite.models.Team] */ - @JvmOverloads @Throws(AppwriteException::class) - suspend fun update( - teamId: String, - name: String - ): Response { - val path = "/teams/{teamId}".replace("{teamId}", teamId) - val params = mapOf( - "name" to name - ) + suspend fun get( + teamId: String, + ): io.appwrite.models.Team> = get( + teamId, + nestedType = classOf(), + ) - val headers = mapOf( - "content-type" to "application/json" - ) + /** + * Update the team's name by its unique ID. + * + * @param teamId Team ID. + * @param name New team name. Max length: 128 chars. + * @return [io.appwrite.models.Team] + */ + suspend fun updateName( + teamId: String, + name: String, + nestedType: Class, + ): io.appwrite.models.Team { + val apiPath = "/teams/{teamId}" + .replace("{teamId}", teamId) - return client.call("PUT", path, headers, params) + val apiParams = mutableMapOf( + "name" to name, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Team = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Team.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) } - + /** - * Delete Team - * - * Delete a team by its unique ID. Only team owners have write access for this - * resource. + * Update the team's name by its unique ID. * - * @param teamId - * @return [Response] + * @param teamId Team ID. + * @param name New team name. Max length: 128 chars. + * @return [io.appwrite.models.Team] */ - @JvmOverloads @Throws(AppwriteException::class) + suspend fun updateName( + teamId: String, + name: String, + ): io.appwrite.models.Team> = updateName( + teamId, + name, + nestedType = classOf(), + ) + + /** + * Delete a team using its ID. Only team members with the owner role can delete the team. + * + * @param teamId Team ID. + * @return [Any] + */ suspend fun delete( - teamId: String - ): Response { - val path = "/teams/{teamId}".replace("{teamId}", teamId) - val params = mapOf( - ) + teamId: String, + ): Any { + val apiPath = "/teams/{teamId}" + .replace("{teamId}", teamId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, ) - - return client.call("DELETE", path, headers, params) } - + + /** - * Get Team Memberships + * Use this endpoint to list a team's members using the team's ID. All team members have read access to this endpoint. Hide sensitive attributes from the response by toggling membership privacy in the Console. * - * Get a team members by the team unique ID. All team members have read access - * for this list of resources. - * - * @param teamId - * @param search - * @param limit - * @param offset - * @param orderType - * @return [Response] + * @param teamId Team ID. + * @param queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles + * @param search Search term to filter your list results. Max length: 256 chars. + * @return [io.appwrite.models.MembershipList] */ @JvmOverloads - @Throws(AppwriteException::class) - suspend fun getMemberships( - teamId: String, - search: String? = null, - limit: Int? = null, - offset: Int? = null, - orderType: String? = null - ): Response { - val path = "/teams/{teamId}/memberships".replace("{teamId}", teamId) - val params = mapOf( + suspend fun listMemberships( + teamId: String, + queries: List? = null, + search: String? = null, + ): io.appwrite.models.MembershipList { + val apiPath = "/teams/{teamId}/memberships" + .replace("{teamId}", teamId) + + val apiParams = mutableMapOf( + "queries" to queries, "search" to search, - "limit" to limit, - "offset" to offset, - "orderType" to orderType ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.MembershipList = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.MembershipList.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.MembershipList::class.java, + converter, ) - - return client.call("GET", path, headers, params) } - + + /** - * Create Team Membership - * - * Use this endpoint to invite a new member to join your team. If initiated - * from Client SDK, an email with a link to join the team will be sent to the - * new member's email address if the member doesn't exist in the project it - * will be created automatically. If initiated from server side SDKs, new - * member will automatically be added to the team. + * Invite a new member to join your team. Provide an ID for existing users, or invite unregistered users using an email or phone number. If initiated from a Client SDK, Appwrite will send an email or sms with a link to join the team to the invited user, and an account will be created for them if one doesn't exist. If initiated from a Server SDK, the new member will be added automatically to the team. + * + * You only need to provide one of a user ID, email, or phone number. Appwrite will prioritize accepting the user ID > email > phone number if you provide more than one of these parameters. * - * Use the 'URL' parameter to redirect the user from the invitation email back - * to your app. When the user is redirected, use the [Update Team Membership - * Status](/docs/client/teams#teamsUpdateMembershipStatus) endpoint to allow - * the user to accept the invitation to the team. While calling from side - * SDKs the redirect url can be empty string. + * Use the `url` parameter to redirect the user from the invitation email to your app. After the user is redirected, use the [Update Team Membership Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) endpoint to allow the user to accept the invitation to the team. + * + * Please note that to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) Appwrite will accept the only redirect URLs under the domains you have added as a platform on the Appwrite Console. * - * Please note that in order to avoid a [Redirect - * Attacks](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - * the only valid redirect URL's are the once from domains you have set when - * added your platforms in the console interface. * - * @param teamId - * @param email - * @param roles - * @param url - * @param name - * @return [Response] + * @param teamId Team ID. + * @param roles Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @param email Email of the new team member. + * @param userId ID of the user to be added to a team. + * @param phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param url URL to redirect the user back to your app from the invitation email. This parameter is not required when an API key is supplied. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param name Name of the new team member. Max length: 128 chars. + * @return [io.appwrite.models.Membership] */ @JvmOverloads - @Throws(AppwriteException::class) suspend fun createMembership( - teamId: String, - email: String, - roles: List, - url: String, - name: String? = null - ): Response { - val path = "/teams/{teamId}/memberships".replace("{teamId}", teamId) - val params = mapOf( + teamId: String, + roles: List, + email: String? = null, + userId: String? = null, + phone: String? = null, + url: String? = null, + name: String? = null, + ): io.appwrite.models.Membership { + val apiPath = "/teams/{teamId}/memberships" + .replace("{teamId}", teamId) + + val apiParams = mutableMapOf( "email" to email, + "userId" to userId, + "phone" to phone, "roles" to roles, "url" to url, - "name" to name + "name" to name, ) - - val headers = mapOf( - "content-type" to "application/json" + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Membership = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Membership.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Membership::class.java, + converter, ) - - return client.call("POST", path, headers, params) } - + + /** - * Update Membership Roles + * 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. * - * @param teamId - * @param membershipId - * @param roles - * @return [Response] + * @param teamId Team ID. + * @param membershipId Membership ID. + * @return [io.appwrite.models.Membership] */ - @JvmOverloads - @Throws(AppwriteException::class) - suspend fun updateMembershipRoles( - teamId: String, - membershipId: String, - roles: List - ): Response { - val path = "/teams/{teamId}/memberships/{membershipId}".replace("{teamId}", teamId).replace("{membershipId}", membershipId) - val params = mapOf( - "roles" to roles - ) + suspend fun getMembership( + teamId: String, + membershipId: String, + ): io.appwrite.models.Membership { + val apiPath = "/teams/{teamId}/memberships/{membershipId}" + .replace("{teamId}", teamId) + .replace("{membershipId}", membershipId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Membership = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Membership.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Membership::class.java, + converter, ) - - return client.call("PATCH", path, headers, params) } - + + /** - * Delete Team Membership + * Modify the roles of a team member. Only team members with the owner role have access to this endpoint. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). + * * - * 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. + * @param teamId Team ID. + * @param membershipId Membership ID. + * @param roles An array of strings. Use this param to set the user's roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @return [io.appwrite.models.Membership] + */ + suspend fun updateMembership( + teamId: String, + membershipId: String, + roles: List, + ): io.appwrite.models.Membership { + val apiPath = "/teams/{teamId}/memberships/{membershipId}" + .replace("{teamId}", teamId) + .replace("{membershipId}", membershipId) + + val apiParams = mutableMapOf( + "roles" to roles, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Membership = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Membership.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Membership::class.java, + converter, + ) + } + + + /** + * 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. * - * @param teamId - * @param membershipId - * @return [Response] + * @param teamId Team ID. + * @param membershipId Membership ID. + * @return [Any] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun deleteMembership( - teamId: String, - membershipId: String - ): Response { - val path = "/teams/{teamId}/memberships/{membershipId}".replace("{teamId}", teamId).replace("{membershipId}", membershipId) - val params = mapOf( - ) + teamId: String, + membershipId: String, + ): Any { + val apiPath = "/teams/{teamId}/memberships/{membershipId}" + .replace("{teamId}", teamId) + .replace("{membershipId}", membershipId) - val headers = mapOf( - "content-type" to "application/json" + val apiParams = mutableMapOf( + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, ) - - return client.call("DELETE", path, headers, params) } - + + /** - * Update Team Membership Status - * - * Use this endpoint to allow a user to accept an invitation to join a team - * after being redirected back to your app from the invitation email recieved - * by the user. + * 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. + * * - * @param teamId - * @param membershipId - * @param userId - * @param secret - * @return [Response] + * @param teamId Team ID. + * @param membershipId Membership ID. + * @param userId User ID. + * @param secret Secret key. + * @return [io.appwrite.models.Membership] */ - @JvmOverloads - @Throws(AppwriteException::class) suspend fun updateMembershipStatus( - teamId: String, - membershipId: String, - userId: String, - secret: String - ): Response { - val path = "/teams/{teamId}/memberships/{membershipId}/status".replace("{teamId}", teamId).replace("{membershipId}", membershipId) - val params = mapOf( + teamId: String, + membershipId: String, + userId: String, + secret: String, + ): io.appwrite.models.Membership { + val apiPath = "/teams/{teamId}/memberships/{membershipId}/status" + .replace("{teamId}", teamId) + .replace("{membershipId}", membershipId) + + val apiParams = mutableMapOf( "userId" to userId, - "secret" to secret + "secret" to secret, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", ) + val converter: (Any) -> io.appwrite.models.Membership = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Membership.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Membership::class.java, + converter, + ) + } - val headers = mapOf( - "content-type" to "application/json" + + /** + * 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). + * + * @param teamId Team ID. + * @return [io.appwrite.models.Preferences] + */ + suspend fun getPrefs( + teamId: String, + nestedType: Class, + ): io.appwrite.models.Preferences { + val apiPath = "/teams/{teamId}/prefs" + .replace("{teamId}", teamId) + + val apiParams = mutableMapOf( ) + val apiHeaders = mutableMapOf( + ) + val converter: (Any) -> io.appwrite.models.Preferences = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Preferences.from(map = it as Map, nestedType) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) + } - return client.call("PATCH", path, headers, params) + /** + * 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). + * + * @param teamId Team ID. + * @return [io.appwrite.models.Preferences] + */ + @Throws(AppwriteException::class) + suspend fun getPrefs( + teamId: String, + ): io.appwrite.models.Preferences> = getPrefs( + teamId, + nestedType = classOf(), + ) + + /** + * 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. + * + * @param teamId Team ID. + * @param prefs Prefs key-value JSON object. + * @return [io.appwrite.models.Preferences] + */ + suspend fun updatePrefs( + teamId: String, + prefs: Any, + nestedType: Class, + ): io.appwrite.models.Preferences { + val apiPath = "/teams/{teamId}/prefs" + .replace("{teamId}", teamId) + + val apiParams = mutableMapOf( + "prefs" to prefs, + ) + val apiHeaders = mutableMapOf( + "content-type" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Preferences = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Preferences.from(map = it as Map, nestedType) + } + return client.call( + "PUT", + apiPath, + apiHeaders, + apiParams, + responseType = classOf(), + converter, + ) } - + + /** + * 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. + * + * @param teamId Team ID. + * @param prefs Prefs key-value JSON object. + * @return [io.appwrite.models.Preferences] + */ + @Throws(AppwriteException::class) + suspend fun updatePrefs( + teamId: String, + prefs: Any, + ): io.appwrite.models.Preferences> = updatePrefs( + teamId, + prefs, + nestedType = classOf(), + ) + } \ No newline at end of file diff --git a/scripts/publish-config.gradle b/scripts/publish-config.gradle index 299c6c4..5934f92 100644 --- a/scripts/publish-config.gradle +++ b/scripts/publish-config.gradle @@ -30,8 +30,8 @@ nexusPublishing { stagingProfileId = sonatypeStagingProfileId username = ossrhUsername password = ossrhPassword - nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) - snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) + nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/")) + snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/")) } } } \ No newline at end of file diff --git a/scripts/publish-module.gradle b/scripts/publish-module.gradle index e32ff84..ca97b16 100644 --- a/scripts/publish-module.gradle +++ b/scripts/publish-module.gradle @@ -8,7 +8,6 @@ tasks.register("sourcesJar", Jar) { tasks.register("javadoc", Javadoc) { source = android.sourceSets.getByName("main").java.srcDirs - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) setDestinationDir(file("../javadoc/")) failOnError false } @@ -19,6 +18,10 @@ tasks.register("javadocJar", Jar) { from(javadoc) } +afterEvaluate { + tasks.javadoc.classpath += files(project.android.getBootClasspath()) +} + publishing { publications { release(MavenPublication) { @@ -63,7 +66,8 @@ publishing { configurations .getByName("releaseCompileClasspath") .resolvedConfiguration - .firstLevelModuleDependencies.forEach { + .firstLevelModuleDependencies + .forEach { def dependency = dependencies.appendNode("dependency") dependency.appendNode("groupId", it.moduleGroup) dependency.appendNode("artifactId", it.moduleName) diff --git a/settings.gradle b/settings.gradle index 73c359b..423c64e 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,3 @@ rootProject.name = "Appwrite Android SDK" include ':example' -include ':library' -include ':example-java' \ No newline at end of file +include ':library' \ No newline at end of file