diff --git a/CHANGELOG.md b/CHANGELOG.md index 1344896b..547ce7c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change Log +## 27.1.0-rc.0 + +* Added: `Apps` service to manage OAuth2 apps, keys, secrets, and installations +* Added: `Oauth2` service for authorization, consent, device, PAR, and token flows +* Added: `Push` service for MQTT realtime push with iOS background delivery +* Added: `Topic` builder and a native `android` module for push +* Added: `Client.setPushEndpoint()` and `Client.setPushClientId()` +* Added: `Avatars.updatePhoto()` and `Avatars.deletePhoto()` methods +* Added: `App`, `Oauth2*`, and `Account` models +* Added: `webflow` to the `OAuthProvider` enum + ## 27.0.0 * Breaking: removed `Account.listLogs` and the `Log`, `LogList` models diff --git a/README.md b/README.md index bbc066a7..000ae1df 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^27.0.0 + appwrite: ^27.1.0-rc.0 ``` You can install packages from the command line: @@ -28,6 +28,58 @@ You can install packages from the command line: flutter pub add appwrite ``` +### Push on Android + +`Push` includes a native Android plugin, so the SDK needs Android 7.0 (API 24) or later: apps +with a lower `minSdk` fail to build until they raise it. `flutter_local_notifications` also needs +core library desugaring. Add both to `android/app/build.gradle.kts` (desugaring is configured when +the app is assembled, so a plugin cannot apply it for you): + +```kotlin +android { + defaultConfig { + minSdk = 24 + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") +} +``` + +A subscription with `background: true` keeps delivering after the app is backgrounded, killed or +the device restarts, until it is unsubscribed or `push.close()` is called (do this on sign-out). +The plugin saves the subscription, and a scheduled job and alarm wake the app every 15 to 60 +seconds to reconnect; the broker replays what was sent in between (`retry: true`). Messages no +in-app callback receives are posted as notifications that open the app. It reconnects with the +credential saved at subscribe time, so use a session rather than a short-lived JWT. + +On Android 13 and later, notifications only appear once the user grants the +`POST_NOTIFICATIONS` runtime permission. Without it, the subscription still delivers to your +callback but posts no notification, so ask before subscribing, for example with +`flutter_local_notifications`: + +```dart +await FlutterLocalNotificationsPlugin() + .resolvePlatformSpecificImplementation() + ?.requestNotificationsPermission(); + +final sub = await push.subscribe('news', (message) => print(message.data), + background: true, title: 'News'); + +// Optional: immediate delivery even after a kill and during Doze, with a quiet ongoing +// notification (call while the app is in the foreground). +await push.setForeground(true); +``` + +Foreground mode runs a `remoteMessaging` foreground service, which Google Play asks apps to +declare in the Play Console. Apps that never enable it can remove the service from their merged +manifest with `tools:node="remove"` on `io.appwrite.services.PushService` and +`android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING`. + ## Getting Started @@ -38,6 +90,8 @@ From the options, choose to add a new **Flutter** platform and add your app cred If you are building your Flutter application for multiple devices, you have to follow this process for each different device. +> On Android, iOS and macOS, call `createOAuth2Session` without the `success` and `failure` URLs. The SDK only returns to your app through the `appwrite-callback-[PROJECT_ID]` scheme, and only the default redirect carries the new session with it. A custom URL, such as an https App Link, makes the call fail (for example with `PlatformException(CANCELED)`) even when the login itself succeeded. Await the returned `Future` and navigate from your Dart code instead. + ### Android For **Android** first add your app name and package name, Your package name is generally the **applicationId** in your app-level build.gradle file. By registering your new app platform, you are allowing your app to communicate with the Appwrite API. diff --git a/android/.editorconfig b/android/.editorconfig new file mode 100644 index 00000000..f0895a33 --- /dev/null +++ b/android/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*.{kt,kts}] +ktlint_code_style = ktlint_official +ktlint_standard_annotation = disabled +ktlint_standard_argument-list-wrapping = disabled +ktlint_standard_blank-line-before-declaration = disabled +ktlint_standard_blank-line-between-when-conditions = disabled +ktlint_standard_chain-method-continuation = disabled +ktlint_standard_class-signature = disabled +ktlint_standard_function-expression-body = disabled +ktlint_standard_function-signature = disabled +ktlint_standard_function-start-of-body-spacing = disabled +ktlint_standard_if-else-bracing = disabled +ktlint_standard_if-else-wrapping = disabled +ktlint_standard_max-line-length = disabled +ktlint_standard_multiline-expression-wrapping = disabled +ktlint_standard_multiline-if-else = disabled +ktlint_standard_no-blank-line-before-rbrace = disabled +ktlint_standard_no-blank-line-in-list = disabled +ktlint_standard_no-empty-first-line-in-class-body = disabled +ktlint_standard_no-line-break-before-assignment = disabled +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_parameter-list-wrapping = disabled +ktlint_standard_spacing-between-declarations-with-annotations = disabled +ktlint_standard_spacing-between-declarations-with-comments = disabled +ktlint_standard_string-template = disabled +ktlint_standard_trailing-comma-on-call-site = disabled +ktlint_standard_trailing-comma-on-declaration-site = disabled +ktlint_standard_when-entry-bracing = disabled +ktlint_standard_wrapping = disabled + +[**/Channel.kt] +# Marker types intentionally use leading underscores to distinguish channel states. +ktlint_standard_class-naming = disabled + +[**/models/*.kt] +# Model imports follow schema property order so generated declarations stay deterministic. +ktlint_standard_import-ordering = disabled diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 00000000..47df6fdf --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,56 @@ +// The native half of Push on Android: background delivery that survives the process being +// killed, a reboot and an app update, shared with the Appwrite Android SDK. +group = "io.appwrite.flutter" +version = "27.1.0-rc.0" + +buildscript { + ext.kotlin_version = "2.1.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.7.3") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" +apply plugin: "kotlin-android" + +android { + namespace = "io.appwrite.flutter" + compileSdk = 35 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + sourceSets { + main.java.srcDirs += "src/main/kotlin" + } + + defaultConfig { + minSdk = 24 + // R8 rules for the bundled MQTT client, applied to the app. + consumerProguardFiles("consumer-rules.pro") + } +} + +dependencies { + implementation("com.hivemq:hivemq-mqtt-client-shaded:1.3.6") + implementation("androidx.core:core-ktx:1.13.1") +} diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro new file mode 100644 index 00000000..04d7db2c --- /dev/null +++ b/android/consumer-rules.pro @@ -0,0 +1,27 @@ +# Push: rules applied to apps that shrink with R8. +# +# The shaded HiveMQ MQTT client relocates Netty and JCTools under +# com.hivemq.client.internal.shaded. Netty references optional classes that are never loaded +# on Android: native transports, the HTTP/WebSocket codecs, proxy handlers, alternative TLS +# providers (tcnative, BouncyCastle, Conscrypt, Jetty ALPN) and logging backends. +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.epoll.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.channel.kqueue.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.codec.http.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.handler.proxy.** +-dontwarn com.hivemq.client.internal.shaded.io.netty.internal.tcnative.** +-dontwarn org.bouncycastle.** +-dontwarn org.conscrypt.** +-dontwarn org.eclipse.jetty.** +-dontwarn org.apache.log4j.** +-dontwarn org.apache.logging.log4j.** +-dontwarn org.slf4j.** +-dontwarn reactor.blockhound.** + +# Netty and JCTools reach their own fields by name, through atomic field updaters and Unsafe offsets. +-keepclassmembernames class com.hivemq.client.internal.shaded.io.netty.** { ; } +-keepclassmembers class com.hivemq.client.internal.shaded.org.jctools.** { ; } + +# Netty's leak detector looks these methods up by name when its classes load. +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AbstractByteBufAllocator { *** toLeakAwareBuffer(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.buffer.AdvancedLeakAwareByteBuf { *** recordLeakNonRefCountingOperation(...); } +-keepclassmembers class com.hivemq.client.internal.shaded.io.netty.util.ReferenceCountUtil { *** touch(...); } diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 00000000..137b5997 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'appwrite' diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..44f894ed --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt new file mode 100644 index 00000000..81b0d30e --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/exceptions/AppwriteException.kt @@ -0,0 +1,6 @@ +package io.appwrite.exceptions + +/** A push error. When the broker explained a refusal or a disconnect, that is its message. */ +class AppwriteException( + override val message: String? = null, +) : Exception(message) diff --git a/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt new file mode 100644 index 00000000..c68a60c6 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/flutter/AppwritePushPlugin.kt @@ -0,0 +1,108 @@ +package io.appwrite.flutter + +import android.os.Handler +import android.os.Looper +import io.appwrite.services.PushBridge +import io.appwrite.services.PushMessage +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +/** + * The Flutter side of [PushBridge]: the SDK's `Push` hosts its background subscriptions here on + * Android over a method channel, and receives their messages and errors over an event channel. + */ +class AppwritePushPlugin : + FlutterPlugin, + MethodChannel.MethodCallHandler, + EventChannel.StreamHandler { + private val main = Handler(Looper.getMainLooper()) + private var methods: MethodChannel? = null + private var events: EventChannel? = null + private var sink: EventChannel.EventSink? = null + private var bridge: PushBridge? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + bridge = PushBridge( + binding.applicationContext, + object : PushBridge.Events { + override fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) = send( + mapOf( + "type" to "message", + "id" to subscriptionId, + "topic" to message.topic, + "payload" to message.payload, + "qos" to message.qos, + "ackToken" to ackToken, + ), + ) + + override fun onError(message: String) = send(mapOf("type" to "error", "message" to message)) + }, + ) + methods = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL).also { it.setMethodCallHandler(this) } + events = EventChannel(binding.binaryMessenger, EVENT_CHANNEL).also { it.setStreamHandler(this) } + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + methods?.setMethodCallHandler(null) + events?.setStreamHandler(null) + methods = null + events = null + sink = null + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + val bridge = bridge ?: return result.error(ERROR_CODE, "Push plugin is not attached", null) + try { + if (call.method == "host") { + // Replies once the connection is up and every filter is subscribed, or with why not. + bridge.host(call.argument("config")!!, call.argument("subscriptions")!!) { error -> + main.post { + if (error == null) { + result.success(null) + } else { + result.error(ERROR_CODE, error, null) + } + } + } + return + } + result.success( + when (call.method) { + "ack" -> bridge.ack(call.argument("token")!!).let { null } + "release" -> bridge.release().let { null } + "stop" -> bridge.stop().let { null } + "setForeground" -> bridge.setForeground(call.argument("enabled") == true).let { null } + "hasSaved" -> bridge.hasSaved() + "resume" -> bridge.resume().let { null } + "setErrorCallback" -> bridge.setErrorCallback(call.argument("registered") == true) + "defaultClientId" -> bridge.defaultClientId(call.argument("authMethod")!!, call.argument("credential")!!) + else -> return result.notImplemented() + }, + ) + } catch (e: Exception) { + result.error(ERROR_CODE, e.message, null) + } + } + + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + sink = events + } + + override fun onCancel(arguments: Any?) { + sink = null + } + + // The bridge calls back on background threads; event sinks must be used on the main thread. + private fun send(event: Map) { + main.post { sink?.success(event) } + } + + private companion object { + const val METHOD_CHANNEL = "appwrite.push" + const val EVENT_CHANNEL = "appwrite.push/events" + const val ERROR_CODE = "appwrite_push" + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBackground.kt b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt new file mode 100644 index 00000000..52517344 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBackground.kt @@ -0,0 +1,1009 @@ +package io.appwrite.services + +import android.app.AlarmManager +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.job.JobInfo +import android.app.job.JobScheduler +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.Network +import android.os.Build +import android.os.PowerManager +import android.os.SystemClock +import android.util.AtomicFile +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.hivemq.client.mqtt.MqttGlobalPublishFilter +import com.hivemq.client.mqtt.datatypes.MqttQos +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.util.UUID +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger + +private const val LOG_TAG = "AppwritePush" + +/** A background subscription saved across restarts: its filter, QoS choice and notification title. */ +internal data class PushEntry( + val filter: String, + val retry: Boolean, + val title: String?, +) + +/** + * The adaptive heartbeat: its interval, the current streak of failed heartbeats, and when the + * interval last shrank (wall-clock ms, as it must survive reboots). + */ +internal data class PushHeartbeat( + val intervalMs: Long, + val failures: Int = 0, + val shrunkAt: Long = 0L, +) + +/** + * The process-wide host of the background push connection, modelled on how socket push + * services survive on Android without keeping a service alive. + * + * The background subscriptions and their connection config are saved to private storage (see + * [PushStore]), so delivery survives the process being killed, a reboot and an app update. A + * job ([PushJobService]) that reschedules itself on every run, backed by an alarm + * ([PushAlarmReceiver]), wakes the process every 15 seconds (60 when the app may use exact + * alarms or is exempt from battery optimisation). Each run holds a short wakelock and + * reconnects when the connection is gone or the default network changed, sends a heartbeat + * when one is due, and re-arms the job. While the process is alive between runs the socket + * stays open and messages arrive immediately; while it is dead the broker keeps the backlog + * for this client id and replays it when the next run subscribes again. + * + * With foreground mode enabled ([Push.setForeground]) a foreground service ([PushService]) also keeps + * the process at foreground priority, so delivery is immediate after a kill and during Doze. + * + * Messages go to the live in-app callbacks that match them. When none match (the process was + * started in the background), a declared [PushReceiver] gets the message, and a notification + * is posted unless it returns true. + */ +internal object PushBackground { + const val CHANNEL_ID = "appwrite-push" + const val NOTIFICATION_ID = 1911 + const val ACTION_TICK = "io.appwrite.push.TICK" + const val ACTION_MESSAGE = "io.appwrite.push.MESSAGE" + const val NOTIFICATION_ICON = "io.appwrite.push.notification_icon" + const val EXTRA_TOPIC = "io.appwrite.push.TOPIC" + const val EXTRA_PAYLOAD = "io.appwrite.push.PAYLOAD" + + private const val SERVICE_CHANNEL_ID = "appwrite-push-service" + private const val JOB_ID = 0x50555348 + private const val INTERVAL_MS = 15_000L + private const val PRIVILEGED_INTERVAL_MS = 60_000L + private const val RESTART_DELAY_MS = 3_000L + // An upper bound covering a run's connect (20 s) and its requests (10 s each); the wakelock is + // released as soon as the run finishes. + private const val WAKE_LOCK_MS = 60_000L + private const val KEEP_ALIVE_SECONDS = 300 + + // The heartbeat interval: below the broker's 1.5 x keep-alive expiry, measured on a clock that + // counts deep sleep. Networks that drop idle connections sooner (carrier NATs) make heartbeats + // fail; after HEARTBEAT_FAILURES in a row the interval shrinks by a quarter, down to + // MIN_HEARTBEAT_MS, and returns to the default HEARTBEAT_RESET_MS after the last shrink, in + // case the device moved to a better network. + const val HEARTBEAT_MS = 180_000L + private const val MIN_HEARTBEAT_MS = 60_000L + private const val HEARTBEAT_FAILURES = 3 + private const val HEARTBEAT_RESET_MS = 3 * 24 * 60 * 60 * 1_000L + private const val REQUEST_TIMEOUT_SECONDS = 10L + private const val CONNECT_TIMEOUT_SECONDS = 20L + + // How long a message waits for a listener that acknowledges it itself (the React Native and + // Flutter bridges, once their callback has run) before it is acknowledged anyway, so one stuck + // callback cannot hold back the acknowledgements after it. + private const val ACK_TIMEOUT_SECONDS = 10L + + // Unsubscribing a filter nothing subscribes to is a harmless round trip the broker always + // acknowledges, so it proves the connection is alive. The broker ignores client PUBLISHes + // without a PUBACK, so a publish cannot serve as the heartbeat. + private const val HEARTBEAT_FILTER = "\$heartbeat" + + @Volatile + var channelName: String = "Notifications" + + @Volatile + var ongoingTitle: String = "Appwrite" + + // Reports errors to the Push instance that hosts its subscriptions here. Returns whether the + // app's onError received the error (false when it registered none). + @Volatile + var errorHandler: ((Throwable) -> Boolean)? = null + + @Volatile + var serviceRunning = false + + // Whether a refused service start was reported, so a job that retries it every run does not + // report the same failure every 15 seconds. + @Volatile + private var serviceStartReported = false + + // The live in-app subscriptions hosted here, each with its callback. Empty after the process + // was restarted in the background, until the app subscribes again. + val listeners = CopyOnWriteArrayList() + + // Guards the saved state below and its copy on disk. + private val lock = Any() + private var loaded = false + private var config: PushConfig? = null + + // Background subscriptions saved by an earlier run that no live subscription has taken over. + private var saved: List = emptyList() + + // Every MQTT call runs on this thread, in order, so the connection state below needs no lock. + private val worker = Executors.newSingleThreadScheduledExecutor { runnable -> + Thread(runnable, "AppwritePushBackground").apply { isDaemon = true } + } + private var mqtt: Mqtt5AsyncClient? = null + private var connectedConfig: PushConfig? = null + private var connectedNetwork: Network? = null + private var lastHeartbeat = 0L + private var heartbeatState: PushHeartbeat? = null + private val subscribed = mutableMapOf() + private var networkCallback: ConnectivityManager.NetworkCallback? = null + + // Worker thread only. While a caller waits for a converge (host with a completion), its + // failures go to that caller, which reports them, instead of onError. + private var waiting = false + private var failure: Throwable? = null + + /** + * Host [newListeners] (the app's live subscriptions) on the background connection with + * [newConfig], save the background ones, and arm the scheduled wake-ups. Saved subscriptions + * from an earlier run stay unless a live subscription on the same filter takes them over + * (with background on or off), or [newConfig] is for another client id (another user), whose + * saved subscriptions are dropped. + * + * With [done], it is called once the connection is up and every filter is subscribed (SUBACK), + * or with the failure, which is then not reported to onError: the caller reports it. + */ + fun host( + context: Context, + newConfig: PushConfig, + newListeners: List, + done: ((Throwable?) -> Unit)? = null, + ) { + val app = context.applicationContext + synchronized(lock) { + load(app) + if (config != null && config?.clientId != newConfig.clientId) { + saved = emptyList() + } + // A live subscription on a saved filter takes it over, whether or not it wants background: + // one that turned background off, or is later unsubscribed, must not leave the saved + // entry delivering in the background. + saved = saved.filter { entry -> newListeners.none { entry.filter in it.topics } } + config = newConfig + listeners.clear() + listeners.addAll(newListeners) + persist(app) + } + activate(app, done) + } + + /** + * Stop hosting the app's live subscriptions, keeping the saved ones from an earlier run. + * Shuts down when none remain. + */ + fun release(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + listeners.clear() + persist(app) + isActive() + } + if (active) { + worker.execute { converge(app, heartbeat = false) } + } else { + shutdown(app) + } + } + + /** Stop background delivery completely and forget every saved subscription. */ + fun stop(context: Context) { + val app = context.applicationContext + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = true + PushStore.clearState(app) + } + shutdown(app) + } + + /** Whether subscriptions saved by an earlier run are still delivered in the background. */ + fun hasSaved(context: Context): Boolean = synchronized(lock) { + load(context.applicationContext) + saved.isNotEmpty() + } + + /** Persist the foreground-mode choice and start or stop the foreground service to match. */ + fun setForeground(context: Context, enabled: Boolean) { + val app = context.applicationContext + PushStore.setForeground(app, enabled) + serviceStartReported = false + ensureService(app) + } + + /** Whether the foreground service should run: foreground mode is enabled and there is work to do. */ + fun wantsService(context: Context): Boolean { + val app = context.applicationContext + return PushStore.foreground(app) && synchronized(lock) { + load(app) + isActive() + } + } + + /** Resume saved background delivery when the app starts, without waiting for the next run. */ + fun resume(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + tick(app) {} + } + } + + /** + * One scheduled run: under a wakelock, reconnect if needed, send a heartbeat when one is due, + * re-arm the next run, and call [done] once finished. Shuts down when nothing is saved. + */ + fun tick(context: Context, done: () -> Unit) { + val app = context.applicationContext + val wakeLock = acquireWakeLock(app) + worker.execute { + try { + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + // Arm the next run first, so a run cut short (killed, or a slow broker outlasting + // the wakelock) still leaves the chain armed. A refused credential in converge() + // shuts down, cancelling it again. + schedule(app, INTERVAL_MS) + ensureService(app) + registerNetworkCallback(app) + converge(app, heartbeat = true) + } else { + shutdown(app) + } + } catch (e: Exception) { + report(e) + } finally { + releaseWakeLock(wakeLock) + done() + } + } + } + + /** Run once more shortly after the task was removed, so an OEM kill that follows is undone. */ + fun scheduleRestart(context: Context) { + schedule(context.applicationContext, RESTART_DELAY_MS, jobToo = false) + } + + /** + * Forget everything held in memory, as the process dying does, keeping only what is saved. + * For tests of what happens after the app's process was killed. + */ + internal fun dropProcessState(context: Context) { + synchronized(lock) { + listeners.clear() + config = null + saved = emptyList() + loaded = false + } + errorHandler = null + unregisterNetworkCallback(context.applicationContext) + worker.submit { disconnect() }.get() + } + + /** Report an error to the hosting Push instance's onError; logged when there is none. */ + fun report(error: Throwable): Boolean { + val delivered = try { + errorHandler?.invoke(error) ?: false + } catch (callbackError: Exception) { + Log.e(LOG_TAG, "Push onError threw", callbackError) + true + } + if (!delivered) { + Log.e(LOG_TAG, "Push background error", error) + } + return delivered + } + + // Must hold [lock]. + private fun load(context: Context) { + if (loaded) { + return + } + loaded = true + val state = PushStore.loadState(context) ?: return + config = state.first + saved = state.second + } + + // Must hold [lock]. + private fun isActive(): Boolean = config != null && (saved.isNotEmpty() || listeners.isNotEmpty()) + + // Must hold [lock]. Every background subscription, live or saved, one per filter and title. + // Subscriptions sharing a filter and title are saved once, with QoS 1 when any of them wants it. + private fun entries(): List = + (saved + listeners.filter { it.background }.flatMap { listener -> listener.topics.map { PushEntry(it, listener.retry, listener.title) } }) + .groupBy { it.filter to it.title } + .map { (key, group) -> PushEntry(key.first, group.any { it.retry }, key.second) } + + // Must hold [lock]. + private fun persist(context: Context) { + val current = config + val entries = entries() + if (current == null || entries.isEmpty()) { + PushStore.clearState(context) + } else { + PushStore.saveState(context, current, entries) + } + } + + // Must hold [lock]. The broker subscriptions wanted, at the highest QoS any subscription on a + // filter asks for. + private fun wanted(): Map { + val qos = linkedMapOf() + fun want(filter: String, retry: Boolean) { + if (retry) { + qos[filter] = MqttQos.AT_LEAST_ONCE + } else if (filter !in qos) { + qos[filter] = MqttQos.AT_MOST_ONCE + } + } + for (listener in listeners) { + listener.topics.forEach { want(it, listener.retry) } + } + saved.forEach { want(it.filter, it.retry) } + return qos + } + + private fun activate(context: Context, done: ((Throwable?) -> Unit)? = null) { + registerNetworkCallback(context) + schedule(context, INTERVAL_MS) + ensureService(context) + worker.execute { converge(context, heartbeat = false, done) } + } + + private fun shutdown(context: Context) { + cancelSchedule(context) + unregisterNetworkCallback(context) + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + worker.execute { disconnect() } + } + + // Worker thread only. Bring the connection to the wanted state: reconnect when the config or + // the default network changed or a due heartbeat fails, then subscribe and unsubscribe the + // difference. With [done], failures go to it (see [waiting]) instead of onError. + private fun converge(context: Context, heartbeat: Boolean, done: ((Throwable?) -> Unit)? = null) { + waiting = done != null + failure = null + try { + convergeOnce(context, heartbeat) + } catch (e: Exception) { + fail(e) + } finally { + waiting = false + done?.invoke(failure) + } + } + + // Worker thread only. Record a failure for the waiting caller, or report it. + private fun fail(error: Throwable) { + if (failure == null) { + failure = error + } + if (!waiting) { + report(error) + } + } + + private fun convergeOnce(context: Context, heartbeat: Boolean) { + val (current, wanted) = synchronized(lock) { config to wanted() } + if (current == null || wanted.isEmpty()) { + disconnect() + return + } + var client = mqtt + if (client != null && (current != connectedConfig || networkChanged(context))) { + disconnect() + client = null + } + if (client != null && heartbeat && SystemClock.elapsedRealtime() - lastHeartbeat >= heartbeatInterval(context)) { + val alive = sendHeartbeat(client) + recordHeartbeat(context, alive) + if (alive) { + lastHeartbeat = SystemClock.elapsedRealtime() + } else { + disconnect() + client = null + } + } + if (client == null) { + client = connect(context, current) ?: return + } + for (filter in subscribed.keys - wanted.keys) { + request { client.unsubscribeWith().topicFilter(filter).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) } + subscribed.remove(filter) + } + for ((filter, qos) in wanted) { + if (subscribed[filter] != qos && subscribe(client, filter, qos)) { + subscribed[filter] = qos + } + } + } + + // Worker thread only. Connect with [config], or report why not and return null. A refused + // credential stops background delivery: retrying it would only be refused again. + private fun connect(context: Context, config: PushConfig): Mqtt5AsyncClient? { + // A failed first connect of a waited-for converge goes to the waiting caller only. + val quiet = waiting + val connected = AtomicBoolean(false) + val client = buildPushClient( + config.copy(keepAlive = KEEP_ALIVE_SECONDS), + onError = { error -> + if (!quiet || connected.get()) { + report(error) + } + }, + onAuthRefused = { error -> worker.execute { refused(context, error) } }, + ) + // Registered before connecting, so the backlog the broker replays right after each + // SUBSCRIBE reaches the app however the subscription was made (including the ones the + // client restores itself after an automatic reconnect). Acknowledged by hand, once the + // message was delivered (see [deliver]). + client.publishes(MqttGlobalPublishFilter.ALL, { publish -> deliver(context, publish) }, true) + try { + client.sendPushConnect(config.copy(keepAlive = KEEP_ALIVE_SECONDS), CONNECT_TIMEOUT_SECONDS) + } catch (e: Exception) { + val cause = (e as? ExecutionException)?.cause ?: e + client.disconnect() + val error = connectError(cause) + when { + isAuthRefusal(cause) -> refused(context, error) + waiting -> fail(error) + // A network failure already reached onError through the client's disconnect + // listener; a refused CONNECT and a timeout did not. + cause is Mqtt5ConnAckException || cause is TimeoutException -> report(error) + } + return null + } + connected.set(true) + mqtt = client + connectedConfig = config + connectedNetwork = activeNetwork(context) + lastHeartbeat = SystemClock.elapsedRealtime() + subscribed.clear() + return client + } + + // Worker thread only. + private fun subscribe(client: Mqtt5AsyncClient, filter: String, qos: MqttQos): Boolean = request { + val subAck = client.subscribeWith().topicFilter(filter).qos(qos).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + val code = subAck.reasonCodes.firstOrNull { it.isError } + if (code != null) { + throw AppwriteException( + subAck.reasonString.map { it.toString() }.orElse("Subscribing to $filter was refused (reason $code)"), + ) + } + } + + // Worker thread only. The current heartbeat interval, back at the default once a shrink is + // old enough. + private fun heartbeatInterval(context: Context): Long { + val state = heartbeatState ?: PushStore.heartbeat(context).also { heartbeatState = it } + if (state.intervalMs < HEARTBEAT_MS && System.currentTimeMillis() - state.shrunkAt >= HEARTBEAT_RESET_MS) { + saveHeartbeat(context, PushHeartbeat(HEARTBEAT_MS)) + return HEARTBEAT_MS + } + return state.intervalMs + } + + // Worker thread only. Count a failed heartbeat (a connection the network dropped silently), + // shrinking the interval after HEARTBEAT_FAILURES in a row; a delivered one ends the streak. + private fun recordHeartbeat(context: Context, alive: Boolean) { + val state = heartbeatState ?: PushStore.heartbeat(context) + val next = when { + alive -> state.copy(failures = 0) + state.failures + 1 < HEARTBEAT_FAILURES -> state.copy(failures = state.failures + 1) + else -> PushHeartbeat(maxOf(MIN_HEARTBEAT_MS, state.intervalMs * 3 / 4), 0, System.currentTimeMillis()) + } + if (next != state) { + saveHeartbeat(context, next) + } + } + + private fun saveHeartbeat(context: Context, state: PushHeartbeat) { + heartbeatState = state + PushStore.setHeartbeat(context, state) + } + + // Worker thread only. + private fun sendHeartbeat(client: Mqtt5AsyncClient): Boolean = try { + client.unsubscribeWith().topicFilter(HEARTBEAT_FILTER).send().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) + true + } catch (e: Exception) { + false + } + + // Run a broker request, recording or reporting its failure. Returns whether it succeeded. + private fun request(block: () -> Unit): Boolean = try { + block() + true + } catch (e: Exception) { + fail((e as? ExecutionException)?.cause ?: e) + false + } + + // Worker thread only. + private fun disconnect() { + mqtt?.disconnect() + mqtt = null + connectedConfig = null + connectedNetwork = null + subscribed.clear() + } + + // Worker thread only. The broker refused the credential: report it and stop. With no onError + // registered the message is also saved, and the next onError registration receives it. A + // waiting caller receives it instead. + private fun refused(context: Context, error: Throwable) { + if (waiting) { + fail(error) + } else if (!report(error)) { + PushStore.setStoppedError(context, error.message ?: "Push connection refused") + } + stop(context) + } + + // Deliver a message, then acknowledge it: right away, or once every listener that acknowledges + // messages itself has done so (at most ACK_TIMEOUT_SECONDS later). + private fun deliver(context: Context, publish: Mqtt5Publish) { + val acknowledged = AtomicBoolean(false) + val acknowledge = { + if (acknowledged.compareAndSet(false, true)) { + runCatching { publish.acknowledge() } + } + } + val pending = AtomicInteger(1) + val settle = { + if (pending.decrementAndGet() == 0) { + acknowledge() + } + } + try { + deliverMessage(context, publish.toPushMessage()) { + pending.incrementAndGet() + val once = AtomicBoolean(false) + val ack: () -> Unit = { + if (once.compareAndSet(false, true)) { + settle() + } + } + ack + } + } finally { + settle() + } + if (!acknowledged.get()) { + worker.schedule({ acknowledge() }, ACK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + } + } + + // Deliver a message to the matching live callbacks; with none, to the declared PushReceiver + // and/or a notification per saved subscription that matches it. [deferAck] hands a listener + // that acknowledges messages itself its acknowledgement. + private fun deliverMessage(context: Context, message: PushMessage, deferAck: () -> () -> Unit) { + val matching = listeners.filter { listener -> listener.topics.any { matchesTopic(it, message.topic) } } + // Saved background subscriptions no live one has taken over; they deliver even when a live + // foreground-only subscription on an overlapping filter received the message too. + val entries = synchronized(lock) { saved }.filter { matchesTopic(it.filter, message.topic) } + if (matching.isEmpty() && entries.isEmpty()) { + return + } + for (listener in matching) { + try { + val acknowledging = listener.acknowledgingCallback + if (acknowledging != null) { + acknowledging(message, deferAck()) + } else { + listener.callback(message) + } + } catch (e: Exception) { + report(e) + } + } + val wakeLock = acquireWakeLock(context) + try { + // The app's PushReceiver gets only messages no live callback received. + val handled = matching.isEmpty() && deliverToReceivers(context, message) + val titles = matching.filter { it.background }.map { it.title ?: message.topic } + + if (handled) emptyList() else entries.map { it.title ?: message.topic } + titles.distinct().forEach { notify(context, message, it) } + } finally { + releaseWakeLock(wakeLock) + } + } + + // Call every PushReceiver the app declares. Returns whether one handled the message. + private fun deliverToReceivers(context: Context, message: PushMessage): Boolean { + val intent = Intent(ACTION_MESSAGE).setPackage(context.packageName) + val receivers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.queryBroadcastReceivers(intent, PackageManager.ResolveInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + context.packageManager.queryBroadcastReceivers(intent, 0) + } + var handled = false + for (info in receivers) { + val name = info.activityInfo?.name ?: continue + try { + val receiver = Class.forName(name, true, context.classLoader).getDeclaredConstructor().newInstance() + if (receiver is PushReceiver && receiver.onMessage(context, message)) { + handled = true + } + } catch (e: Exception) { + report(e) + } + } + return handled + } + + /** Post a notification for [message] that opens the app, with the message in its extras. */ + fun notify(context: Context, message: PushMessage, title: String) { + val manager = NotificationManagerCompat.from(context) + if (!manager.areNotificationsEnabled()) { + return + } + createChannels(context) + val id = 31 * message.hashCode() + title.hashCode() + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setContentTitle(title) + .setContentText(message.data) + .setSmallIcon(notificationIcon(context)) + .setAutoCancel(true) + context.packageManager.getLaunchIntentForPackage(context.packageName)?.let { launch -> + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(EXTRA_TOPIC, message.topic) + .putExtra(EXTRA_PAYLOAD, message.data) + builder.setContentIntent( + PendingIntent.getActivity(context, id, launch, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE), + ) + } + try { + manager.notify(id, builder.build()) + } catch (e: SecurityException) { + // POST_NOTIFICATIONS not granted; nothing to show. + } + } + + /** The ongoing notification the foreground service shows, on its own quiet channel. */ + fun ongoingNotification(context: Context) = NotificationCompat.Builder(context, SERVICE_CHANNEL_ID) + .also { createChannels(context) } + .setContentTitle(ongoingTitle) + .setContentText("Listening for messages") + .setSmallIcon(notificationIcon(context)) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOngoing(true) + .build() + + private fun createChannels(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return + } + val manager = context.getSystemService(NotificationManager::class.java) ?: return + manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH)) + manager.createNotificationChannel( + NotificationChannel(SERVICE_CHANNEL_ID, "Background connection", NotificationManager.IMPORTANCE_LOW), + ) + } + + // The icon named by the app's ``, else a + // generic one. + private fun notificationIcon(context: Context): Int { + val metaData = runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.getApplicationInfo(context.packageName, PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong())) + } else { + @Suppress("DEPRECATION") + context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) + }.metaData + }.getOrNull() + return metaData?.getInt(NOTIFICATION_ICON, 0)?.takeIf { it != 0 } ?: android.R.drawable.stat_notify_chat + } + + private fun ensureService(context: Context) { + if (!wantsService(context)) { + if (serviceRunning) { + context.stopService(Intent(context, PushService::class.java)) + } + return + } + if (serviceRunning) { + return + } + try { + ContextCompat.startForegroundService(context, Intent(context, PushService::class.java)) + } catch (e: Exception) { + // Android 12+ refuses a foreground-service start from the background; the scheduled + // runs keep delivering, and the next start from the foreground succeeds. + if (!serviceStartReported) { + serviceStartReported = true + report(e) + } + } + } + + // Arm the next run in [delayMs]: the job, and an alarm just after it in case the job is late. + private fun schedule(context: Context, delayMs: Long, jobToo: Boolean = true) { + val interval = if (delayMs == INTERVAL_MS && privileged(context)) PRIVILEGED_INTERVAL_MS else delayMs + if (jobToo) { + try { + val job = JobInfo.Builder(JOB_ID, ComponentName(context, PushJobService::class.java)) + .setMinimumLatency(interval) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) + .setPersisted(true) + .build() + context.getSystemService(JobScheduler::class.java)?.schedule(job) + } catch (e: Exception) { + report(e) + } + } + val alarms = context.getSystemService(AlarmManager::class.java) ?: return + val at = SystemClock.elapsedRealtime() + interval + 1_000L + val intent = tickIntent(context) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarms.canScheduleExactAlarms()) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } else { + alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } catch (e: SecurityException) { + alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, intent) + } + } + + private fun cancelSchedule(context: Context) { + context.getSystemService(JobScheduler::class.java)?.cancel(JOB_ID) + context.getSystemService(AlarmManager::class.java)?.cancel(tickIntent(context)) + } + + private fun tickIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( + context, + 0, + Intent(context, PushAlarmReceiver::class.java).setAction(ACTION_TICK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + // Allowed exact alarms or exempt from battery optimisation: the alarm is reliable, so the + // runs can be spaced further apart. + private fun privileged(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.S || + context.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true || + context.getSystemService(PowerManager::class.java)?.isIgnoringBatteryOptimizations(context.packageName) == true + + private fun activeNetwork(context: Context): Network? = + runCatching { context.getSystemService(ConnectivityManager::class.java)?.activeNetwork }.getOrNull() + + private fun networkChanged(context: Context): Boolean { + val now = activeNetwork(context) + return now != null && connectedNetwork != null && now != connectedNetwork + } + + // Reconnect as soon as the default network changes (e.g. from cellular to Wi-Fi) while the + // process is alive, instead of waiting for the next run to notice. + private fun registerNetworkCallback(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + return + } + synchronized(lock) { + if (networkCallback != null) { + return + } + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + worker.execute { + if (mqtt != null && network != connectedNetwork) { + converge(context, heartbeat = false) + } + } + } + } + try { + context.getSystemService(ConnectivityManager::class.java)?.registerDefaultNetworkCallback(callback) + networkCallback = callback + } catch (e: Exception) { + report(e) + } + } + } + + private fun unregisterNetworkCallback(context: Context) { + val callback = synchronized(lock) { networkCallback.also { networkCallback = null } } ?: return + runCatching { context.getSystemService(ConnectivityManager::class.java)?.unregisterNetworkCallback(callback) } + } + + private fun acquireWakeLock(context: Context): PowerManager.WakeLock? = runCatching { + context.getSystemService(PowerManager::class.java) + ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Appwrite:push") + ?.apply { + setReferenceCounted(false) + acquire(WAKE_LOCK_MS) + } + }.getOrNull() + + private fun releaseWakeLock(wakeLock: PowerManager.WakeLock?) { + runCatching { + if (wakeLock?.isHeld == true) { + wakeLock.release() + } + } + } +} + +/** + * Background push state in the app's no-backup directory, so a restored backup on another + * device never carries this install's id or credential: the saved subscriptions with their + * connection config (cleared when background delivery stops), and the settings that outlive + * it (the install id, the foreground-mode choice, a refusal waiting for onError). + */ +internal object PushStore { + private const val STATE_FILE = "appwrite_push_state.json" + private const val SETTINGS_FILE = "appwrite_push_settings.json" + + fun loadState(context: Context): Pair>? = synchronized(this) { + val json = read(context, STATE_FILE) ?: return null + runCatching { + val config = json.getJSONObject("config").let { + PushConfig( + host = it.getString("host"), + port = it.getInt("port"), + tls = it.getBoolean("tls"), + tlsInsecure = it.getBoolean("tlsInsecure"), + clientId = it.getString("clientId"), + keepAlive = it.getInt("keepAlive"), + authMethod = it.getString("authMethod"), + credential = it.getString("credential"), + project = it.getString("project"), + ) + } + val list = json.getJSONArray("entries") + val entries = (0 until list.length()).map { index -> + val entry = list.getJSONObject(index) + PushEntry( + filter = entry.getString("filter"), + retry = entry.getBoolean("retry"), + title = if (entry.isNull("title")) null else entry.getString("title"), + ) + } + config to entries + }.getOrNull() + } + + fun saveState(context: Context, config: PushConfig, entries: List) = synchronized(this) { + val json = JSONObject() + .put( + "config", + JSONObject() + .put("host", config.host) + .put("port", config.port) + .put("tls", config.tls) + .put("tlsInsecure", config.tlsInsecure) + .put("clientId", config.clientId) + .put("keepAlive", config.keepAlive) + .put("authMethod", config.authMethod) + .put("credential", config.credential) + .put("project", config.project), + ) + .put( + "entries", + JSONArray(entries.map { JSONObject().put("filter", it.filter).put("retry", it.retry).put("title", it.title ?: JSONObject.NULL) }), + ) + write(context, STATE_FILE, json) + } + + fun clearState(context: Context) = synchronized(this) { + file(context, STATE_FILE).delete() + } + + /** A random id for this install, created once, which keeps the broker's replay position. */ + fun installId(context: Context): String = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: JSONObject() + settings.optString("installId").ifEmpty { + val id = UUID.randomUUID().toString() + write(context, SETTINGS_FILE, settings.put("installId", id)) + id + } + } + + fun foreground(context: Context): Boolean = synchronized(this) { + read(context, SETTINGS_FILE)?.optBoolean("foreground", false) ?: false + } + + fun setForeground(context: Context, enabled: Boolean) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("foreground", enabled)) + } + + /** The saved adaptive heartbeat; the default interval until one was saved. */ + fun heartbeat(context: Context): PushHeartbeat = synchronized(this) { + val json = read(context, SETTINGS_FILE)?.optJSONObject("heartbeat") ?: return PushHeartbeat(PushBackground.HEARTBEAT_MS) + PushHeartbeat( + intervalMs = json.optLong("intervalMs", PushBackground.HEARTBEAT_MS), + failures = json.optInt("failures", 0), + shrunkAt = json.optLong("shrunkAt", 0L), + ) + } + + fun setHeartbeat(context: Context, state: PushHeartbeat) = synchronized(this) { + val heartbeat = JSONObject() + .put("intervalMs", state.intervalMs) + .put("failures", state.failures) + .put("shrunkAt", state.shrunkAt) + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("heartbeat", heartbeat)) + } + + fun setStoppedError(context: Context, message: String) = synchronized(this) { + write(context, SETTINGS_FILE, (read(context, SETTINGS_FILE) ?: JSONObject()).put("stoppedError", message)) + } + + /** The refusal that stopped background delivery while no onError was registered, once. */ + fun takeStoppedError(context: Context): String? = synchronized(this) { + val settings = read(context, SETTINGS_FILE) ?: return null + val message = settings.optString("stoppedError").ifEmpty { return null } + settings.remove("stoppedError") + write(context, SETTINGS_FILE, settings) + message + } + + private fun file(context: Context, name: String) = AtomicFile(File(context.noBackupFilesDir, name)) + + private fun read(context: Context, name: String): JSONObject? = + runCatching { JSONObject(String(file(context, name).readFully(), Charsets.UTF_8)) }.getOrNull() + + private fun write(context: Context, name: String, json: JSONObject) { + val file = file(context, name) + val out = try { + file.startWrite() + } catch (e: IOException) { + Log.e(LOG_TAG, "Could not save push state", e) + return + } + try { + out.write(json.toString().toByteArray(Charsets.UTF_8)) + file.finishWrite(out) + } catch (e: IOException) { + file.failWrite(out) + Log.e(LOG_TAG, "Could not save push state", e) + } + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushBridge.kt b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt new file mode 100644 index 00000000..d7b79b5d --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushBridge.kt @@ -0,0 +1,135 @@ +package io.appwrite.services + +import android.content.Context +import android.os.SystemClock +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** + * The contract the React Native and Flutter SDKs use to host their background push + * subscriptions on this Android core, so they get the same delivery as the Android SDK: saved + * subscriptions, scheduled wake-ups after the process dies, notifications, and foreground mode. + * + * Both SDKs pass the same JSON: [host] takes the connection config and every live subscription, + * and each message for a live subscription comes back through [Events.onMessage] with its id and + * an acknowledgement token, which the SDK passes to [ack] once its callback has run (the broker's + * PUBACK waits for it, at most ten seconds). One bridge per process; hosting again replaces the + * live subscriptions. + */ +class PushBridge(context: Context, private val events: Events) { + /** Where messages and errors go; called on a background thread. */ + interface Events { + fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) + + fun onError(message: String) + } + + private val appContext = context.applicationContext + // Acknowledgement token -> (when it was handed out, the acknowledgement). A token the SDK never + // acknowledges (its JS or Dart side was gone) is dropped once the core has acknowledged the + // message anyway, so the map stays bounded. + private val acks = ConcurrentHashMap Unit>>() + + // Whether the app registered onError; without one, errors are logged and a refused + // credential is kept for the next registration. + @Volatile + private var errorCallback = false + + /** + * Host the subscriptions in [subscriptionsJson] on the background connection described by + * [configJson]. + * + * Config: `{"host", "port", "tls", "tlsInsecure", "clientId" (optional; per user and install + * when empty), "authMethod", "credential", "project"}`. Subscriptions: an array of + * `{"id", "topic", "background", "title" (optional), "retry"}`. + * + * [done] is called once the connection is up and every filter is subscribed, or with the + * failure's message; the SDK rejects its subscribe with it and reports it itself. + */ + fun host(configJson: String, subscriptionsJson: String, done: (String?) -> Unit) { + val json = JSONObject(configJson) + val authMethod = json.getString("authMethod") + val credential = json.getString("credential") + val config = PushConfig( + host = json.getString("host"), + port = json.getInt("port"), + tls = json.optBoolean("tls", false), + tlsInsecure = json.optBoolean("tlsInsecure", false), + clientId = json.optString("clientId").ifEmpty { defaultPushClientId(appContext, authMethod, credential) }, + keepAlive = KEEP_ALIVE_SECONDS, + authMethod = authMethod, + credential = credential, + project = json.optString("project"), + ) + val list = JSONArray(subscriptionsJson) + val listeners = (0 until list.length()).map { index -> + val subscription = list.getJSONObject(index) + val id = subscription.getString("id") + PushListener( + topics = setOf(subscription.getString("topic")), + callback = {}, + acknowledgingCallback = { message, ack -> + val token = UUID.randomUUID().toString() + val now = SystemClock.elapsedRealtime() + acks.entries.removeIf { now - it.value.first > STALE_ACK_MS } + acks[token] = now to ack + events.onMessage(id, message, token) + }, + background = subscription.optBoolean("background", false), + title = if (subscription.isNull("title")) null else subscription.optString("title").ifEmpty { null }, + retry = subscription.optBoolean("retry", true), + ) + } + PushBackground.errorHandler = { error -> + if (errorCallback) { + events.onError(error.message ?: error.toString()) + } + errorCallback + } + PushBackground.host(appContext, config, listeners) { error -> + done(error?.let { it.message ?: it.toString() }) + } + } + + /** Acknowledge a message once the SDK's callback for it has run. */ + fun ack(token: String) { + acks.remove(token)?.second?.invoke() + } + + /** Stop hosting the live subscriptions, keeping the ones saved by an earlier run. */ + fun release() = PushBackground.release(appContext) + + /** Stop background delivery and forget every saved subscription (sign-out). */ + fun stop() = PushBackground.stop(appContext) + + /** Run background delivery in a foreground service; saved across restarts. */ + fun setForeground(enabled: Boolean) = PushBackground.setForeground(appContext, enabled) + + /** Whether an earlier run saved background subscriptions that are still delivered. */ + fun hasSaved(): Boolean = PushBackground.hasSaved(appContext) + + /** Resume saved background delivery now instead of at the next scheduled run. */ + fun resume() = PushBackground.resume(appContext) + + /** + * Record whether the app has an onError callback. Returns the refusal that stopped background + * delivery while it had none, once, so the app can deliver it now. + */ + fun setErrorCallback(registered: Boolean): String? { + errorCallback = registered + return if (registered) PushStore.takeStoppedError(appContext) else null + } + + /** The default client id for a credential, so a foreground connection shares its session. */ + fun defaultClientId(authMethod: String, credential: String): String = + defaultPushClientId(appContext, authMethod, credential) + + private companion object { + const val KEEP_ALIVE_SECONDS = 60 + + // Past the core's ten-second acknowledgement cap, after which the message was acknowledged. + const val STALE_ACK_MS = 30_000L + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushCore.kt b/android/src/main/kotlin/io/appwrite/services/PushCore.kt new file mode 100644 index 00000000..20c56242 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushCore.kt @@ -0,0 +1,374 @@ +package io.appwrite.services + +import android.content.Context +import android.os.Build +import android.util.Base64 +import com.hivemq.client.mqtt.MqttClient +import com.hivemq.client.mqtt.datatypes.MqttUtf8String +import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext +import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient +import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientConfig +import com.hivemq.client.mqtt.mqtt5.auth.Mqtt5EnhancedAuthMechanism +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5ConnAckException +import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5DisconnectException +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5Auth +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5AuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5EnhancedAuthBuilder +import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck +import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAckReasonCode +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect +import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5DisconnectReasonCode +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish +import io.appwrite.exceptions.AppwriteException +import org.json.JSONObject +import java.security.KeyStore +import java.security.Provider +import java.security.cert.X509Certificate +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ExecutionException +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import javax.net.ssl.ManagerFactoryParameters +import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.TrustManagerFactorySpi +import javax.net.ssl.X509TrustManager + +/** + * A message delivered on a subscribed topic — the MQTT push analog of a realtime event. + */ +data class PushMessage( + val topic: String, + val payload: ByteArray, + val qos: Int, +) { + /** The payload decoded as UTF-8 text, as it was sent. */ + val data: String + get() = String(payload, Charsets.UTF_8) +} + +/** Connection parameters shared between the in-process client and the foreground service. */ +internal data class PushConfig( + val host: String, + val port: Int, + val tls: Boolean, + val tlsInsecure: Boolean, + val clientId: String, + val keepAlive: Int, + val authMethod: String, + val credential: String, + val project: String, +) + +/** + * The userId claim from an Appwrite JWT, used as the default MQTT client id so the + * broker's replay cursor is stable per user. Returns "" when the token is not a decodable JWT + * (e.g. a session secret), so the caller can fall back to the raw credential. + */ +internal fun userIdFromJwt(jwt: String): String { + val parts = jwt.split('.') + if (parts.size < 2) { + return "" + } + return runCatching { + val json = String( + Base64.decode(parts[1], Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING), + Charsets.UTF_8, + ) + JSONObject(json).optString("userId", "") + }.getOrDefault("") +} + +/** The user `id` from an Appwrite session secret, or "" when it is not decodable. */ +internal fun userIdFromSession(session: String): String = runCatching { + val json = String(Base64.decode(session, Base64.DEFAULT), Charsets.UTF_8) + JSONObject(json).optString("id", "") +}.getOrDefault("") + +/** + * The default MQTT client id: one per user and install (`-`, or the install id + * alone when the credential names no user). The broker keeps the replay position per user and + * client id, so each device resumes its own backlog across restarts, and two devices of one user + * do not take over each other's session. + */ +internal fun defaultPushClientId(context: Context, authMethod: String, credential: String): String { + val userId = if (authMethod == "appwrite-session") userIdFromSession(credential) else userIdFromJwt(credential) + val installId = PushStore.installId(context) + return if (userId.isEmpty()) installId else "$userId-$installId" +} + +/** + * Build (but do not connect) an MQTT 5 client from [config]. [onError] receives every connection + * error (a lost connection, a failed automatic reconnect, a broker DISCONNECT) except a refused + * initial CONNECT, which [pushConnect] throws instead. + */ +internal fun buildPushClient( + config: PushConfig, + onConnected: (() -> Unit)? = null, + onDisconnected: (() -> Unit)? = null, + onError: ((Throwable) -> Unit)? = null, + onAuthRefused: ((Throwable) -> Unit)? = null, +): Mqtt5AsyncClient { + // config.clientId is stable per user (see buildConfig), so a reconnect rebuild reuses it + // and resumes the same session. + var builder = MqttClient.builder() + .useMqttVersion5() + .serverHost(config.host) + .serverPort(config.port) + // Recover from an unexpected disconnect (network drop, broker restart) with HiveMQ's + // exponential backoff. A user-initiated disconnect() (see close()) does not trigger it. + // Because clean start is off and the broker resumes the same session, subscriptions and + // the QoS-1 replay cursor persist, so delivery continues without resubscribing (which + // would stack a second per-subscription callback). + .automaticReconnectWithDefaultConfig() + + if (config.clientId.isNotEmpty()) { + builder = builder.identifier(config.clientId) + } + + // Whether this client has connected yet: until it has, a refused CONNECT is final. + val connected = AtomicBoolean(false) + builder = builder.addConnectedListener { + connected.set(true) + onConnected?.invoke() + } + builder = builder.addDisconnectedListener { context -> + // A refused first CONNECT (bad credential, rate limit) is final: stop the automatic + // reconnect so pushConnect fails with the broker's reason instead of retrying forever. + val refused = !connected.get() && context.cause is Mqtt5ConnAckException + // With [onAuthRefused], a credential refused later (a failed automatic reconnect or + // re-auth) is final too, instead of being retried with the same credential forever. + val authRefused = onAuthRefused != null && connected.get() && + context.source != MqttDisconnectSource.USER && isAuthRefusal(context.cause) + if (refused || authRefused) { + context.reconnector.reconnect(false) + } + onDisconnected?.invoke() + if (!refused) { + val error = pushDisconnectError(context) + if (authRefused && error != null) { + // Reported by onAuthRefused, which also stops for good. + onAuthRefused?.invoke(error) + } else { + error?.let { onError?.invoke(it) } + } + } + } + + if (config.tls) { + builder = if (config.tlsInsecure) { + builder.sslConfig() + .trustManagerFactory(PushInsecureTrustManagerFactory) + .hostnameVerifier { _, _ -> true } + .applySslConfig() + } else { + builder.sslWithDefaultConfig() + } + } + + return builder.buildAsync() +} + +/** + * Connect with Appwrite enhanced auth; blocks until CONNACK. Throws an + * [AppwriteException] on failure, whose message is the broker's MQTT 5 + * Reason String when it refused the CONNECT with one. + */ +internal fun Mqtt5AsyncClient.pushConnect(config: PushConfig) { + try { + sendPushConnect(config) + } catch (e: Exception) { + throw connectError((e as? ExecutionException)?.cause ?: e) + } +} + +/** The error a failed CONNECT reports: the broker's Reason String when it refused one. */ +internal fun connectError(cause: Throwable): AppwriteException = + if (cause is Mqtt5ConnAckException) { + connAckError(cause) + } else { + AppwriteException(cause.message ?: "MQTT connection failed") + } + +/** + * Whether [error] is the broker refusing the credential (a CONNECT or re-auth), which retrying + * with the same credential cannot fix, unlike a rate limit or a network failure. + */ +internal fun isAuthRefusal(error: Throwable?): Boolean = when (error) { + is Mqtt5ConnAckException -> error.mqttMessage.reasonCode in setOf( + Mqtt5ConnAckReasonCode.NOT_AUTHORIZED, + Mqtt5ConnAckReasonCode.BAD_USER_NAME_OR_PASSWORD, + Mqtt5ConnAckReasonCode.BAD_AUTHENTICATION_METHOD, + Mqtt5ConnAckReasonCode.BANNED, + ) + is Mqtt5DisconnectException -> error.mqttMessage.reasonCode == Mqtt5DisconnectReasonCode.NOT_AUTHORIZED + else -> false +} + +/** Send the CONNECT and wait for the CONNACK, at most [timeoutSeconds] when given. */ +internal fun Mqtt5AsyncClient.sendPushConnect(config: PushConfig, timeoutSeconds: Long? = null) { + val connAck = connectWith() + .enhancedAuth(PushAuthMechanism(config.authMethod, config.credential)) + // Clean start is always off, so the broker keeps this client's session and can + // redeliver missed messages to QoS-1 subscriptions on reconnect. + .cleanStart(false) + .keepAlive(config.keepAlive) + .userProperties() + .add("projectId", config.project) + .applyUserProperties() + .send() + if (timeoutSeconds == null) { + connAck.get() + } else { + connAck.get(timeoutSeconds, TimeUnit.SECONDS) + } +} + +/** + * The error a lost connection reports, or null when it is not an error (a disconnect the app + * asked for, or a broker DISCONNECT with a success reason code). The broker explains a refused + * CONNECT or a DISCONNECT it sends with an MQTT 5 Reason String, which becomes the message. + */ +internal fun pushDisconnectError(context: MqttClientDisconnectedContext): Throwable? { + val cause = context.cause + return when { + context.source == MqttDisconnectSource.USER -> null + cause is Mqtt5ConnAckException -> connAckError(cause) + cause is Mqtt5DisconnectException && context.source == MqttDisconnectSource.SERVER -> { + val disconnect = cause.mqttMessage + if (disconnect.reasonCode.isError) { + AppwriteException( + disconnect.reasonString.map { it.toString() } + .orElse("Disconnected by the broker (reason ${disconnect.reasonCode})"), + ) + } else { + null + } + } + else -> cause + } +} + +/** A refused CONNECT, with the CONNACK Reason String as its message when the broker sent one. */ +internal fun connAckError(e: Mqtt5ConnAckException): AppwriteException = + AppwriteException( + e.mqttMessage.reasonString.map { it.toString() }.orElse(e.message ?: "MQTT connection refused"), + ) + +internal fun Mqtt5Publish.toPushMessage(): PushMessage = + PushMessage( + topic = topic.toString(), + payload = payloadAsBytes, + qos = qos.code, + ) + +/** + * Single-step MQTT 5 enhanced auth: the method and credential are placed in the CONNECT + * packet and the broker accepts them in the CONNACK, with no AUTH round-trip. + */ +internal class PushAuthMechanism( + private val method: String, + private val credential: String, +) : Mqtt5EnhancedAuthMechanism { + + override fun getMethod(): MqttUtf8String = MqttUtf8String.of(method) + + override fun getTimeout(): Int = 30 + + override fun onAuth( + clientConfig: Mqtt5ClientConfig, + connect: Mqtt5Connect, + authBuilder: Mqtt5EnhancedAuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onReAuth( + clientConfig: Mqtt5ClientConfig, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture { + authBuilder.data(credential.toByteArray(Charsets.UTF_8)) + return CompletableFuture.completedFuture(null) + } + + override fun onContinue( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + authBuilder: Mqtt5AuthBuilder, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthSuccess( + clientConfig: Mqtt5ClientConfig, + connAck: Mqtt5ConnAck, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onReAuthSuccess( + clientConfig: Mqtt5ClientConfig, + auth: Mqtt5Auth, + ): CompletableFuture = CompletableFuture.completedFuture(true) + + override fun onAuthRejected(clientConfig: Mqtt5ClientConfig, connAck: Mqtt5ConnAck) = Unit + + override fun onReAuthRejected(clientConfig: Mqtt5ClientConfig, disconnect: Mqtt5Disconnect) = Unit + + override fun onAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit + + override fun onReAuthError(clientConfig: Mqtt5ClientConfig, cause: Throwable) = Unit +} + +/** + * A [TrustManagerFactory] that accepts any certificate — used when `tlsInsecure` is set + * (for a broker whose certificate does not chain to a public root). + */ +internal object PushInsecureTrustManagerFactory : TrustManagerFactory( + object : TrustManagerFactorySpi() { + override fun engineInit(keyStore: KeyStore?) = Unit + + override fun engineInit(parameters: ManagerFactoryParameters?) = Unit + + override fun engineGetTrustManagers(): Array = arrayOf( + object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + + override fun getAcceptedIssuers(): Array = emptyArray() + }, + ) + }, + @Suppress("DEPRECATION") object : Provider("AppwriteInsecure", 1.0, "insecure trust-all") {}, + "AppwriteInsecure", +) + +/** A live in-app subscription hosted in the background: its topics, callback, notification opt-in and QoS. */ +internal class PushListener( + val topics: Set, + val callback: (PushMessage) -> Unit, + val background: Boolean, + val title: String?, + val retry: Boolean, + // Called instead of [callback] when set, with the acknowledgement to run once the message was + // handled: the React Native and Flutter bridges acknowledge after their callback has run. + val acknowledgingCallback: ((PushMessage, () -> Unit) -> Unit)? = null, +) + +/** MQTT topic-filter match with '+' (single level) and '#' (multi level). */ +internal fun matchesTopic(filter: String, topic: String): Boolean { + val filterParts = filter.split('/') + val topicParts = topic.split('/') + for (i in filterParts.indices) { + if (filterParts[i] == "#") { + return true + } + if (i >= topicParts.size) { + return false + } + if (filterParts[i] != "+" && filterParts[i] != topicParts[i]) { + return false + } + } + return filterParts.size == topicParts.size +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt new file mode 100644 index 00000000..92d04727 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushReceiver.kt @@ -0,0 +1,33 @@ +package io.appwrite.services + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * Handles background push messages in code when no in-app callback is listening, e.g. after + * the process was started in the background to reconnect. Subclass it and declare it in your + * manifest with the push message action: + * + * ```xml + * + * + * + * + * + * ``` + * + * The SDK calls [onMessage] directly on a background thread, under a wakelock of about ten + * seconds, so hand longer work to WorkManager. Messages a live callback receives do not + * reach it. + */ +abstract class PushReceiver : BroadcastReceiver() { + /** + * Handle [message]. Return true when you handled it yourself, so the SDK does not post its + * default notification; return false to have it posted as well. + */ + abstract fun onMessage(context: Context, message: PushMessage): Boolean + + // Messages arrive through onMessage, never as a broadcast. + final override fun onReceive(context: Context, intent: Intent) = Unit +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushService.kt b/android/src/main/kotlin/io/appwrite/services/PushService.kt new file mode 100644 index 00000000..e2a05f89 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushService.kt @@ -0,0 +1,67 @@ +package io.appwrite.services + +import android.app.Service +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.ServiceCompat + +/** + * The foreground mode of background push delivery ([Push.setForeground]): a foreground service + * that keeps the process at foreground priority, so the connection held by the process stays + * up and delivers immediately, also during Doze. The system restarts it after a kill, and it + * restores the saved subscriptions. Started by the SDK; not meant to be started directly. + */ +class PushService : Service() { + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + PushBackground.serviceRunning = true + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (!PushBackground.wantsService(this)) { + stopSelf() + return START_NOT_STICKY + } + try { + startForegroundCompat() + } catch (e: Exception) { + // E.g. a background start refused on Android 12+; the scheduled runs keep delivering. + stopSelf() + PushBackground.report(e) + return START_NOT_STICKY + } + PushBackground.tick(this) {} + // Recreated after a kill with a null intent; the saved subscriptions are restored then. + return START_STICKY + } + + private fun startForegroundCompat() { + val notification = PushBackground.ongoingNotification(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceCompat.startForeground( + this, + PushBackground.NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING, + ) + } else { + startForeground(PushBackground.NOTIFICATION_ID, notification) + } + } + + // Some devices kill the process shortly after its task is swiped away; a run a few seconds + // later restarts the service. + override fun onTaskRemoved(rootIntent: Intent?) { + PushBackground.scheduleRestart(this) + super.onTaskRemoved(rootIntent) + } + + override fun onDestroy() { + PushBackground.serviceRunning = false + super.onDestroy() + } +} diff --git a/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt new file mode 100644 index 00000000..091fd528 --- /dev/null +++ b/android/src/main/kotlin/io/appwrite/services/PushWakeups.kt @@ -0,0 +1,46 @@ +package io.appwrite.services + +import android.app.job.JobParameters +import android.app.job.JobService +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * The scheduled run of background push delivery: reconnects and re-arms itself. Scheduled + * by the SDK; not meant to be started directly. + */ +class PushJobService : JobService() { + override fun onStartJob(params: JobParameters): Boolean { + PushBackground.tick(this) { jobFinished(params, false) } + return true + } + + // The run re-arms the next one itself, so a stopped run needs no retry. + override fun onStopJob(params: JobParameters): Boolean = false +} + +/** + * The alarm that backs up the scheduled job when it runs late. Scheduled by the SDK; not meant + * to be sent directly. + */ +class PushAlarmReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != PushBackground.ACTION_TICK) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} + +/** Resumes background push delivery after a reboot or an app update. */ +class PushBootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) { + return + } + val pending = goAsync() + PushBackground.tick(context) { pending.finish() } + } +} diff --git a/docs/examples/account/create-anonymous-session.md b/docs/examples/account/create-anonymous-session.md index 0cdedf8f..5fa3803b 100644 --- a/docs/examples/account/create-anonymous-session.md +++ b/docs/examples/account/create-anonymous-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Session result = await account.createAnonymousSession(); +models.Session result = await account.createAnonymousSession(); ``` diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index d444996d..e40921bd 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,8 +8,9 @@ Client client = Client() Account account = Account(client); -Session result = await account.createEmailPasswordSession( +models.Session result = await account.createEmailPasswordSession( email: 'email@example.com', password: 'password', + duration: 60, // optional ); ``` diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index 73890581..a2b3d4cc 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailToken( +models.Token result = await account.createEmailToken( userId: '', email: 'email@example.com', phrase: false, // optional diff --git a/docs/examples/account/create-email-verification-otp.md b/docs/examples/account/create-email-verification-otp.md index 941db965..0e7cc23c 100644 --- a/docs/examples/account/create-email-verification-otp.md +++ b/docs/examples/account/create-email-verification-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailVerificationOTP( +models.Token result = await account.createEmailVerificationOTP( phrase: false, // optional ); ``` diff --git a/docs/examples/account/create-email-verification.md b/docs/examples/account/create-email-verification.md index d88979c8..48011dba 100644 --- a/docs/examples/account/create-email-verification.md +++ b/docs/examples/account/create-email-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createEmailVerification( +models.Token result = await account.createEmailVerification( url: 'https://example.com', ); ``` diff --git a/docs/examples/account/create-id-token-session.md b/docs/examples/account/create-id-token-session.md index 61f84065..f667ea96 100644 --- a/docs/examples/account/create-id-token-session.md +++ b/docs/examples/account/create-id-token-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.createIdTokenSession( +models.Session result = await account.createIdTokenSession( provider: enums.IdTokenProvider.apple, idToken: '', nonce: '', // optional diff --git a/docs/examples/account/create-jwt.md b/docs/examples/account/create-jwt.md index 72ff1180..dee4f4d9 100644 --- a/docs/examples/account/create-jwt.md +++ b/docs/examples/account/create-jwt.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Jwt result = await account.createJWT( +models.Jwt result = await account.createJWT( duration: 0, // optional ); ``` diff --git a/docs/examples/account/create-magic-url-token.md b/docs/examples/account/create-magic-url-token.md index 59d1cc24..fc04f508 100644 --- a/docs/examples/account/create-magic-url-token.md +++ b/docs/examples/account/create-magic-url-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createMagicURLToken( +models.Token result = await account.createMagicURLToken( userId: '', email: 'email@example.com', url: 'https://example.com', // optional diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index c86de3ba..7dc8321c 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -MfaType result = await account.createMFAAuthenticator( +models.MfaType result = await account.createMFAAuthenticator( type: enums.AuthenticatorType.totp, ); ``` diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index c7007d32..f5f71618 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -MfaChallenge result = await account.createMFAChallenge( +models.MfaChallenge result = await account.createMFAChallenge( factor: enums.AuthenticationFactor.email, ); ``` diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index 252dec7a..d39925f4 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.createMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.createMFARecoveryCodes(); ``` diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index 95799d62..907f85bd 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createPhoneToken( +models.Token result = await account.createPhoneToken( userId: '', phone: '+12065550100', ); diff --git a/docs/examples/account/create-phone-verification.md b/docs/examples/account/create-phone-verification.md index 9fc84dfc..0fd3951a 100644 --- a/docs/examples/account/create-phone-verification.md +++ b/docs/examples/account/create-phone-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Token result = await account.createPhoneVerification(); +models.Token result = await account.createPhoneVerification(); ``` diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index d493b2a0..250cd4db 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Target result = await account.createPushTarget( +models.Target result = await account.createPushTarget( targetId: '', identifier: '', providerId: '', // optional diff --git a/docs/examples/account/create-recovery-otp.md b/docs/examples/account/create-recovery-otp.md index 366469f3..a081194e 100644 --- a/docs/examples/account/create-recovery-otp.md +++ b/docs/examples/account/create-recovery-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createRecoveryOTP( +models.Token result = await account.createRecoveryOTP( email: 'email@example.com', phrase: false, // optional ); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index fe5ecfa0..d59589fe 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createRecovery( +models.Token result = await account.createRecovery( email: 'email@example.com', url: 'https://example.com', ); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index ebac1f93..3cf9382f 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.createSession( +models.Session result = await account.createSession( userId: '', secret: '', ); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index c36cb8f3..08896cbc 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.createVerification( +models.Token result = await account.createVerification( url: 'https://example.com', ); ``` diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index 8343f628..6f1350aa 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.create( +models.User result = await account.create( userId: '', email: 'email@example.com', password: 'password', diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index e8e8ba1a..388661a9 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -7,5 +7,7 @@ Client client = Client() Account account = Account(client); -await account.deleteSessions(); +await account.deleteSessions( + current: false, // optional +); ``` diff --git a/docs/examples/account/get-consent-token.md b/docs/examples/account/get-consent-token.md index 67a0d842..4454000a 100644 --- a/docs/examples/account/get-consent-token.md +++ b/docs/examples/account/get-consent-token.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentToken result = await account.getConsentToken( +models.Oauth2ConsentToken result = await account.getConsentToken( consentId: '', tokenId: '', ); diff --git a/docs/examples/account/get-consent.md b/docs/examples/account/get-consent.md index aff62725..5fcf846e 100644 --- a/docs/examples/account/get-consent.md +++ b/docs/examples/account/get-consent.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2Consent result = await account.getConsent( +models.Oauth2Consent result = await account.getConsent( consentId: '', ); ``` diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index ed5531a3..889252fd 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.getMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.getMFARecoveryCodes(); ``` diff --git a/docs/examples/account/get-prefs.md b/docs/examples/account/get-prefs.md index dc359f9c..a2407a58 100644 --- a/docs/examples/account/get-prefs.md +++ b/docs/examples/account/get-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -Preferences result = await account.getPrefs(); +models.Preferences result = await account.getPrefs(); ``` diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index c27058a8..10ca295e 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.getSession( +models.Session result = await account.getSession( sessionId: '', ); ``` diff --git a/docs/examples/account/get.md b/docs/examples/account/get.md index 1bd67c6a..52c6dbb6 100644 --- a/docs/examples/account/get.md +++ b/docs/examples/account/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -User result = await account.get(); +models.User result = await account.get(); ``` diff --git a/docs/examples/account/list-consent-tokens.md b/docs/examples/account/list-consent-tokens.md index 835c7775..58f12a41 100644 --- a/docs/examples/account/list-consent-tokens.md +++ b/docs/examples/account/list-consent-tokens.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentTokenList result = await account.listConsentTokens( +models.Oauth2ConsentTokenList result = await account.listConsentTokens( consentId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/account/list-consents.md b/docs/examples/account/list-consents.md index d39f0547..cae45ca3 100644 --- a/docs/examples/account/list-consents.md +++ b/docs/examples/account/list-consents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Oauth2ConsentList result = await account.listConsents( +models.Oauth2ConsentList result = await account.listConsents( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index d0c0e5b6..73c900ec 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -IdentityList result = await account.listIdentities( +models.IdentityList result = await account.listIdentities( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index 4cfcf88b..98e1815e 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaFactors result = await account.listMFAFactors(); +models.MfaFactors result = await account.listMFAFactors(); ``` diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 18db93bb..21bdd898 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Account account = Account(client); -SessionList result = await account.listSessions(); +models.SessionList result = await account.listSessions( + total: false, // optional +); ``` diff --git a/docs/examples/account/update-email-verification-otp.md b/docs/examples/account/update-email-verification-otp.md index 52ff4c11..f4572d83 100644 --- a/docs/examples/account/update-email-verification-otp.md +++ b/docs/examples/account/update-email-verification-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateEmailVerificationOTP( +models.Token result = await account.updateEmailVerificationOTP( userId: '', secret: '', ); diff --git a/docs/examples/account/update-email-verification.md b/docs/examples/account/update-email-verification.md index 7e3975e9..828013f1 100644 --- a/docs/examples/account/update-email-verification.md +++ b/docs/examples/account/update-email-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateEmailVerification( +models.Token result = await account.updateEmailVerification( userId: '', secret: '', ); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index e5e1a169..13cc2d7c 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateEmail( +models.User result = await account.updateEmail( email: 'email@example.com', password: 'password', ); diff --git a/docs/examples/account/update-magic-url-session.md b/docs/examples/account/update-magic-url-session.md index c45dcf1e..590d6f9e 100644 --- a/docs/examples/account/update-magic-url-session.md +++ b/docs/examples/account/update-magic-url-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateMagicURLSession( +models.Session result = await account.updateMagicURLSession( userId: '', secret: '', ); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 539c5e28..bb946951 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateMFAAuthenticator( +models.User result = await account.updateMFAAuthenticator( type: enums.AuthenticatorType.totp, otp: '', ); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index 55f4ebee..8e1ee662 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateMFAChallenge( +models.Session result = await account.updateMFAChallenge( challengeId: '', otp: '', ); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 7a188d40..88e5284e 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -MfaRecoveryCodes result = await account.updateMFARecoveryCodes(); +models.MfaRecoveryCodes result = await account.updateMFARecoveryCodes(); ``` diff --git a/docs/examples/account/update-mfa.md b/docs/examples/account/update-mfa.md index db9addd6..fd5826bc 100644 --- a/docs/examples/account/update-mfa.md +++ b/docs/examples/account/update-mfa.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateMFA( +models.User result = await account.updateMFA( mfa: false, ); ``` diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index 8ab71223..cf9064db 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updateName( +models.User result = await account.updateName( name: '', ); ``` diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index c2604a9c..e5e5495f 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePassword( +models.User result = await account.updatePassword( password: 'password', oldPassword: 'password', // optional ); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index f538680a..4137cece 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updatePhoneSession( +models.Session result = await account.updatePhoneSession( userId: '', secret: '', ); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index de226a7c..dc2afd5c 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updatePhoneVerification( +models.Token result = await account.updatePhoneVerification( userId: '', secret: '', ); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index f631c5df..914b64d2 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePhone( +models.User result = await account.updatePhone( phone: '+12065550100', password: 'password', ); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index 6f9863d3..2ae515f6 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -User result = await account.updatePrefs( +models.User result = await account.updatePrefs( prefs: { "language": "en", "timezone": "UTC", diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index 601f3aec..49429983 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Target result = await account.updatePushTarget( +models.Target result = await account.updatePushTarget( targetId: '', identifier: '', ); diff --git a/docs/examples/account/update-recovery-otp.md b/docs/examples/account/update-recovery-otp.md index f7b4a2ef..0103c951 100644 --- a/docs/examples/account/update-recovery-otp.md +++ b/docs/examples/account/update-recovery-otp.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateRecoveryOTP( +models.Token result = await account.updateRecoveryOTP( userId: '', secret: '', password: 'password', diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index 809aa044..8d85a1fa 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateRecovery( +models.Token result = await account.updateRecovery( userId: '', secret: '', password: 'password', diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index 7fb334aa..18fe1ede 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Session result = await account.updateSession( +models.Session result = await account.updateSession( sessionId: '', ); ``` diff --git a/docs/examples/account/update-status.md b/docs/examples/account/update-status.md index d7b0d0dc..88c9ecff 100644 --- a/docs/examples/account/update-status.md +++ b/docs/examples/account/update-status.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Account account = Account(client); -User result = await account.updateStatus(); +models.User result = await account.updateStatus(); ``` diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index 339b4b91..433677aa 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Account account = Account(client); -Token result = await account.updateVerification( +models.Token result = await account.updateVerification( userId: '', secret: '', ); diff --git a/docs/examples/apps/create-installation-token.md b/docs/examples/apps/create-installation-token.md new file mode 100644 index 00000000..32b738ae --- /dev/null +++ b/docs/examples/apps/create-installation-token.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.Oauth2Token result = await apps.createInstallationToken( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/create-key.md b/docs/examples/apps/create-key.md new file mode 100644 index 00000000..6e8974b7 --- /dev/null +++ b/docs/examples/apps/create-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKey result = await apps.createKey( + appId: '', +); +``` diff --git a/docs/examples/apps/create-secret.md b/docs/examples/apps/create-secret.md new file mode 100644 index 00000000..c7c46ea0 --- /dev/null +++ b/docs/examples/apps/create-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecretPlaintext result = await apps.createSecret( + appId: '', +); +``` diff --git a/docs/examples/apps/create.md b/docs/examples/apps/create.md new file mode 100644 index 00000000..0613f535 --- /dev/null +++ b/docs/examples/apps/create.md @@ -0,0 +1,32 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.create( + appId: '', + name: '', + redirectUris: [], + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + postLogoutRedirectUris: [], // optional + enabled: false, // optional + type: 'public', // optional + deviceFlow: false, // optional + teamId: '', // optional +); +``` diff --git a/docs/examples/apps/delete-installation.md b/docs/examples/apps/delete-installation.md new file mode 100644 index 00000000..55707ce0 --- /dev/null +++ b/docs/examples/apps/delete-installation.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/delete-key.md b/docs/examples/apps/delete-key.md new file mode 100644 index 00000000..e6bd4065 --- /dev/null +++ b/docs/examples/apps/delete-key.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/delete-secret.md b/docs/examples/apps/delete-secret.md new file mode 100644 index 00000000..0e7a1506 --- /dev/null +++ b/docs/examples/apps/delete-secret.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/delete-tokens.md b/docs/examples/apps/delete-tokens.md new file mode 100644 index 00000000..cdba07ee --- /dev/null +++ b/docs/examples/apps/delete-tokens.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.deleteTokens( + appId: '', +); +``` diff --git a/docs/examples/apps/delete.md b/docs/examples/apps/delete.md new file mode 100644 index 00000000..e56502a6 --- /dev/null +++ b/docs/examples/apps/delete.md @@ -0,0 +1,13 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +await apps.delete( + appId: '', +); +``` diff --git a/docs/examples/apps/get-installation.md b/docs/examples/apps/get-installation.md new file mode 100644 index 00000000..0d31b69a --- /dev/null +++ b/docs/examples/apps/get-installation.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppInstallation result = await apps.getInstallation( + appId: '', + installationId: '', +); +``` diff --git a/docs/examples/apps/get-key.md b/docs/examples/apps/get-key.md new file mode 100644 index 00000000..29cb78f4 --- /dev/null +++ b/docs/examples/apps/get-key.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKey result = await apps.getKey( + appId: '', + keyId: '', +); +``` diff --git a/docs/examples/apps/get-secret.md b/docs/examples/apps/get-secret.md new file mode 100644 index 00000000..d6c39ca9 --- /dev/null +++ b/docs/examples/apps/get-secret.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecret result = await apps.getSecret( + appId: '', + secretId: '', +); +``` diff --git a/docs/examples/apps/get.md b/docs/examples/apps/get.md new file mode 100644 index 00000000..a70e4c91 --- /dev/null +++ b/docs/examples/apps/get.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.get( + appId: '', +); +``` diff --git a/docs/examples/apps/list-installation-scopes.md b/docs/examples/apps/list-installation-scopes.md new file mode 100644 index 00000000..2bd15fe2 --- /dev/null +++ b/docs/examples/apps/list-installation-scopes.md @@ -0,0 +1,12 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppScopeList result = await apps.listInstallationScopes(); +``` diff --git a/docs/examples/apps/list-installations.md b/docs/examples/apps/list-installations.md new file mode 100644 index 00000000..1463bc7f --- /dev/null +++ b/docs/examples/apps/list-installations.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppInstallationList result = await apps.listInstallations( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-keys.md b/docs/examples/apps/list-keys.md new file mode 100644 index 00000000..f52f2754 --- /dev/null +++ b/docs/examples/apps/list-keys.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppKeyList result = await apps.listKeys( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list-o-auth-2-scopes.md b/docs/examples/apps/list-o-auth-2-scopes.md new file mode 100644 index 00000000..08755449 --- /dev/null +++ b/docs/examples/apps/list-o-auth-2-scopes.md @@ -0,0 +1,12 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppScopeList result = await apps.listOAuth2Scopes(); +``` diff --git a/docs/examples/apps/list-secrets.md b/docs/examples/apps/list-secrets.md new file mode 100644 index 00000000..51998b3c --- /dev/null +++ b/docs/examples/apps/list-secrets.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppSecretList result = await apps.listSecrets( + appId: '', + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/list.md b/docs/examples/apps/list.md new file mode 100644 index 00000000..e7868580 --- /dev/null +++ b/docs/examples/apps/list.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.AppsList result = await apps.list( + queries: [], // optional + total: false, // optional +); +``` diff --git a/docs/examples/apps/update-team.md b/docs/examples/apps/update-team.md new file mode 100644 index 00000000..adcd2361 --- /dev/null +++ b/docs/examples/apps/update-team.md @@ -0,0 +1,15 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.updateTeam( + appId: '', + teamId: '', +); +``` diff --git a/docs/examples/apps/update.md b/docs/examples/apps/update.md new file mode 100644 index 00000000..38ceb19a --- /dev/null +++ b/docs/examples/apps/update.md @@ -0,0 +1,33 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Apps apps = Apps(client); + +models.App result = await apps.update( + appId: '', + name: '', + description: '', // optional + clientUri: 'https://example.com', // optional + logoUri: 'https://example.com', // optional + privacyPolicyUrl: 'https://example.com', // optional + termsUrl: 'https://example.com', // optional + contacts: [], // optional + tagline: '', // optional + tags: [], // optional + images: [], // optional + supportUrl: 'https://example.com', // optional + dataDeletionUrl: 'https://example.com', // optional + enabled: false, // optional + redirectUris: [], // optional + postLogoutRedirectUris: [], // optional + type: 'public', // optional + deviceFlow: false, // optional + installationScopes: [], // optional + installationRedirectUrl: 'https://example.com', // optional +); +``` diff --git a/docs/examples/avatars/delete-photo.md b/docs/examples/avatars/delete-photo.md new file mode 100644 index 00000000..390a3192 --- /dev/null +++ b/docs/examples/avatars/delete-photo.md @@ -0,0 +1,11 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +await avatars.deletePhoto(); +``` diff --git a/docs/examples/avatars/get-screenshot.md b/docs/examples/avatars/get-screenshot.md index daa38d17..1a22a692 100644 --- a/docs/examples/avatars/get-screenshot.md +++ b/docs/examples/avatars/get-screenshot.md @@ -15,8 +15,7 @@ Avatars avatars = Avatars(client); Uint8List bytes = await avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional @@ -46,8 +45,7 @@ FutureBuilder( future: avatars.getScreenshot( url: 'https://example.com', headers: { - "Authorization": "Bearer token123", - "X-Custom-Header": "value" + "Accept-Language": "en-US,en;q=0.9" }, // optional viewportWidth: 1920, // optional viewportHeight: 1080, // optional diff --git a/docs/examples/avatars/update-photo.md b/docs/examples/avatars/update-photo.md new file mode 100644 index 00000000..e667a94a --- /dev/null +++ b/docs/examples/avatars/update-photo.md @@ -0,0 +1,15 @@ +```dart +import 'dart:io'; +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Avatars avatars = Avatars(client); + +models.Account result = await avatars.updatePhoto( + file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), +); +``` diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index a4df848f..ade4f576 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.createDocument( +models.Document result = await databases.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/create-operations.md b/docs/examples/databases/create-operations.md index 0551c28b..e3528d32 100644 --- a/docs/examples/databases/create-operations.md +++ b/docs/examples/databases/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.createOperations( +models.Transaction result = await databases.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/databases/create-transaction.md b/docs/examples/databases/create-transaction.md index 14ea5563..b7ccbf21 100644 --- a/docs/examples/databases/create-transaction.md +++ b/docs/examples/databases/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.createTransaction( +models.Transaction result = await databases.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/databases/decrement-document-attribute.md b/docs/examples/databases/decrement-document-attribute.md index 0d178cff..6780426c 100644 --- a/docs/examples/databases/decrement-document-attribute.md +++ b/docs/examples/databases/decrement-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.decrementDocumentAttribute( +models.Document result = await databases.decrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index 1f384afd..fabd67df 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.getDocument( +models.Document result = await databases.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/get-transaction.md b/docs/examples/databases/get-transaction.md index 142b8bfa..012e2e27 100644 --- a/docs/examples/databases/get-transaction.md +++ b/docs/examples/databases/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.getTransaction( +models.Transaction result = await databases.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/databases/increment-document-attribute.md b/docs/examples/databases/increment-document-attribute.md index 05b3690e..dce65a73 100644 --- a/docs/examples/databases/increment-document-attribute.md +++ b/docs/examples/databases/increment-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.incrementDocumentAttribute( +models.Document result = await databases.incrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index 531be6ad..090e731a 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -DocumentList result = await databases.listDocuments( +models.DocumentList result = await databases.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/databases/list-transactions.md b/docs/examples/databases/list-transactions.md index ca9ff6fb..d090af1e 100644 --- a/docs/examples/databases/list-transactions.md +++ b/docs/examples/databases/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() Databases databases = Databases(client); -TransactionList result = await databases.listTransactions( +models.TransactionList result = await databases.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index 52557334..cf6d599c 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.updateDocument( +models.Document result = await databases.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/databases/update-transaction.md b/docs/examples/databases/update-transaction.md index a882eb92..1695fe8c 100644 --- a/docs/examples/databases/update-transaction.md +++ b/docs/examples/databases/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Databases databases = Databases(client); -Transaction result = await databases.updateTransaction( +models.Transaction result = await databases.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/databases/upsert-document.md b/docs/examples/databases/upsert-document.md index 6678a0dc..1cd30f25 100644 --- a/docs/examples/databases/upsert-document.md +++ b/docs/examples/databases/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Databases databases = Databases(client); -Document result = await databases.upsertDocument( +models.Document result = await databases.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/create-document.md b/docs/examples/documentsdb/create-document.md index d4b564e2..5ed989ad 100644 --- a/docs/examples/documentsdb/create-document.md +++ b/docs/examples/documentsdb/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.createDocument( +models.Document result = await documentsDB.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/create-documents.md b/docs/examples/documentsdb/create-documents.md index 6a508373..b3f24c51 100644 --- a/docs/examples/documentsdb/create-documents.md +++ b/docs/examples/documentsdb/create-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,10 +8,19 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -DocumentList result = await documentsDB.createDocuments( +models.DocumentList result = await documentsDB.createDocuments( databaseId: '', collectionId: '', - documents: [], + documents: [ + { + "\$id": "example1", + "username": "walter.obrien", + "email": "walter.obrien@example.com", + "fullName": "Walter O'Brien", + "age": 30, + "isAdmin": false + } + ], transactionId: '', // optional ); ``` diff --git a/docs/examples/documentsdb/create-operations.md b/docs/examples/documentsdb/create-operations.md index a4d1ecdd..5e5799d8 100644 --- a/docs/examples/documentsdb/create-operations.md +++ b/docs/examples/documentsdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.createOperations( +models.Transaction result = await documentsDB.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/documentsdb/create-transaction.md b/docs/examples/documentsdb/create-transaction.md index 2d9cb9f7..bd287408 100644 --- a/docs/examples/documentsdb/create-transaction.md +++ b/docs/examples/documentsdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.createTransaction( +models.Transaction result = await documentsDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/documentsdb/decrement-document-attribute.md b/docs/examples/documentsdb/decrement-document-attribute.md index dcdac3aa..fbf0a5a7 100644 --- a/docs/examples/documentsdb/decrement-document-attribute.md +++ b/docs/examples/documentsdb/decrement-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.decrementDocumentAttribute( +models.Document result = await documentsDB.decrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/get-document.md b/docs/examples/documentsdb/get-document.md index 45db46e6..f37160a1 100644 --- a/docs/examples/documentsdb/get-document.md +++ b/docs/examples/documentsdb/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.getDocument( +models.Document result = await documentsDB.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/get-transaction.md b/docs/examples/documentsdb/get-transaction.md index 4b1a5f1f..77885681 100644 --- a/docs/examples/documentsdb/get-transaction.md +++ b/docs/examples/documentsdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.getTransaction( +models.Transaction result = await documentsDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/documentsdb/increment-document-attribute.md b/docs/examples/documentsdb/increment-document-attribute.md index c2c6e95c..5df158fc 100644 --- a/docs/examples/documentsdb/increment-document-attribute.md +++ b/docs/examples/documentsdb/increment-document-attribute.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.incrementDocumentAttribute( +models.Document result = await documentsDB.incrementDocumentAttribute( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/list-documents.md b/docs/examples/documentsdb/list-documents.md index 92d2651c..bd5f04b7 100644 --- a/docs/examples/documentsdb/list-documents.md +++ b/docs/examples/documentsdb/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -DocumentList result = await documentsDB.listDocuments( +models.DocumentList result = await documentsDB.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md index d2c09525..73e59ee4 100644 --- a/docs/examples/documentsdb/list-transactions.md +++ b/docs/examples/documentsdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -TransactionList result = await documentsDB.listTransactions( +models.TransactionList result = await documentsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/documentsdb/update-document.md b/docs/examples/documentsdb/update-document.md index 1b9fba9a..ec752959 100644 --- a/docs/examples/documentsdb/update-document.md +++ b/docs/examples/documentsdb/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.updateDocument( +models.Document result = await documentsDB.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/documentsdb/update-transaction.md b/docs/examples/documentsdb/update-transaction.md index ebcf17be..049ed68c 100644 --- a/docs/examples/documentsdb/update-transaction.md +++ b/docs/examples/documentsdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Transaction result = await documentsDB.updateTransaction( +models.Transaction result = await documentsDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/documentsdb/upsert-document.md b/docs/examples/documentsdb/upsert-document.md index bdf3844b..61baa69d 100644 --- a/docs/examples/documentsdb/upsert-document.md +++ b/docs/examples/documentsdb/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() DocumentsDB documentsDB = DocumentsDB(client); -Document result = await documentsDB.upsertDocument( +models.Document result = await documentsDB.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 0e219748..d8970844 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/enums.dart' as enums; Client client = Client() @@ -8,7 +9,7 @@ Client client = Client() Functions functions = Functions(client); -Execution result = await functions.createExecution( +models.Execution result = await functions.createExecution( functionId: '', body: '', // optional xasync: false, // optional diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index f17e10c1..7ad87740 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Functions functions = Functions(client); -Execution result = await functions.getExecution( +models.Execution result = await functions.getExecution( functionId: '', executionId: '', ); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index ae31ffcc..df498257 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Functions functions = Functions(client); -ExecutionList result = await functions.listExecutions( +models.ExecutionList result = await functions.listExecutions( functionId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index 7ec3ba75..e9632b86 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,9 @@ Client client = Client() Graphql graphql = Graphql(client); -Any result = await graphql.mutation( - query: {}, +models.Any result = await graphql.mutation( + query: { + "query": "mutation { accountUpdateName(name: \"Walter\") { name } }" + }, ); ``` diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index cac705e5..de938d4a 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,9 @@ Client client = Client() Graphql graphql = Graphql(client); -Any result = await graphql.query( - query: {}, +models.Any result = await graphql.query( + query: { + "query": "query { localeGet { ip } }" + }, ); ``` diff --git a/docs/examples/locale/get.md b/docs/examples/locale/get.md index 63021144..633588f3 100644 --- a/docs/examples/locale/get.md +++ b/docs/examples/locale/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,5 @@ Client client = Client() Locale locale = Locale(client); -Locale result = await locale.get(); +models.Locale result = await locale.get(); ``` diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index 23c375ba..e706e517 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -LocaleCodeList result = await locale.listCodes(); +models.LocaleCodeList result = await locale.listCodes( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index 349be795..fb4ae372 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -ContinentList result = await locale.listContinents(); +models.ContinentList result = await locale.listContinents( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-eu.md b/docs/examples/locale/list-countries-eu.md index f775aa2e..0f734c5f 100644 --- a/docs/examples/locale/list-countries-eu.md +++ b/docs/examples/locale/list-countries-eu.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountriesEU(); +models.CountryList result = await locale.listCountriesEU( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index ee368e29..1a29575a 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -PhoneList result = await locale.listCountriesPhones(); +models.PhoneList result = await locale.listCountriesPhones( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 17e0814f..e1059d44 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CountryList result = await locale.listCountries(); +models.CountryList result = await locale.listCountries( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 751de786..276264ce 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -CurrencyList result = await locale.listCurrencies(); +models.CurrencyList result = await locale.listCurrencies( + total: false, // optional +); ``` diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index 28b46a0a..4b8763f8 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,5 +8,7 @@ Client client = Client() Locale locale = Locale(client); -LanguageList result = await locale.listLanguages(); +models.LanguageList result = await locale.listLanguages( + total: false, // optional +); ``` diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index e28a1ab6..6b4bb2ee 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Messaging messaging = Messaging(client); -Subscriber result = await messaging.createSubscriber( +models.Subscriber result = await messaging.createSubscriber( topicId: '', subscriberId: '', targetId: '', diff --git a/docs/examples/oauth2/approve.md b/docs/examples/oauth2/approve.md new file mode 100644 index 00000000..02117db4 --- /dev/null +++ b/docs/examples/oauth2/approve.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Approve result = await oauth2.approve( + grantId: '', + authorizationDetails: '', // optional + scope: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize-post.md b/docs/examples/oauth2/authorize-post.md new file mode 100644 index 00000000..cc16efa2 --- /dev/null +++ b/docs/examples/oauth2/authorize-post.md @@ -0,0 +1,27 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Authorize result = await oauth2.authorizePost( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/authorize.md b/docs/examples/oauth2/authorize.md new file mode 100644 index 00000000..d7c6889a --- /dev/null +++ b/docs/examples/oauth2/authorize.md @@ -0,0 +1,27 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Authorize result = await oauth2.authorize( + clientId: '', // optional + redirectUri: 'https://example.com', // optional + responseType: '', // optional + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional + requestUri: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-device-authorization.md b/docs/examples/oauth2/create-device-authorization.md new file mode 100644 index 00000000..dcd41d61 --- /dev/null +++ b/docs/examples/oauth2/create-device-authorization.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2DeviceAuthorization result = await oauth2.createDeviceAuthorization( + clientId: '', // optional + scope: '', // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-grant.md b/docs/examples/oauth2/create-grant.md new file mode 100644 index 00000000..f1f5a5c1 --- /dev/null +++ b/docs/examples/oauth2/create-grant.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Grant result = await oauth2.createGrant( + userCode: '', +); +``` diff --git a/docs/examples/oauth2/create-par.md b/docs/examples/oauth2/create-par.md new file mode 100644 index 00000000..4034af4c --- /dev/null +++ b/docs/examples/oauth2/create-par.md @@ -0,0 +1,26 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2PAR result = await oauth2.createPAR( + clientId: '', + redirectUri: 'https://example.com', + responseType: 'code', + scope: '', // optional + state: '', // optional + nonce: '', // optional + codeChallenge: '', // optional + codeChallengeMethod: 's256', // optional + prompt: '', // optional + maxAge: 0, // optional + authorizationDetails: '', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/create-token.md b/docs/examples/oauth2/create-token.md new file mode 100644 index 00000000..2037d4cd --- /dev/null +++ b/docs/examples/oauth2/create-token.md @@ -0,0 +1,23 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Token result = await oauth2.createToken( + grantType: '', + code: '', // optional + refreshToken: '', // optional + deviceCode: '', // optional + clientId: '', // optional + clientSecret: '', // optional + codeVerifier: '', // optional + redirectUri: 'https://example.com', // optional + resource: '', // optional + audience: '', // optional +); +``` diff --git a/docs/examples/oauth2/get-grant.md b/docs/examples/oauth2/get-grant.md new file mode 100644 index 00000000..fbb461d2 --- /dev/null +++ b/docs/examples/oauth2/get-grant.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Grant result = await oauth2.getGrant( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/list-organizations.md b/docs/examples/oauth2/list-organizations.md new file mode 100644 index 00000000..37376b57 --- /dev/null +++ b/docs/examples/oauth2/list-organizations.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2OrganizationList result = await oauth2.listOrganizations( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/list-projects.md b/docs/examples/oauth2/list-projects.md new file mode 100644 index 00000000..0a2924ed --- /dev/null +++ b/docs/examples/oauth2/list-projects.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2ProjectList result = await oauth2.listProjects( + limit: 1, // optional + offset: 0, // optional + search: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout-post.md b/docs/examples/oauth2/logout-post.md new file mode 100644 index 00000000..3d163784 --- /dev/null +++ b/docs/examples/oauth2/logout-post.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.logoutPost( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/logout.md b/docs/examples/oauth2/logout.md new file mode 100644 index 00000000..3892325e --- /dev/null +++ b/docs/examples/oauth2/logout.md @@ -0,0 +1,18 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.logout( + idTokenHint: '', // optional + logoutHint: '', // optional + clientId: '', // optional + postLogoutRedirectUri: 'https://example.com', // optional + state: '', // optional + uiLocales: '', // optional +); +``` diff --git a/docs/examples/oauth2/reject.md b/docs/examples/oauth2/reject.md new file mode 100644 index 00000000..20f5cb22 --- /dev/null +++ b/docs/examples/oauth2/reject.md @@ -0,0 +1,14 @@ +```dart +import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models.Oauth2Reject result = await oauth2.reject( + grantId: '', +); +``` diff --git a/docs/examples/oauth2/revoke.md b/docs/examples/oauth2/revoke.md new file mode 100644 index 00000000..777340f7 --- /dev/null +++ b/docs/examples/oauth2/revoke.md @@ -0,0 +1,16 @@ +```dart +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +Oauth2 oauth2 = Oauth2(client); + +models. result = await oauth2.revoke( + token: '', + tokenTypeHint: 'access_token', // optional + clientId: '', // optional + clientSecret: '', // optional +); +``` diff --git a/docs/examples/organization/create-installation.md b/docs/examples/organization/create-installation.md index d28dacfc..520c4e41 100644 --- a/docs/examples/organization/create-installation.md +++ b/docs/examples/organization/create-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.createInstallation( +models.AppInstallation result = await organization.createInstallation( appId: '', authorizationDetails: '', // optional ); diff --git a/docs/examples/organization/get-installation.md b/docs/examples/organization/get-installation.md index dd2d7ac7..f6a1ef77 100644 --- a/docs/examples/organization/get-installation.md +++ b/docs/examples/organization/get-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.getInstallation( +models.AppInstallation result = await organization.getInstallation( installationId: '', ); ``` diff --git a/docs/examples/organization/list-installations.md b/docs/examples/organization/list-installations.md index bdecb108..58350547 100644 --- a/docs/examples/organization/list-installations.md +++ b/docs/examples/organization/list-installations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallationList result = await organization.listInstallations( +models.AppInstallationList result = await organization.listInstallations( queries: [], // optional total: false, // optional ); diff --git a/docs/examples/organization/update-installation.md b/docs/examples/organization/update-installation.md index fa834d49..8d2fddf4 100644 --- a/docs/examples/organization/update-installation.md +++ b/docs/examples/organization/update-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Organization organization = Organization(client); -AppInstallation result = await organization.updateInstallation( +models.AppInstallation result = await organization.updateInstallation( installationId: '', authorizationDetails: '', // optional ); diff --git a/docs/examples/presences/get.md b/docs/examples/presences/get.md index 9fad57c6..fd10e547 100644 --- a/docs/examples/presences/get.md +++ b/docs/examples/presences/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.get( +models.Presence result = await presences.get( presenceId: '', ); ``` diff --git a/docs/examples/presences/list.md b/docs/examples/presences/list.md index 5810a298..cfd67ab0 100644 --- a/docs/examples/presences/list.md +++ b/docs/examples/presences/list.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Presences presences = Presences(client); -PresenceList result = await presences.list( +models.PresenceList result = await presences.list( queries: [], // optional total: false, // optional ttl: 0, // optional diff --git a/docs/examples/presences/update.md b/docs/examples/presences/update.md index 84a64be0..ed52a7b0 100644 --- a/docs/examples/presences/update.md +++ b/docs/examples/presences/update.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.update( +models.Presence result = await presences.update( presenceId: '', status: '', // optional expiresAt: '2020-10-15T06:38:00.000+00:00', // optional diff --git a/docs/examples/presences/upsert.md b/docs/examples/presences/upsert.md index 32acc92f..1620ff55 100644 --- a/docs/examples/presences/upsert.md +++ b/docs/examples/presences/upsert.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Presences presences = Presences(client); -Presence result = await presences.upsert( +models.Presence result = await presences.upsert( presenceId: '', status: '', permissions: [Permission.read(Role.any())], // optional diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 7d8fbd13..f7267340 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -1,6 +1,7 @@ ```dart import 'dart:io'; import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -10,7 +11,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.createFile( +models.File result = await storage.createFile( bucketId: '', fileId: '', file: InputFile(path: './path-to-files/image.jpg', filename: 'image.jpg'), diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index 9f1adb6e..8cd043ca 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.getFile( +models.File result = await storage.getFile( bucketId: '', fileId: '', ); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index 0decd695..41f947a5 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Storage storage = Storage(client); -FileList result = await storage.listFiles( +models.FileList result = await storage.listFiles( bucketId: '', queries: [], // optional search: '', // optional diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index 90814329..fe33f0bf 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() Storage storage = Storage(client); -File result = await storage.updateFile( +models.File result = await storage.updateFile( bucketId: '', fileId: '', name: '', // optional diff --git a/docs/examples/tablesdb/create-operations.md b/docs/examples/tablesdb/create-operations.md index bc779b6b..8cdbeb48 100644 --- a/docs/examples/tablesdb/create-operations.md +++ b/docs/examples/tablesdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.createOperations( +models.Transaction result = await tablesDB.createOperations( transactionId: '', operations: [ { diff --git a/docs/examples/tablesdb/create-row.md b/docs/examples/tablesdb/create-row.md index cb5d8578..e3b639c7 100644 --- a/docs/examples/tablesdb/create-row.md +++ b/docs/examples/tablesdb/create-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.createRow( +models.Row result = await tablesDB.createRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/create-transaction.md b/docs/examples/tablesdb/create-transaction.md index 527dde39..c27b2c3f 100644 --- a/docs/examples/tablesdb/create-transaction.md +++ b/docs/examples/tablesdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.createTransaction( +models.Transaction result = await tablesDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/tablesdb/decrement-row-column.md b/docs/examples/tablesdb/decrement-row-column.md index bee4987f..c6582bb7 100644 --- a/docs/examples/tablesdb/decrement-row-column.md +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.decrementRowColumn( +models.Row result = await tablesDB.decrementRowColumn( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/get-row.md b/docs/examples/tablesdb/get-row.md index 6e385a84..560c6ad3 100644 --- a/docs/examples/tablesdb/get-row.md +++ b/docs/examples/tablesdb/get-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.getRow( +models.Row result = await tablesDB.getRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/get-transaction.md b/docs/examples/tablesdb/get-transaction.md index 39b02a77..7137420b 100644 --- a/docs/examples/tablesdb/get-transaction.md +++ b/docs/examples/tablesdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.getTransaction( +models.Transaction result = await tablesDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/tablesdb/increment-row-column.md b/docs/examples/tablesdb/increment-row-column.md index 9b0e4769..8123160c 100644 --- a/docs/examples/tablesdb/increment-row-column.md +++ b/docs/examples/tablesdb/increment-row-column.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.incrementRowColumn( +models.Row result = await tablesDB.incrementRowColumn( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/list-rows.md b/docs/examples/tablesdb/list-rows.md index a2637a93..f681a236 100644 --- a/docs/examples/tablesdb/list-rows.md +++ b/docs/examples/tablesdb/list-rows.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -RowList result = await tablesDB.listRows( +models.RowList result = await tablesDB.listRows( databaseId: '', tableId: '', queries: [], // optional diff --git a/docs/examples/tablesdb/list-transactions.md b/docs/examples/tablesdb/list-transactions.md index d95e5198..a863deab 100644 --- a/docs/examples/tablesdb/list-transactions.md +++ b/docs/examples/tablesdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -TransactionList result = await tablesDB.listTransactions( +models.TransactionList result = await tablesDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/tablesdb/update-row.md b/docs/examples/tablesdb/update-row.md index 3cf3c955..1d42d637 100644 --- a/docs/examples/tablesdb/update-row.md +++ b/docs/examples/tablesdb/update-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.updateRow( +models.Row result = await tablesDB.updateRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/tablesdb/update-transaction.md b/docs/examples/tablesdb/update-transaction.md index d5a8e082..cfc7f99e 100644 --- a/docs/examples/tablesdb/update-transaction.md +++ b/docs/examples/tablesdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Transaction result = await tablesDB.updateTransaction( +models.Transaction result = await tablesDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/tablesdb/upsert-row.md b/docs/examples/tablesdb/upsert-row.md index 74c7d2c5..a9df95fb 100644 --- a/docs/examples/tablesdb/upsert-row.md +++ b/docs/examples/tablesdb/upsert-row.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() TablesDB tablesDB = TablesDB(client); -Row result = await tablesDB.upsertRow( +models.Row result = await tablesDB.upsertRow( databaseId: '', tableId: '', rowId: '', diff --git a/docs/examples/teams/create-installation.md b/docs/examples/teams/create-installation.md index 4ad63b8d..26732254 100644 --- a/docs/examples/teams/create-installation.md +++ b/docs/examples/teams/create-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.createInstallation( +models.AppInstallation result = await teams.createInstallation( teamId: '', appId: '', authorizationDetails: '', // optional diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index caab7926..48940095 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,9 +8,9 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.createMembership( +models.Membership result = await teams.createMembership( teamId: '', - roles: [], + roles: ["editor"], email: 'email@example.com', // optional userId: '', // optional phone: '+12065550100', // optional diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 7a4af366..4bc35166 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.create( +models.Team result = await teams.create( teamId: '', name: '', roles: [], // optional diff --git a/docs/examples/teams/get-installation.md b/docs/examples/teams/get-installation.md index eec87662..10f3f096 100644 --- a/docs/examples/teams/get-installation.md +++ b/docs/examples/teams/get-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.getInstallation( +models.AppInstallation result = await teams.getInstallation( teamId: '', installationId: '', ); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 3a2906b9..798aa48f 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.getMembership( +models.Membership result = await teams.getMembership( teamId: '', membershipId: '', ); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index e35006fa..6b9805b0 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Preferences result = await teams.getPrefs( +models.Preferences result = await teams.getPrefs( teamId: '', ); ``` diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index 2a71db42..df4f911f 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.get( +models.Team result = await teams.get( teamId: '', ); ``` diff --git a/docs/examples/teams/list-installations.md b/docs/examples/teams/list-installations.md index 9c3aa852..73818abd 100644 --- a/docs/examples/teams/list-installations.md +++ b/docs/examples/teams/list-installations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallationList result = await teams.listInstallations( +models.AppInstallationList result = await teams.listInstallations( teamId: '', queries: [], // optional total: false, // optional diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index bf643511..b3a0ceef 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -MembershipList result = await teams.listMemberships( +models.MembershipList result = await teams.listMemberships( teamId: '', queries: [], // optional search: '', // optional diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 2de4ebfe..9df25089 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -TeamList result = await teams.list( +models.TeamList result = await teams.list( queries: [], // optional search: '', // optional total: false, // optional diff --git a/docs/examples/teams/update-installation.md b/docs/examples/teams/update-installation.md index e9e8ba4b..5b66afa4 100644 --- a/docs/examples/teams/update-installation.md +++ b/docs/examples/teams/update-installation.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -AppInstallation result = await teams.updateInstallation( +models.AppInstallation result = await teams.updateInstallation( teamId: '', installationId: '', authorizationDetails: '', // optional diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index ebb924b0..7968476c 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.updateMembershipStatus( +models.Membership result = await teams.updateMembershipStatus( teamId: '', membershipId: '', userId: '', diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 2d7c25c8..a86fa3f1 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,9 +8,9 @@ Client client = Client() Teams teams = Teams(client); -Membership result = await teams.updateMembership( +models.Membership result = await teams.updateMembership( teamId: '', membershipId: '', - roles: [], + roles: ["editor"], ); ``` diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index 629e7608..1c9d6502 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Team result = await teams.updateName( +models.Team result = await teams.updateName( teamId: '', name: '', ); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index 1a53c498..9d652cb9 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() Teams teams = Teams(client); -Preferences result = await teams.updatePrefs( +models.Preferences result = await teams.updatePrefs( teamId: '', prefs: {}, ); diff --git a/docs/examples/vectorsdb/create-document.md b/docs/examples/vectorsdb/create-document.md index fc39a7c1..ecc02176 100644 --- a/docs/examples/vectorsdb/create-document.md +++ b/docs/examples/vectorsdb/create-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.createDocument( +models.Document result = await vectorsDB.createDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/create-operations.md b/docs/examples/vectorsdb/create-operations.md index a994693e..0604ef6b 100644 --- a/docs/examples/vectorsdb/create-operations.md +++ b/docs/examples/vectorsdb/create-operations.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.createOperations( +models.Transaction result = await vectorsDB.createOperations( transactionId: '', operations: [ { @@ -16,7 +17,15 @@ Transaction result = await vectorsDB.createOperations( "collectionId": "", "documentId": "", "data": { - "name": "Walter O'Brien" + "embeddings": [ + 0.12, + -0.55, + 0.88, + 1.02 + ], + "metadata": { + "name": "First document" + } } } ], // optional diff --git a/docs/examples/vectorsdb/create-query.md b/docs/examples/vectorsdb/create-query.md index fa41ee5c..3b72a0c4 100644 --- a/docs/examples/vectorsdb/create-query.md +++ b/docs/examples/vectorsdb/create-query.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -DocumentList result = await vectorsDB.createQuery( +models.DocumentList result = await vectorsDB.createQuery( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/vectorsdb/create-transaction.md b/docs/examples/vectorsdb/create-transaction.md index 9c8c96d3..d197ad2a 100644 --- a/docs/examples/vectorsdb/create-transaction.md +++ b/docs/examples/vectorsdb/create-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.createTransaction( +models.Transaction result = await vectorsDB.createTransaction( ttl: 60, // optional ); ``` diff --git a/docs/examples/vectorsdb/get-document.md b/docs/examples/vectorsdb/get-document.md index 28e544b3..42a2a2b8 100644 --- a/docs/examples/vectorsdb/get-document.md +++ b/docs/examples/vectorsdb/get-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.getDocument( +models.Document result = await vectorsDB.getDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/get-transaction.md b/docs/examples/vectorsdb/get-transaction.md index 1d191d09..68023e00 100644 --- a/docs/examples/vectorsdb/get-transaction.md +++ b/docs/examples/vectorsdb/get-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.getTransaction( +models.Transaction result = await vectorsDB.getTransaction( transactionId: '', ); ``` diff --git a/docs/examples/vectorsdb/list-documents.md b/docs/examples/vectorsdb/list-documents.md index 03b4931d..26793163 100644 --- a/docs/examples/vectorsdb/list-documents.md +++ b/docs/examples/vectorsdb/list-documents.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -DocumentList result = await vectorsDB.listDocuments( +models.DocumentList result = await vectorsDB.listDocuments( databaseId: '', collectionId: '', queries: [], // optional diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md index fb7f83db..befe5379 100644 --- a/docs/examples/vectorsdb/list-transactions.md +++ b/docs/examples/vectorsdb/list-transactions.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,8 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -TransactionList result = await vectorsDB.listTransactions( +models.TransactionList result = await vectorsDB.listTransactions( queries: [], // optional + total: false, // optional ); ``` diff --git a/docs/examples/vectorsdb/update-document.md b/docs/examples/vectorsdb/update-document.md index 8c2a9091..0457e855 100644 --- a/docs/examples/vectorsdb/update-document.md +++ b/docs/examples/vectorsdb/update-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.updateDocument( +models.Document result = await vectorsDB.updateDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/docs/examples/vectorsdb/update-transaction.md b/docs/examples/vectorsdb/update-transaction.md index 1abd8b02..6915d144 100644 --- a/docs/examples/vectorsdb/update-transaction.md +++ b/docs/examples/vectorsdb/update-transaction.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; Client client = Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint @@ -7,7 +8,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Transaction result = await vectorsDB.updateTransaction( +models.Transaction result = await vectorsDB.updateTransaction( transactionId: '', commit: false, // optional rollback: false, // optional diff --git a/docs/examples/vectorsdb/upsert-document.md b/docs/examples/vectorsdb/upsert-document.md index 1367bba4..de7503fb 100644 --- a/docs/examples/vectorsdb/upsert-document.md +++ b/docs/examples/vectorsdb/upsert-document.md @@ -1,5 +1,6 @@ ```dart import 'package:appwrite/appwrite.dart'; +import 'package:appwrite/models.dart' as models; import 'package:appwrite/permission.dart'; import 'package:appwrite/role.dart'; @@ -9,7 +10,7 @@ Client client = Client() VectorsDB vectorsDB = VectorsDB(client); -Document result = await vectorsDB.upsertDocument( +models.Document result = await vectorsDB.upsertDocument( databaseId: '', collectionId: '', documentId: '', diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c80609e3..c2083c8a 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -24,6 +24,8 @@ export 'src/response.dart'; export 'src/client.dart'; export 'src/exception.dart'; export 'src/realtime.dart'; +export 'src/mqtt.dart'; +export 'src/mqtt_message.dart'; export 'src/upload_progress.dart'; export 'src/realtime_subscription.dart'; export 'src/realtime_message.dart'; @@ -33,9 +35,11 @@ part 'query.dart'; part 'permission.dart'; part 'role.dart'; part 'id.dart'; +part 'topic.dart'; part 'channel.dart'; part 'operator.dart'; part 'services/account.dart'; +part 'services/apps.dart'; part 'services/avatars.dart'; part 'services/databases.dart'; part 'services/documents_db.dart'; @@ -43,6 +47,7 @@ part 'services/functions.dart'; part 'services/graphql.dart'; part 'services/locale.dart'; part 'services/messaging.dart'; +part 'services/oauth2.dart'; part 'services/organization.dart'; part 'services/presences.dart'; part 'services/storage.dart'; diff --git a/lib/models.dart b/lib/models.dart index f1fca69d..ce40157d 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -31,6 +31,7 @@ part 'src/models/algo_bcrypt.dart'; part 'src/models/algo_scrypt.dart'; part 'src/models/algo_scrypt_modified.dart'; part 'src/models/algo_argon2.dart'; +part 'src/models/account.dart'; part 'src/models/preferences.dart'; part 'src/models/session.dart'; part 'src/models/identity.dart'; @@ -55,9 +56,29 @@ part 'src/models/mfa_factors.dart'; part 'src/models/transaction.dart'; part 'src/models/subscriber.dart'; part 'src/models/target.dart'; +part 'src/models/app.dart'; +part 'src/models/app_secret.dart'; +part 'src/models/app_secret_plaintext.dart'; +part 'src/models/app_scope.dart'; part 'src/models/app_installation.dart'; +part 'src/models/app_key.dart'; +part 'src/models/oauth2_authorize.dart'; +part 'src/models/oauth2_approve.dart'; +part 'src/models/oauth2_reject.dart'; +part 'src/models/oauth2_grant.dart'; +part 'src/models/oauth2_device_authorization.dart'; +part 'src/models/oauth2_par.dart'; +part 'src/models/oauth2_token.dart'; part 'src/models/oauth2_consent.dart'; part 'src/models/oauth2_consent_token.dart'; +part 'src/models/oauth2_project.dart'; +part 'src/models/oauth2_organization.dart'; +part 'src/models/oauth2_project_list.dart'; +part 'src/models/oauth2_organization_list.dart'; part 'src/models/oauth2_consent_list.dart'; part 'src/models/oauth2_consent_token_list.dart'; +part 'src/models/apps_list.dart'; +part 'src/models/app_secret_list.dart'; +part 'src/models/app_scope_list.dart'; part 'src/models/app_installation_list.dart'; +part 'src/models/app_key_list.dart'; diff --git a/lib/query.dart b/lib/query.dart index 1ad97bdc..aeb93797 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -159,27 +159,33 @@ class Query { static String updatedBetween(String start, String end) => between('\$updatedAt', start, end); - static String or(List queries) => Query._( - 'or', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); - - static String and(List queries) => Query._( - 'and', - null, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + static String or(List queries) { + return Query._( + 'or', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } + + static String and(List queries) { + return Query._( + 'and', + null, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Filter array elements where at least one element matches all the specified queries. /// /// [attribute] The attribute containing the array to filter on. /// [queries] The list of query strings to match against array elements. - static String elemMatch(String attribute, List queries) => Query._( - 'elemMatch', - attribute, - queries.map((query) => jsonDecode(query)).toList(), - ).toString(); + static String elemMatch(String attribute, List queries) { + return Query._( + 'elemMatch', + attribute, + queries.map((query) => jsonDecode(query)).toList(), + ).toString(); + } /// Specify which attributes should be returned by the API call. static String select(List attributes) => diff --git a/lib/services/account.dart b/lib/services/account.dart index 48492bdb..9eda7926 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -1246,10 +1246,14 @@ class Account extends Service { /// Get the list of active sessions across different devices for the currently /// logged in user. - Future listSessions() async { + Future listSessions({ + bool? total, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1267,11 +1271,16 @@ class Account extends Service { } /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { + /// from the end client. Pass `current` as false to keep the session making the + /// request and sign out of every other session. + Future deleteSessions({ + bool? current, + }) async { final String apiPath = '/account/sessions'; - final Map apiParams = {}; + final Map apiParams = { + if (current != null) 'current': current, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -1319,6 +1328,9 @@ class Account extends Service { /// Allow the user to login into their account by providing a valid email and /// password combination. This route will create a new session for the user. + /// Use the optional `duration` parameter to create a shorter session, for + /// example when the user doesn't choose "remember me". It must be at least 60 + /// seconds and cannot exceed the project maximum session length. /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session @@ -1326,12 +1338,14 @@ class Account extends Service { Future createEmailPasswordSession({ required String email, required String password, + int? duration, }) async { final String apiPath = '/account/sessions/email'; final Map apiParams = { 'email': email, 'password': password, + if (duration != null) 'duration': duration, }; final Map apiHeaders = { diff --git a/lib/services/apps.dart b/lib/services/apps.dart new file mode 100644 index 00000000..1026e7ea --- /dev/null +++ b/lib/services/apps.dart @@ -0,0 +1,852 @@ +part of '../appwrite.dart'; + +/// The Apps service allows you to manage OAuth2 applications, their keys, +/// secrets, scopes, and installations. +class Apps extends Service { + /// Initializes a [Apps] service + Apps(super.client); + + /// List applications. + Future list({ + List? queries, + bool? total, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppsList.fromMap(res.data); + } + + /// Create a new application. + Future create({ + required String appId, + required String name, + required List redirectUris, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + List? postLogoutRedirectUris, + bool? enabled, + String? type, + bool? deviceFlow, + String? teamId, + }) async { + final String apiPath = '/apps'; + + final Map apiParams = { + 'appId': appId, + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (enabled != null) 'enabled': enabled, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (teamId != null) 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// List scopes an application can request when installed on a team. + Future listInstallationScopes() async { + final String apiPath = '/apps/scopes/installations'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// List scopes an application can request during the OAuth2 flow. + Future listOAuth2Scopes() async { + final String apiPath = '/apps/scopes/oauth2'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppScopeList.fromMap(res.data); + } + + /// Get an application by its unique ID. + Future get({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Update an application by its unique ID. + Future update({ + required String appId, + required String name, + String? description, + String? clientUri, + String? logoUri, + String? privacyPolicyUrl, + String? termsUrl, + List? contacts, + String? tagline, + List? tags, + List? images, + String? supportUrl, + String? dataDeletionUrl, + bool? enabled, + List? redirectUris, + List? postLogoutRedirectUris, + String? type, + bool? deviceFlow, + List? installationScopes, + String? installationRedirectUrl, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'name': name, + if (description != null) 'description': description, + if (clientUri != null) 'clientUri': clientUri, + if (logoUri != null) 'logoUri': logoUri, + if (privacyPolicyUrl != null) 'privacyPolicyUrl': privacyPolicyUrl, + if (termsUrl != null) 'termsUrl': termsUrl, + if (contacts != null) 'contacts': contacts, + if (tagline != null) 'tagline': tagline, + if (tags != null) 'tags': tags, + if (images != null) 'images': images, + if (supportUrl != null) 'supportUrl': supportUrl, + if (dataDeletionUrl != null) 'dataDeletionUrl': dataDeletionUrl, + if (enabled != null) 'enabled': enabled, + if (redirectUris != null) 'redirectUris': redirectUris, + if (postLogoutRedirectUris != null) + 'postLogoutRedirectUris': postLogoutRedirectUris, + if (type != null) 'type': type, + if (deviceFlow != null) 'deviceFlow': deviceFlow, + if (installationScopes != null) 'installationScopes': installationScopes, + if (installationRedirectUrl != null) + 'installationRedirectUrl': installationRedirectUrl, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.put, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Delete an application by its unique ID. + Future delete({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List installations of an application. Requires an app key sent in the + /// `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, or a caller + /// with update access to the app. + Future listInstallations({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/installations'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallationList.fromMap(res.data); + } + + /// Get an installation of an application by its unique ID. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. + Future getInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppInstallation.fromMap(res.data); + } + + /// Delete an installation of an application by its unique ID. Requires a + /// caller with update access to the app. Previously issued installation access + /// tokens are revoked. + Future deleteInstallation({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Create a token for an installation of an application. Requires an app key + /// sent in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header, + /// or a caller with update access to the app. The returned token carries the + /// scopes and authorization details granted to the installation, and can be + /// used as an `Authorization: Bearer` header everywhere OAuth2 access tokens + /// are accepted. Multiple tokens can be active for the same installation at + /// once; each token stays valid until it expires or the installation is + /// updated or deleted. + Future createInstallationToken({ + required String appId, + required String installationId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (installationId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "installationId"', + ); + } + + final String apiPath = '/apps/{appId}/installations/{installationId}/tokens' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{installationId}', + installationId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } + + /// List app keys for an application. + Future listKeys({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKeyList.fromMap(res.data); + } + + /// Create a new app key for an application. App keys carry no scopes; send one + /// in the `X-Appwrite-Key` header alongside the `X-Appwrite-App` header to + /// list the application's installations and create installation access tokens. + Future createKey({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/keys'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Get an app key by its unique ID. + Future getKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppKey.fromMap(res.data); + } + + /// Delete an app key by its unique ID. + Future deleteKey({ + required String appId, + required String keyId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (keyId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "keyId"', + ); + } + + final String apiPath = '/apps/{appId}/keys/{keyId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{keyId}', + keyId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List client secrets for an application. + Future listSecrets({ + required String appId, + List? queries, + bool? total, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + if (queries != null) 'queries': queries, + if (total != null) 'total': total, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretList.fromMap(res.data); + } + + /// Create a new client secret for an application. + Future createSecret({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecretPlaintext.fromMap(res.data); + } + + /// Get an application client secret by its unique ID. + Future getSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.AppSecret.fromMap(res.data); + } + + /// Delete an application client secret by its unique ID. + Future deleteSecret({ + required String appId, + required String secretId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + if (secretId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "secretId"', + ); + } + + final String apiPath = '/apps/{appId}/secrets/{secretId}' + .replaceAll( + '{appId}', + appId, + ) + .replaceAll( + '{secretId}', + secretId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Transfer an application to another team by its unique ID. + Future updateTeam({ + required String appId, + required String teamId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/team'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = { + 'teamId': teamId, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.patch, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.App.fromMap(res.data); + } + + /// Revoke all tokens for an application by its unique ID. + Future deleteTokens({ + required String appId, + }) async { + if (appId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "appId"', + ); + } + + final String apiPath = '/apps/{appId}/tokens'.replaceAll( + '{appId}', + appId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index c57fb66e..f9b4cbd5 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -242,9 +242,9 @@ class Avatars extends Service { } /// Returns the best available profile photo for a user. The endpoint tries - /// each source in priority order and returns the first successful result: - /// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in - /// static fallback. + /// each source in priority order and returns the first successful result: a + /// custom uploaded photo (see avatars.updatePhoto), OAuth2 identity photo, + /// Gravatar, Libravatar, Appwrite Initials, built-in static fallback. /// /// Passing `userId` — `current()` for the authenticated user — resolves /// the photo from everything known about that user: identity photos, email, @@ -294,6 +294,68 @@ class Avatars extends Service { return res.data; } + /// Update the profile photo of the currently authenticated user. The uploaded + /// image takes priority over every other photo source, including OAuth2 + /// identity photos, Gravatar, and Libravatar. Updating an already customized + /// photo replaces it. The image must be at most 5MB and is sent in a single + /// request. + Future updatePhoto({ + required InputFile file, + Function(UploadProgress)? onProgress, + }) async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = { + 'file': file, + }; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'multipart/form-data', + 'accept': 'application/json', + }; + + String idParamName = ''; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + method: HttpMethod.put, + ); + + return models.Account.fromMap(res.data); + } + + /// Delete the profile photo of the currently authenticated user and store the + /// built-in static placeholder in its place. The placeholder is the user's + /// photo from then on, so it takes priority over every other photo source — + /// OAuth2 identity photos, Gravatar, Libravatar, and initials — until a new + /// photo is uploaded with avatars.updatePhoto. + Future deletePhoto() async { + final String apiPath = '/avatars/photo'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'X-Appwrite-Project': client.config['project'] ?? '', + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.delete, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + /// Converts a given plain text to a QR code image. You can use the query /// parameters to change the size and style of the resulting image. Future getQR({ diff --git a/lib/services/databases.dart b/lib/services/databases.dart index f1bb2510..96fed789 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -12,11 +12,13 @@ class Databases extends Service { ) Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/databases/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -189,11 +191,11 @@ class Databases extends Service { ); } - final String apiPath = - '/databases/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/databases/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/documents_db.dart b/lib/services/documents_db.dart index 3ca77cdb..1d04aa9c 100644 --- a/lib/services/documents_db.dart +++ b/lib/services/documents_db.dart @@ -7,11 +7,13 @@ class DocumentsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/documentsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -65,11 +67,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; @@ -100,11 +102,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (commit != null) 'commit': commit, @@ -137,11 +139,11 @@ class DocumentsDB extends Service { ); } - final String apiPath = - '/documentsdb/transactions/{transactionId}'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/documentsdb/transactions/{transactionId}' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = {}; diff --git a/lib/services/locale.dart b/lib/services/locale.dart index d4831b74..227f1a9b 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -34,10 +34,14 @@ class Locale extends Service { /// List of all locale codes in [ISO /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { + Future listCodes({ + bool? total, + }) async { final String apiPath = '/locale/codes'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -56,10 +60,14 @@ class Locale extends Service { /// List of all continents. You can use the locale header to get the data in a /// supported language. - Future listContinents() async { + Future listContinents({ + bool? total, + }) async { final String apiPath = '/locale/continents'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -78,10 +86,14 @@ class Locale extends Service { /// List of all countries. You can use the locale header to get the data in a /// supported language. - Future listCountries() async { + Future listCountries({ + bool? total, + }) async { final String apiPath = '/locale/countries'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -100,10 +112,14 @@ class Locale extends Service { /// List of all countries that are currently members of the EU. You can use the /// locale header to get the data in a supported language. - Future listCountriesEU() async { + Future listCountriesEU({ + bool? total, + }) async { final String apiPath = '/locale/countries/eu'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -122,10 +138,14 @@ class Locale extends Service { /// List of all countries phone codes. You can use the locale header to get the /// data in a supported language. - Future listCountriesPhones() async { + Future listCountriesPhones({ + bool? total, + }) async { final String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -145,10 +165,14 @@ class Locale extends Service { /// List of all currencies, including currency symbol, name, plural, and /// decimal digits for all major and minor currencies. You can use the locale /// header to get the data in a supported language. - Future listCurrencies() async { + Future listCurrencies({ + bool? total, + }) async { final String apiPath = '/locale/currencies'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', @@ -167,10 +191,14 @@ class Locale extends Service { /// List of all languages classified by ISO 639-1 including 2-letter code, name /// in English, and name in the respective language. - Future listLanguages() async { + Future listLanguages({ + bool? total, + }) async { final String apiPath = '/locale/languages'; - final Map apiParams = {}; + final Map apiParams = { + if (total != null) 'total': total, + }; final Map apiHeaders = { 'X-Appwrite-Project': client.config['project'] ?? '', diff --git a/lib/services/oauth2.dart b/lib/services/oauth2.dart new file mode 100644 index 00000000..1950338a --- /dev/null +++ b/lib/services/oauth2.dart @@ -0,0 +1,588 @@ +part of '../appwrite.dart'; + +/// The OAuth2 service allows you to authorize apps and issue standards-based +/// OAuth2 and OpenID Connect tokens. +class Oauth2 extends Service { + /// Initializes a [Oauth2] service + Oauth2(super.client); + + /// Approve an OAuth2 grant after the user gives consent. Returns the + /// `redirectUrl` the end user should be sent to. The consent screen may + /// optionally pass enriched `authorization_details` to record the concrete + /// resources the user selected. You can pass Accept header of + /// `application/json` to receive a JSON response instead of a redirect. + Future approve({ + required String grantId, + String? authorizationDetails, + String? scope, + }) async { + final String apiPath = '/oauth2/{project_id}/approve'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (scope != null) 'scope': scope, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Approve.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorize({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Begin the OAuth2 authorization flow. When called without a session, the + /// user is redirected to the consent screen without grant ID. When called with + /// a session, the redirect URL includes param for grant ID. You can pass + /// Accept header of `application/json` to receive a JSON response instead of a + /// redirect. + Future authorizePost({ + String? clientId, + String? redirectUri, + String? responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + String? requestUri, + }) async { + final String apiPath = '/oauth2/{project_id}/authorize'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (responseType != null) 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + if (requestUri != null) 'request_uri': requestUri, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Authorize.fromMap(res.data); + } + + /// Start the OAuth2 Device Authorization Grant. Returns the device code, user + /// code, verification URL, expiration, and polling interval. + Future createDeviceAuthorization({ + String? clientId, + String? scope, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/device_authorization' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (clientId != null) 'client_id': clientId, + if (scope != null) 'scope': scope, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2DeviceAuthorization.fromMap(res.data); + } + + /// Exchange a device flow user code for an OAuth2 grant. The authenticated + /// user is bound to the pending grant. Pass the returned grant ID to the get + /// grant endpoint to render the consent screen, then to the approve or reject + /// endpoint to complete the flow. + Future createGrant({ + required String userCode, + }) async { + final String apiPath = '/oauth2/{project_id}/grants'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'user_code': userCode, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// Get an OAuth2 grant by its ID. Used by the consent screen to display the + /// details of the authorization the user is being asked to approve. A grant + /// can only be read by the user it belongs to, or by server SDK. + Future getGrant({ + required String grantId, + }) async { + if (grantId.isEmpty) { + throw AppwriteException( + 'Missing required parameter: "grantId"', + ); + } + + final String apiPath = '/oauth2/{project_id}/grants/{grant_id}' + .replaceAll( + '{project_id}', + client.config['project'] ?? '', + ) + .replaceAll( + '{grant_id}', + grantId, + ); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Grant.fromMap(res.data); + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logout({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// OpenID Connect RP-Initiated Logout. Ends the user session and revokes the + /// tokens issued to the app identified by the `id_token_hint`, then redirects + /// the user to `post_logout_redirect_uri` when it matches a URI registered on + /// the app. + Future logoutPost({ + String? idTokenHint, + String? logoutHint, + String? clientId, + String? postLogoutRedirectUri, + String? state, + String? uiLocales, + }) async { + final String apiPath = '/oauth2/{project_id}/logout'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (idTokenHint != null) 'id_token_hint': idTokenHint, + if (logoutHint != null) 'logout_hint': logoutHint, + if (clientId != null) 'client_id': clientId, + if (postLogoutRedirectUri != null) + 'post_logout_redirect_uri': postLogoutRedirectUri, + if (state != null) 'state': state, + if (uiLocales != null) 'ui_locales': uiLocales, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// List the organizations the OAuth2 access token can access. Resolves the + /// token's `organization` authorization details, expanding the `*` wildcard + /// into the concrete set of organizations the user can see. + Future listOrganizations({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/organizations'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2OrganizationList.fromMap(res.data); + } + + /// Store an OAuth2 authorization request server-side and receive a short-lived + /// request_uri handle for the authorize endpoint. + Future createPAR({ + required String clientId, + required String redirectUri, + required String responseType, + String? scope, + String? state, + String? nonce, + String? codeChallenge, + String? codeChallengeMethod, + String? prompt, + int? maxAge, + String? authorizationDetails, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/par'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'client_id': clientId, + 'redirect_uri': redirectUri, + 'response_type': responseType, + if (scope != null) 'scope': scope, + if (state != null) 'state': state, + if (nonce != null) 'nonce': nonce, + if (codeChallenge != null) 'code_challenge': codeChallenge, + if (codeChallengeMethod != null) + 'code_challenge_method': codeChallengeMethod, + if (prompt != null) 'prompt': prompt, + if (maxAge != null) 'max_age': maxAge, + if (authorizationDetails != null) + 'authorization_details': authorizationDetails, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2PAR.fromMap(res.data); + } + + /// List the projects the OAuth2 access token can access. Resolves the token's + /// `project` authorization details, expanding the `*` wildcard into the + /// concrete set of projects the user can see. + Future listProjects({ + int? limit, + int? offset, + String? search, + }) async { + final String apiPath = '/oauth2/{project_id}/projects'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + if (limit != null) 'limit': limit, + if (offset != null) 'offset': offset, + if (search != null) 'search': search, + }; + + final Map apiHeaders = { + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.get, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2ProjectList.fromMap(res.data); + } + + /// Reject an OAuth2 grant when the user denies consent. Returns the + /// `redirectUrl` the end user should be sent to with an `access_denied` error. + /// You can pass Accept header of `application/json` to receive a JSON response + /// instead of a redirect. + Future reject({ + required String grantId, + }) async { + final String apiPath = '/oauth2/{project_id}/reject'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_id': grantId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Reject.fromMap(res.data); + } + + /// Revoke an OAuth2 access token or refresh token. + Future revoke({ + required String token, + String? tokenTypeHint, + String? clientId, + String? clientSecret, + }) async { + final String apiPath = '/oauth2/{project_id}/revoke'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'token': token, + if (tokenTypeHint != null) 'token_type_hint': tokenTypeHint, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return res.data; + } + + /// Exchange an OAuth2 authorization code, refresh token, or device code for + /// access and refresh tokens. + Future createToken({ + required String grantType, + String? code, + String? refreshToken, + String? deviceCode, + String? clientId, + String? clientSecret, + String? codeVerifier, + String? redirectUri, + String? resource, + String? audience, + }) async { + final String apiPath = '/oauth2/{project_id}/token'.replaceAll( + '{project_id}', + client.config['project'] ?? '', + ); + + final Map apiParams = { + 'grant_type': grantType, + if (code != null) 'code': code, + if (refreshToken != null) 'refresh_token': refreshToken, + if (deviceCode != null) 'device_code': deviceCode, + if (clientId != null) 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + if (codeVerifier != null) 'code_verifier': codeVerifier, + if (redirectUri != null) 'redirect_uri': redirectUri, + if (resource != null) 'resource': resource, + if (audience != null) 'audience': audience, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + 'accept': 'application/json', + }; + + final res = await client.call( + HttpMethod.post, + path: apiPath, + params: apiParams, + headers: apiHeaders, + ); + + return models.Oauth2Token.fromMap(res.data); + } +} diff --git a/lib/services/organization.dart b/lib/services/organization.dart index bbda874a..68b762c9 100644 --- a/lib/services/organization.dart +++ b/lib/services/organization.dart @@ -75,11 +75,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; @@ -112,11 +112,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = { if (authorizationDetails != null) @@ -151,11 +151,11 @@ class Organization extends Service { ); } - final String apiPath = - '/organization/installations/{installationId}'.replaceAll( - '{installationId}', - installationId, - ); + final String apiPath = '/organization/installations/{installationId}' + .replaceAll( + '{installationId}', + installationId, + ); final Map apiParams = {}; diff --git a/lib/services/storage.dart b/lib/services/storage.dart index 52a129a8..ec4522fe 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -104,6 +104,7 @@ class Storage extends Service { idParamName: idParamName, headers: apiHeaders, onProgress: onProgress, + method: HttpMethod.post, ); return models.File.fromMap(res.data); diff --git a/lib/services/tables_db.dart b/lib/services/tables_db.dart index 4fdbb987..e7a5d4a3 100644 --- a/lib/services/tables_db.dart +++ b/lib/services/tables_db.dart @@ -9,11 +9,13 @@ class TablesDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/tablesdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -171,11 +173,11 @@ class TablesDB extends Service { ); } - final String apiPath = - '/tablesdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/tablesdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/services/vectors_db.dart b/lib/services/vectors_db.dart index e257b38c..fddd1087 100644 --- a/lib/services/vectors_db.dart +++ b/lib/services/vectors_db.dart @@ -7,11 +7,13 @@ class VectorsDB extends Service { /// List transactions across all databases. Future listTransactions({ List? queries, + bool? total, }) async { final String apiPath = '/vectorsdb/transactions'; final Map apiParams = { if (queries != null) 'queries': queries, + if (total != null) 'total': total, }; final Map apiHeaders = { @@ -169,11 +171,11 @@ class VectorsDB extends Service { ); } - final String apiPath = - '/vectorsdb/transactions/{transactionId}/operations'.replaceAll( - '{transactionId}', - transactionId, - ); + final String apiPath = '/vectorsdb/transactions/{transactionId}/operations' + .replaceAll( + '{transactionId}', + transactionId, + ); final Map apiParams = { if (operations != null) 'operations': operations, diff --git a/lib/src/client.dart b/lib/src/client.dart index fedec03c..f456f011 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -27,8 +27,7 @@ abstract class Client { factory Client({ String endPoint = 'https://cloud.appwrite.io/v1', bool selfSigned = false, - }) => - createClient(endPoint: endPoint, selfSigned: selfSigned); + }) => createClient(endPoint: endPoint, selfSigned: selfSigned); /// Handle OAuth2 session creation. Future webAuth(Uri url, {String? callbackUrlScheme}); @@ -41,6 +40,8 @@ abstract class Client { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }); /// Set self signed to [status]. @@ -56,6 +57,14 @@ abstract class Client { /// Set the Appwrite realtime endpoint. Client setEndPointRealtime(String endPoint); + /// Set the Appwrite push (MQTT broker) endpoint, e.g. + /// `mqtt://host:1883` or `mqtts://host:8883`. + Client setPushEndpoint(String endPoint); + + /// Set a stable push client id, so the broker resumes this client's offline-replay + /// cursor across restarts. Defaults to a per-connection id when unset. + Client setPushClientId(String pushClientId); + /// Set Project. /// /// Your project ID. diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index 36e4bbc9..9897e898 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -47,6 +47,12 @@ abstract class ClientBase implements Client { @override Client setEndPointRealtime(String endPoint); + @override + Client setPushEndpoint(String endPoint); + + @override + Client setPushClientId(String pushClientId); + @override ClientBase addHeader(String key, String value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index d04f9bc6..182870c7 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -40,7 +40,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -155,6 +155,18 @@ class ClientBrowser extends ClientBase with ClientMixin { return this; } + @override + ClientBrowser setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientBrowser setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientBrowser addHeader(String key, String value) { _headers![key] = value; @@ -182,7 +194,19 @@ class ClientBrowser extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.bytes == null) { throw AppwriteException("File bytes must be provided for Flutter web"); @@ -191,17 +215,18 @@ class ClientBrowser extends ClientBase with ClientMixin { int size = file.bytes!.length; late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { params[paramName] = http.MultipartFile.fromBytes( paramName, file.bytes!, filename: file.filename, ); return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -249,7 +274,7 @@ class ClientBrowser extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f228d17f..00e8954f 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -47,9 +47,10 @@ class ClientIO extends ClientBase with ClientMixin { String endPoint = 'https://cloud.appwrite.io/v1', this.selfSigned = false, }) : _endPoint = endPoint { - _nativeClient = HttpClient() - ..badCertificateCallback = - ((X509Certificate cert, String host, int port) => selfSigned); + _nativeClient = + HttpClient() + ..badCertificateCallback = + ((X509Certificate cert, String host, int port) => selfSigned); _httpClient = IOClient(_nativeClient); _endPointRealtime = endPoint .replaceFirst('https://', 'wss://') @@ -59,7 +60,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '27.0.0', + 'x-sdk-version': '27.1.0-rc.0', 'X-Appwrite-Response-Format': '2.3.0', }; @@ -185,6 +186,18 @@ class ClientIO extends ClientBase with ClientMixin { return this; } + @override + ClientIO setPushEndpoint(String endPoint) { + config['endpointPush'] = endPoint; + return this; + } + + @override + ClientIO setPushClientId(String pushClientId) { + config['pushClientId'] = pushClientId; + return this; + } + @override ClientIO addHeader(String key, String value) { _headers![key] = value; @@ -286,7 +299,19 @@ class ClientIO extends ClientBase with ClientMixin { required String idParamName, required Map headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { + if (params[paramName] == null) { + return call( + method, + path: path, + params: params, + headers: headers, + responseType: responseType, + ); + } + InputFile file = params[paramName]; if (file.path == null && file.bytes == null) { throw AppwriteException("File path or bytes must be provided"); @@ -305,7 +330,7 @@ class ClientIO extends ClientBase with ClientMixin { } late Response res; - if (size <= chunkSize) { + if (size <= chunkSize || responseType == ResponseType.plain) { if (file.path != null) { params[paramName] = await http.MultipartFile.fromPath( paramName, @@ -320,10 +345,11 @@ class ClientIO extends ClientBase with ClientMixin { ); } return call( - HttpMethod.post, + method, path: path, params: params, headers: headers, + responseType: responseType, ); } @@ -349,8 +375,13 @@ class ClientIO extends ClientBase with ClientMixin { final totalChunks = (size / chunkSize).ceil(); - Future uploadChunk(int index, int start, int end, String? id, - [RandomAccessFile? raf]) async { + Future uploadChunk( + int index, + int start, + int end, + String? id, [ + RandomAccessFile? raf, + ]) async { List chunk = []; if (file.bytes != null) { chunk = file.bytes!.getRange(start, end).toList(); @@ -382,7 +413,7 @@ class ClientIO extends ClientBase with ClientMixin { chunkHeaders['content-range'] = 'bytes $start-${end - 1}/$size'; return call( - HttpMethod.post, + method, path: path, headers: chunkHeaders, params: chunkParams, @@ -474,9 +505,10 @@ class ClientIO extends ClientBase with ClientMixin { Future webAuth(Uri url, {String? callbackUrlScheme}) { return FlutterWebAuth2.authenticate( url: url.toString(), - callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed - ? callbackUrlScheme - : "appwrite-callback-${config['project']!}", + callbackUrlScheme: + callbackUrlScheme != null && _customSchemeAllowed + ? callbackUrlScheme + : "appwrite-callback-${config['project']!}", options: const FlutterWebAuth2Options( useWebview: false, ), @@ -491,9 +523,10 @@ class ClientIO extends ClientBase with ClientMixin { final parsed = jsonDecode(error); if (parsed is Map) { final codeValue = parsed['code']; - final int? code = codeValue is int - ? codeValue - : int.tryParse('${codeValue ?? ''}'); + final int? code = + codeValue is int + ? codeValue + : int.tryParse('${codeValue ?? ''}'); throw AppwriteException( parsed['message']?.toString() ?? error, code, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 952d7114..55a75c2c 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -31,6 +31,10 @@ mixin ClientMixin { }); } }); + } else if (value is Map) { + (request as http.MultipartRequest).fields.addAll({ + key: jsonEncode(value), + }); } else { (request as http.MultipartRequest).fields.addAll({ key: value.toString(), @@ -91,9 +95,10 @@ mixin ClientMixin { warnings.split(';').forEach((warning) => log('Warning: $warning')); } + final isJson = (res.headers['content-type'] ?? '').contains( + 'application/json', + ); if (res.statusCode >= 400) { - final isJson = - (res.headers['content-type'] ?? '').contains('application/json'); // Empty bodies still arrive with application/json (e.g. truncated // proxy/edge errors). Avoid FormatException from json.decode(''). if (isJson && res.body.isNotEmpty) { @@ -116,20 +121,16 @@ mixin ClientMixin { } } dynamic data; - if ((res.headers['content-type'] ?? '').contains('application/json')) { - if (responseType == ResponseType.json) { - data = json.decode(res.body); - } else if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + if (responseType == ResponseType.bytes) { + data = res.bodyBytes; + } else if (responseType == ResponseType.plain) { + // Decode as UTF-8 whatever the charset, since package:http falls back + // to latin1 when the content-type does not name one. + data = utf8.decode(res.bodyBytes); + } else if (isJson) { + data = json.decode(res.body); } else { - if (responseType == ResponseType.bytes) { - data = res.bodyBytes; - } else { - data = res.body; - } + data = res.body; } return Response(data: data); } @@ -141,10 +142,12 @@ mixin ClientMixin { return http.Response( '', streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), + headers: streamedResponse.headers.map( + (k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v), + ), request: streamedResponse.request, isRedirect: streamedResponse.isRedirect, persistentConnection: streamedResponse.persistentConnection, diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 6b1e67cd..05253273 100644 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -17,14 +17,15 @@ class CookieManager extends Interceptor { await cookieJar .loadForRequest(Uri(scheme: request.url.scheme, host: request.url.host)) .then((cookies) { - var cookie = getCookies(cookies); - if (cookie.isNotEmpty) { - request.headers.addAll({HttpHeaders.cookieHeader: cookie}); - } - return request; - }).catchError((e, stackTrace) { - return request; - }); + var cookie = getCookies(cookies); + if (cookie.isNotEmpty) { + request.headers.addAll({HttpHeaders.cookieHeader: cookie}); + } + return request; + }) + .catchError((e, stackTrace) { + return request; + }); return request; } @@ -43,8 +44,9 @@ class CookieManager extends Interceptor { var cookies = cookie.split(exp); await cookieJar.saveFromResponse( Uri( - scheme: response.request!.url.scheme, - host: response.request!.url.host), + scheme: response.request!.url.scheme, + host: response.request!.url.host, + ), cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } diff --git a/lib/src/enums.dart b/lib/src/enums.dart index 595afdc2..0f250ea3 100644 --- a/lib/src/enums.dart +++ b/lib/src/enums.dart @@ -17,5 +17,5 @@ enum ResponseType { plain, /// Get original bytes, the type of response will be `List` - bytes + bytes, } diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 02b85c7f..ab1b5668 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -43,6 +43,7 @@ enum OAuthProvider { tradeshift(value: "tradeshift"), tradeshiftBox(value: "tradeshiftBox"), twitch(value: "twitch"), + webflow(value: "webflow"), wordpress(value: "wordpress"), x(value: "x"), yahoo(value: "yahoo"), diff --git a/lib/src/input_file.dart b/lib/src/input_file.dart index c0be7c04..f1022c22 100644 --- a/lib/src/input_file.dart +++ b/lib/src/input_file.dart @@ -8,16 +8,38 @@ class InputFile { final String? contentType; @Deprecated('Use `InputFile.fromPath` or `InputFile.fromBytes` instead.') - InputFile({this.path, this.filename, this.contentType, this.bytes}) { + InputFile({ + String? path, + String? filename, + String? contentType, + List? bytes, + }) : this._( + path: path, + filename: filename, + contentType: contentType, + bytes: bytes, + ); + + InputFile._({this.path, String? filename, this.contentType, this.bytes}) + : filename = filename ?? _filenameFromPath(path) { if (path == null && bytes == null) { throw AppwriteException('One of `path` or `bytes` is required'); } } - InputFile._({this.path, this.filename, this.contentType, this.bytes}) { - if (path == null && bytes == null) { - throw AppwriteException('One of `path` or `bytes` is required'); + /// Mirrors how `package:http` derives a filename in `MultipartFile.fromPath`, + /// so a chunked upload sends the same `filename` as a single-request one. + /// Without it the chunk parts carry no `filename` and the server rejects them + /// as an empty file. + static String? _filenameFromPath(String? path) { + if (path == null) { + return null; } + + final segments = Uri.file(path).pathSegments; + final filename = segments.isEmpty ? '' : segments.last; + + return filename.isEmpty ? null : filename; } /// Provide a file using `path` diff --git a/lib/src/models/account.dart b/lib/src/models/account.dart new file mode 100644 index 00000000..31e79064 --- /dev/null +++ b/lib/src/models/account.dart @@ -0,0 +1,167 @@ +part of '../../models.dart'; + +/// Account +class Account implements Model { + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Canonical form of the user email address. + final String? emailCanonical; + + /// Whether the user email is from a free email provider. + final bool? emailIsFree; + + /// Whether the user email is from a disposable email provider. + final bool? emailIsDisposable; + + /// Whether the user email is from a corporate domain. + final bool? emailIsCorporate; + + /// Whether the user email is in its canonical form. + final bool? emailIsCanonical; + + /// Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked. + final bool? passwordPwned; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + /// Whether the user can impersonate other users. + final bool? impersonator; + + /// ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data. + final String? impersonatorUserId; + + Account({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + this.emailCanonical, + this.emailIsFree, + this.emailIsDisposable, + this.emailIsCorporate, + this.emailIsCanonical, + this.passwordPwned, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + this.impersonator, + this.impersonatorUserId, + }); + factory Account.fromMap( + Map map, + ) { + return Account( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + registration: map['registration'].toString(), + status: map['status'], + labels: List.from(map['labels'] ?? []), + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + emailCanonical: map['emailCanonical']?.toString(), + emailIsFree: map['emailIsFree'], + emailIsDisposable: map['emailIsDisposable'], + emailIsCorporate: map['emailIsCorporate'], + emailIsCanonical: map['emailIsCanonical'], + passwordPwned: map['passwordPwned'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap( + map['prefs'], + ), + targets: List.from( + map['targets'].map((p) => Target.fromMap(p)), + ), + accessedAt: map['accessedAt'].toString(), + impersonator: map['impersonator'], + impersonatorUserId: map['impersonatorUserId']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "emailCanonical": emailCanonical, + "emailIsFree": emailIsFree, + "emailIsDisposable": emailIsDisposable, + "emailIsCorporate": emailIsCorporate, + "emailIsCanonical": emailIsCanonical, + "passwordPwned": passwordPwned, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + "impersonator": impersonator, + "impersonatorUserId": impersonatorUserId, + }; + } +} diff --git a/lib/src/models/app.dart b/lib/src/models/app.dart new file mode 100644 index 00000000..7f2a93cf --- /dev/null +++ b/lib/src/models/app.dart @@ -0,0 +1,177 @@ +part of '../../models.dart'; + +/// App +class App implements Model { + /// App ID. + final String $id; + + /// App creation time in ISO 8601 format. + final String $createdAt; + + /// App update date in ISO 8601 format. + final String $updatedAt; + + /// Application name. + final String name; + + /// Application description shown to users during OAuth2 consent. + final String description; + + /// Application homepage URL shown to users during OAuth2 consent. + final String clientUri; + + /// Application logo URL shown to users during OAuth2 consent. + final String logoUri; + + /// Application privacy policy URL shown to users during OAuth2 consent. + final String privacyPolicyUrl; + + /// Application terms of service URL shown to users during OAuth2 consent. + final String termsUrl; + + /// Application support or security contact emails. + final List contacts; + + /// Application tagline shown to users during OAuth2 consent. + final String tagline; + + /// Application tags shown to users during OAuth2 consent. + final List tags; + + /// Application labels. Read-only for clients; only a server SDK using a project API key can update them. + final List labels; + + /// Application image URLs shown to users during OAuth2 consent. + final List images; + + /// Application support URL shown to users during OAuth2 consent. + final String supportUrl; + + /// Application data deletion URL shown to users during OAuth2 consent. + final String dataDeletionUrl; + + /// List of authorized redirect URIs. These URIs can be used to redirect users after they authenticate. + final List redirectUris; + + /// List of authorized post-logout redirect URIs for OpenID Connect RP-Initiated Logout. The logout endpoint only redirects users to URIs in this list after ending their session. + final List postLogoutRedirectUris; + + /// Whether the app is enabled or not. + final bool enabled; + + /// OAuth2 client type. `public` for SPAs, mobile, and native apps that cannot keep a client secret (PKCE required); `confidential` for server-side clients that authenticate with a client secret. + final String type; + + /// Whether this client may use the OAuth2 Device Authorization Grant (RFC 8628). + final bool deviceFlow; + + /// ID of team that owns the application, if owned by team. Otherwise, user ID will be used. + final String teamId; + + /// ID of user who owns the application, if owned by user. Otherwise, team ID will be used. + final String userId; + + /// Scopes the application requests when installed on a team. Organization-level and project-level scopes only. + final List installationScopes; + + /// URL users are redirected to after creating or updating an installation of this application. Empty for no redirect. + final String installationRedirectUrl; + + /// List of application secrets. + final List secrets; + + App({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.description, + required this.clientUri, + required this.logoUri, + required this.privacyPolicyUrl, + required this.termsUrl, + required this.contacts, + required this.tagline, + required this.tags, + required this.labels, + required this.images, + required this.supportUrl, + required this.dataDeletionUrl, + required this.redirectUris, + required this.postLogoutRedirectUris, + required this.enabled, + required this.type, + required this.deviceFlow, + required this.teamId, + required this.userId, + required this.installationScopes, + required this.installationRedirectUrl, + required this.secrets, + }); + factory App.fromMap( + Map map, + ) { + return App( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + description: map['description'].toString(), + clientUri: map['clientUri'].toString(), + logoUri: map['logoUri'].toString(), + privacyPolicyUrl: map['privacyPolicyUrl'].toString(), + termsUrl: map['termsUrl'].toString(), + contacts: List.from(map['contacts'] ?? []), + tagline: map['tagline'].toString(), + tags: List.from(map['tags'] ?? []), + labels: List.from(map['labels'] ?? []), + images: List.from(map['images'] ?? []), + supportUrl: map['supportUrl'].toString(), + dataDeletionUrl: map['dataDeletionUrl'].toString(), + redirectUris: List.from(map['redirectUris'] ?? []), + postLogoutRedirectUris: List.from(map['postLogoutRedirectUris'] ?? []), + enabled: map['enabled'], + type: map['type'].toString(), + deviceFlow: map['deviceFlow'], + teamId: map['teamId'].toString(), + userId: map['userId'].toString(), + installationScopes: List.from(map['installationScopes'] ?? []), + installationRedirectUrl: map['installationRedirectUrl'].toString(), + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "description": description, + "clientUri": clientUri, + "logoUri": logoUri, + "privacyPolicyUrl": privacyPolicyUrl, + "termsUrl": termsUrl, + "contacts": contacts, + "tagline": tagline, + "tags": tags, + "labels": labels, + "images": images, + "supportUrl": supportUrl, + "dataDeletionUrl": dataDeletionUrl, + "redirectUris": redirectUris, + "postLogoutRedirectUris": postLogoutRedirectUris, + "enabled": enabled, + "type": type, + "deviceFlow": deviceFlow, + "teamId": teamId, + "userId": userId, + "installationScopes": installationScopes, + "installationRedirectUrl": installationRedirectUrl, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_key.dart b/lib/src/models/app_key.dart new file mode 100644 index 00000000..5834ee2d --- /dev/null +++ b/lib/src/models/app_key.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppKey +class AppKey implements Model { + /// App key ID. + final String $id; + + /// App key creation time in ISO 8601 format. + final String $createdAt; + + /// App key update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this app key belongs to. + final String appId; + + /// App key secret. + final String secret; + + /// Last few characters of the app key secret, used to help identify it. + final String hint; + + /// ID of the user who created the app key. + final String createdById; + + /// Name of the user who created the app key. + final String createdByName; + + /// Time the app key was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppKey({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppKey.fromMap( + Map map, + ) { + return AppKey( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_key_list.dart b/lib/src/models/app_key_list.dart new file mode 100644 index 00000000..f4175972 --- /dev/null +++ b/lib/src/models/app_key_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App keys list +class AppKeyList implements Model { + /// Total number of keys that matched your query. + final int total; + + /// List of keys. + final List keys; + + AppKeyList({ + required this.total, + required this.keys, + }); + factory AppKeyList.fromMap( + Map map, + ) { + return AppKeyList( + total: map['total'], + keys: List.from( + map['keys'].map((p) => AppKey.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "keys": keys.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_scope.dart b/lib/src/models/app_scope.dart new file mode 100644 index 00000000..456b614b --- /dev/null +++ b/lib/src/models/app_scope.dart @@ -0,0 +1,49 @@ +part of '../../models.dart'; + +/// AppScope +class AppScope implements Model { + /// Scope value as requested by apps. + final String value; + + /// Human-readable description of what the scope grants. + final String description; + + /// What the scope grants access to. One of `account`, `project`, or `organization`. Only `project` and `organization` scopes are installable. + final String type; + + /// Scope category, used to group scopes on consent and installation screens. + final String category; + + /// Whether the scope is deprecated. Deprecated scopes can still be requested but should not be offered for new grants. + final bool deprecated; + + AppScope({ + required this.value, + required this.description, + required this.type, + required this.category, + required this.deprecated, + }); + factory AppScope.fromMap( + Map map, + ) { + return AppScope( + value: map['value'].toString(), + description: map['description'].toString(), + type: map['type'].toString(), + category: map['category'].toString(), + deprecated: map['deprecated'], + ); + } + + @override + Map toMap() { + return { + "value": value, + "description": description, + "type": type, + "category": category, + "deprecated": deprecated, + }; + } +} diff --git a/lib/src/models/app_scope_list.dart b/lib/src/models/app_scope_list.dart new file mode 100644 index 00000000..b59e3e64 --- /dev/null +++ b/lib/src/models/app_scope_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App scopes list +class AppScopeList implements Model { + /// Total number of scopes that matched your query. + final int total; + + /// List of scopes. + final List scopes; + + AppScopeList({ + required this.total, + required this.scopes, + }); + factory AppScopeList.fromMap( + Map map, + ) { + return AppScopeList( + total: map['total'], + scopes: List.from( + map['scopes'].map((p) => AppScope.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "scopes": scopes.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret.dart b/lib/src/models/app_secret.dart new file mode 100644 index 00000000..b16b102b --- /dev/null +++ b/lib/src/models/app_secret.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecret +class AppSecret implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Always empty. The application client secret is returned only once, in the response of the createSecret method. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecret({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecret.fromMap( + Map map, + ) { + return AppSecret( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/app_secret_list.dart b/lib/src/models/app_secret_list.dart new file mode 100644 index 00000000..7eb90b7a --- /dev/null +++ b/lib/src/models/app_secret_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// App secrets list +class AppSecretList implements Model { + /// Total number of secrets that matched your query. + final int total; + + /// List of secrets. + final List secrets; + + AppSecretList({ + required this.total, + required this.secrets, + }); + factory AppSecretList.fromMap( + Map map, + ) { + return AppSecretList( + total: map['total'], + secrets: List.from( + map['secrets'].map((p) => AppSecret.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "secrets": secrets.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/app_secret_plaintext.dart b/lib/src/models/app_secret_plaintext.dart new file mode 100644 index 00000000..b70d06e1 --- /dev/null +++ b/lib/src/models/app_secret_plaintext.dart @@ -0,0 +1,73 @@ +part of '../../models.dart'; + +/// AppSecretPlaintext +class AppSecretPlaintext implements Model { + /// Secret ID. + final String $id; + + /// Secret creation time in ISO 8601 format. + final String $createdAt; + + /// Secret update time in ISO 8601 format. + final String $updatedAt; + + /// Application ID this secret belongs to. + final String appId; + + /// Application client secret. Returned only when the secret is created; subsequent reads always return an empty value. + final String secret; + + /// Last few characters of the client secret, used to help identify it. + final String hint; + + /// ID of the user who created the secret. + final String createdById; + + /// Name of the user who created the secret. + final String createdByName; + + /// Time the secret was last used for authentication in ISO 8601 format. Null if never used. + final String? lastAccessedAt; + + AppSecretPlaintext({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.appId, + required this.secret, + required this.hint, + required this.createdById, + required this.createdByName, + this.lastAccessedAt, + }); + factory AppSecretPlaintext.fromMap( + Map map, + ) { + return AppSecretPlaintext( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + appId: map['appId'].toString(), + secret: map['secret'].toString(), + hint: map['hint'].toString(), + createdById: map['createdById'].toString(), + createdByName: map['createdByName'].toString(), + lastAccessedAt: map['lastAccessedAt']?.toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "appId": appId, + "secret": secret, + "hint": hint, + "createdById": createdById, + "createdByName": createdByName, + "lastAccessedAt": lastAccessedAt, + }; + } +} diff --git a/lib/src/models/apps_list.dart b/lib/src/models/apps_list.dart new file mode 100644 index 00000000..0492e9f4 --- /dev/null +++ b/lib/src/models/apps_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// Apps list +class AppsList implements Model { + /// Total number of apps that matched your query. + final int total; + + /// List of apps. + final List apps; + + AppsList({ + required this.total, + required this.apps, + }); + factory AppsList.fromMap( + Map map, + ) { + return AppsList( + total: map['total'], + apps: List.from( + map['apps'].map((p) => App.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "apps": apps.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_approve.dart b/lib/src/models/oauth2_approve.dart new file mode 100644 index 00000000..e4db0be4 --- /dev/null +++ b/lib/src/models/oauth2_approve.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Approve +class Oauth2Approve implements Model { + /// URL the end user should be redirected to after the grant is approved, carrying the authorization `code` and/or `id_token` along with the original `state`. + final String redirectUrl; + + Oauth2Approve({ + required this.redirectUrl, + }); + factory Oauth2Approve.fromMap( + Map map, + ) { + return Oauth2Approve( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_authorize.dart b/lib/src/models/oauth2_authorize.dart new file mode 100644 index 00000000..0e820c68 --- /dev/null +++ b/lib/src/models/oauth2_authorize.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 Authorize +class Oauth2Authorize implements Model { + /// OAuth2 grant ID. Set when the user must give explicit consent; pass it to the approve or reject endpoint. Empty when a redirect URL is returned instead. + final String grantId; + + /// URL the end user should be redirected to when the flow can complete without consent. Empty when consent is still required. + final String redirectUrl; + + Oauth2Authorize({ + required this.grantId, + required this.redirectUrl, + }); + factory Oauth2Authorize.fromMap( + Map map, + ) { + return Oauth2Authorize( + grantId: map['grantId'].toString(), + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "grantId": grantId, + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_device_authorization.dart b/lib/src/models/oauth2_device_authorization.dart new file mode 100644 index 00000000..010af212 --- /dev/null +++ b/lib/src/models/oauth2_device_authorization.dart @@ -0,0 +1,55 @@ +part of '../../models.dart'; + +/// OAuth2 Device Authorization +class Oauth2DeviceAuthorization implements Model { + /// Device verification code used by the client to poll the token endpoint. + final String device_code; + + /// Short code the end user enters on the verification page. + final String user_code; + + /// URL where the end user enters the user code. + final String verification_uri; + + /// Verification URL with the user code prefilled as a query parameter. + final String verification_uri_complete; + + /// Lifetime of the device code and user code in seconds. + final int expires_in; + + /// Minimum polling interval for the token endpoint in seconds. + final int interval; + + Oauth2DeviceAuthorization({ + required this.device_code, + required this.user_code, + required this.verification_uri, + required this.verification_uri_complete, + required this.expires_in, + required this.interval, + }); + factory Oauth2DeviceAuthorization.fromMap( + Map map, + ) { + return Oauth2DeviceAuthorization( + device_code: map['device_code'].toString(), + user_code: map['user_code'].toString(), + verification_uri: map['verification_uri'].toString(), + verification_uri_complete: map['verification_uri_complete'].toString(), + expires_in: map['expires_in'], + interval: map['interval'], + ); + } + + @override + Map toMap() { + return { + "device_code": device_code, + "user_code": user_code, + "verification_uri": verification_uri, + "verification_uri_complete": verification_uri_complete, + "expires_in": expires_in, + "interval": interval, + }; + } +} diff --git a/lib/src/models/oauth2_grant.dart b/lib/src/models/oauth2_grant.dart new file mode 100644 index 00000000..32f22b8f --- /dev/null +++ b/lib/src/models/oauth2_grant.dart @@ -0,0 +1,91 @@ +part of '../../models.dart'; + +/// OAuth2 Grant +class Oauth2Grant implements Model { + /// Grant ID. + final String $id; + + /// Grant creation time in ISO 8601 format. + final String $createdAt; + + /// Grant update date in ISO 8601 format. + final String $updatedAt; + + /// ID of the user the grant belongs to. + final String userId; + + /// ID of the OAuth2 client (app) the grant was requested for. + final String appId; + + /// Requested OAuth2 scopes the user is being asked to consent to. + final List scopes; + + /// Requested RFC 8707 resource indicators the user is being asked to consent to. + final List resources; + + /// Requested authorization_details the user is being asked to consent to, as a JSON string. Each entry has a `type` plus project-defined fields. + final String authorizationDetails; + + /// OIDC prompt directive the consent screen should honor. Space-separated list of: login, consent, select_account. + final String prompt; + + /// Redirect URI the user will be sent to after the flow completes. + final String redirectUri; + + /// Unix timestamp of when the user last authenticated. + final int authTime; + + /// Grant expiration time in ISO 8601 format. + final String expire; + + Oauth2Grant({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.appId, + required this.scopes, + required this.resources, + required this.authorizationDetails, + required this.prompt, + required this.redirectUri, + required this.authTime, + required this.expire, + }); + factory Oauth2Grant.fromMap( + Map map, + ) { + return Oauth2Grant( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + appId: map['appId'].toString(), + scopes: List.from(map['scopes'] ?? []), + resources: List.from(map['resources'] ?? []), + authorizationDetails: map['authorizationDetails'].toString(), + prompt: map['prompt'].toString(), + redirectUri: map['redirectUri'].toString(), + authTime: map['authTime'], + expire: map['expire'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "appId": appId, + "scopes": scopes, + "resources": resources, + "authorizationDetails": authorizationDetails, + "prompt": prompt, + "redirectUri": redirectUri, + "authTime": authTime, + "expire": expire, + }; + } +} diff --git a/lib/src/models/oauth2_organization.dart b/lib/src/models/oauth2_organization.dart new file mode 100644 index 00000000..bef13975 --- /dev/null +++ b/lib/src/models/oauth2_organization.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Organization +class Oauth2Organization implements Model { + /// Organization ID. + final String $id; + + Oauth2Organization({ + required this.$id, + }); + factory Oauth2Organization.fromMap( + Map map, + ) { + return Oauth2Organization( + $id: map['\$id'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + }; + } +} diff --git a/lib/src/models/oauth2_organization_list.dart b/lib/src/models/oauth2_organization_list.dart new file mode 100644 index 00000000..e9136230 --- /dev/null +++ b/lib/src/models/oauth2_organization_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible organizations list +class Oauth2OrganizationList implements Model { + /// Total number of organizations that matched your query. + final int total; + + /// List of organizations. + final List organizations; + + Oauth2OrganizationList({ + required this.total, + required this.organizations, + }); + factory Oauth2OrganizationList.fromMap( + Map map, + ) { + return Oauth2OrganizationList( + total: map['total'], + organizations: List.from( + map['organizations'].map((p) => Oauth2Organization.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "organizations": organizations.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_par.dart b/lib/src/models/oauth2_par.dart new file mode 100644 index 00000000..24c14ec5 --- /dev/null +++ b/lib/src/models/oauth2_par.dart @@ -0,0 +1,31 @@ +part of '../../models.dart'; + +/// OAuth2 PAR +class Oauth2PAR implements Model { + /// Authorization request handle to pass to the authorize endpoint. + final String request_uri; + + /// Lifetime of the authorization request handle in seconds. + final int expires_in; + + Oauth2PAR({ + required this.request_uri, + required this.expires_in, + }); + factory Oauth2PAR.fromMap( + Map map, + ) { + return Oauth2PAR( + request_uri: map['request_uri'].toString(), + expires_in: map['expires_in'], + ); + } + + @override + Map toMap() { + return { + "request_uri": request_uri, + "expires_in": expires_in, + }; + } +} diff --git a/lib/src/models/oauth2_project.dart b/lib/src/models/oauth2_project.dart new file mode 100644 index 00000000..306faf36 --- /dev/null +++ b/lib/src/models/oauth2_project.dart @@ -0,0 +1,37 @@ +part of '../../models.dart'; + +/// OAuth2 Project +class Oauth2Project implements Model { + /// Project ID. + final String $id; + + /// Region ID the project is deployed in. + final String region; + + /// API endpoint of the region the project is deployed in. Empty when the region has no public hostname configured. + final String endpoint; + + Oauth2Project({ + required this.$id, + required this.region, + required this.endpoint, + }); + factory Oauth2Project.fromMap( + Map map, + ) { + return Oauth2Project( + $id: map['\$id'].toString(), + region: map['region'].toString(), + endpoint: map['endpoint'].toString(), + ); + } + + @override + Map toMap() { + return { + "\$id": $id, + "region": region, + "endpoint": endpoint, + }; + } +} diff --git a/lib/src/models/oauth2_project_list.dart b/lib/src/models/oauth2_project_list.dart new file mode 100644 index 00000000..6eef6c21 --- /dev/null +++ b/lib/src/models/oauth2_project_list.dart @@ -0,0 +1,33 @@ +part of '../../models.dart'; + +/// OAuth2 accessible projects list +class Oauth2ProjectList implements Model { + /// Total number of projects that matched your query. + final int total; + + /// List of projects. + final List projects; + + Oauth2ProjectList({ + required this.total, + required this.projects, + }); + factory Oauth2ProjectList.fromMap( + Map map, + ) { + return Oauth2ProjectList( + total: map['total'], + projects: List.from( + map['projects'].map((p) => Oauth2Project.fromMap(p)), + ), + ); + } + + @override + Map toMap() { + return { + "total": total, + "projects": projects.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/oauth2_reject.dart b/lib/src/models/oauth2_reject.dart new file mode 100644 index 00000000..26b94257 --- /dev/null +++ b/lib/src/models/oauth2_reject.dart @@ -0,0 +1,25 @@ +part of '../../models.dart'; + +/// OAuth2 Reject +class Oauth2Reject implements Model { + /// URL the end user should be redirected to after the grant is rejected, carrying an `access_denied` error. + final String redirectUrl; + + Oauth2Reject({ + required this.redirectUrl, + }); + factory Oauth2Reject.fromMap( + Map map, + ) { + return Oauth2Reject( + redirectUrl: map['redirectUrl'].toString(), + ); + } + + @override + Map toMap() { + return { + "redirectUrl": redirectUrl, + }; + } +} diff --git a/lib/src/models/oauth2_token.dart b/lib/src/models/oauth2_token.dart new file mode 100644 index 00000000..590264b2 --- /dev/null +++ b/lib/src/models/oauth2_token.dart @@ -0,0 +1,61 @@ +part of '../../models.dart'; + +/// OAuth2 Token +class Oauth2Token implements Model { + /// OAuth2 access token. + final String access_token; + + /// OAuth2 token type. + final String token_type; + + /// Access token lifetime in seconds. + final int expires_in; + + /// OAuth2 refresh token. + final String refresh_token; + + /// Space-separated scopes granted to the access token. + final String scope; + + /// Granted RFC 9396 authorization details as a JSON string. + final String? authorization_details; + + /// OpenID Connect ID token. Returned when the `openid` scope is granted. + final String? id_token; + + Oauth2Token({ + required this.access_token, + required this.token_type, + required this.expires_in, + required this.refresh_token, + required this.scope, + this.authorization_details, + this.id_token, + }); + factory Oauth2Token.fromMap( + Map map, + ) { + return Oauth2Token( + access_token: map['access_token'].toString(), + token_type: map['token_type'].toString(), + expires_in: map['expires_in'], + refresh_token: map['refresh_token'].toString(), + scope: map['scope'].toString(), + authorization_details: map['authorization_details']?.toString(), + id_token: map['id_token']?.toString(), + ); + } + + @override + Map toMap() { + return { + "access_token": access_token, + "token_type": token_type, + "expires_in": expires_in, + "refresh_token": refresh_token, + "scope": scope, + "authorization_details": authorization_details, + "id_token": id_token, + }; + } +} diff --git a/lib/src/mqtt.dart b/lib/src/mqtt.dart new file mode 100644 index 00000000..d55f1e8e --- /dev/null +++ b/lib/src/mqtt.dart @@ -0,0 +1,129 @@ +import 'mqtt_browser.dart' if (dart.library.io) 'mqtt_io.dart'; +import 'service.dart'; +import 'client.dart'; +import 'mqtt_message.dart'; + +/// A callback invoked for every message delivered on a subscribed topic. +typedef PushCallback = void Function(PushMessage message); + +/// Handle for a live subscription created with [Push.subscribe]. +/// +/// Unlike the realtime service's bare unsubscribe callable, a push subscription carries +/// per-subscription state (background delivery, notification title), so [subscribe] +/// returns this handle instead: [unsubscribe] drops it (and closes the connection once +/// the last one is gone) and [update] toggles its options live without resubscribing. +abstract class PushSubscription { + /// Drop this subscription. Closes the connection once the last one is gone. + void unsubscribe(); + + /// Live-update this subscription's [background] delivery, notification [title] and/or + /// [retry] (QoS). Only the arguments you pass change; the rest stay as they + /// were. Changing [retry] re-subscribes this subscription's topics at the + /// new QoS. + void update({bool? background, String? title, bool? retry}); +} + +/// Appwrite native push service — the realtime analog delivered over an MQTT +/// broker, without FCM or APNS. While the app is alive the connection stays open and each +/// message is handed to your callback; a subscription can also opt into background +/// delivery (a notification per message, and on mobile continued delivery while the app is +/// backgrounded or closed). +/// +/// The connection has no tunables — it always keeps its session (clean start off) so the +/// broker can redeliver missed messages, and reliability is chosen per subscription via +/// [subscribe]'s `retry`. TLS (and skipping cert verification via a +/// `?tlsInsecure=true` query flag) is derived from the endpoint, so the whole connection +/// is described in one place. `subscribe` opens the connection lazily and returns a +/// [PushSubscription] handle. The credential is read off the client — set a JWT or session +/// on it (`Client.setJWT` / `Client.setSession`), the same way every other service reads +/// auth. The broker location comes from `Client.setPushEndpoint()` (or the client +/// endpoint) and a stable id from `Client.setPushClientId()`. +/// +/// ```dart +/// final client = Client().setEndpoint('...').setProject('...').setJWT(jwt); +/// final push = Push(client); +/// final sub = await push.subscribe('user/123/#', (message) { +/// print('${message.topic}: ${message.data}'); +/// }); +/// +/// // sub.update(background: true, title: 'Messages'); +/// sub.unsubscribe(); +/// ``` +abstract class Push extends Service { + /// Initializes a [Push] service. + factory Push(Client client) => createPush(client); + + /// Register a callback invoked when the connection opens (CONNACK success). + Push onOpen(void Function() callback); + + /// Register a callback invoked when the connection closes. + Push onClose(void Function() callback); + + /// Register a callback invoked with every error the service hits: a failed or refused + /// connect or reconnect (carrying the broker's reason string when it sent one), a + /// DISCONNECT from the broker, a rejected SUBSCRIBE and background delivery failures. + /// Errors a call also throws (such as [subscribe]'s) are reported here as well. Errors that + /// no call throws are never thrown, so they cannot crash the app: with no callback + /// registered they are logged. + Push onError(void Function(Object error) callback); + + /// Subscribe to one or more topics, resolving to a [PushSubscription] handle. + /// + /// [topics] is a single topic or a list of them, each a string or a `Topic` builder + /// (e.g. `Topic.path(['user', userId]).all()`). Pass `null` to subscribe to the + /// signed-in user's own `users/` topic ("messages for me") without knowing any + /// topic: the user id is read off the client's JWT (or, without one, its session) with + /// no network call, and `AppwriteException` is thrown when neither is set. + /// Like FCM/APNs delivery, the `null` form defaults to [background] `true` (topics default to + /// `false`) and, as always, [retry] `true` (QoS 1); pass either to override. + /// + /// ```dart + /// final sub = await push.subscribe(null, (message) { + /// print(message.data); + /// }); + /// ``` + /// + /// The future resolves only once every subscription has been acknowledged (SUBACK), so a + /// subscribe-then-publish is reliable, and [onOpen]/[onClose]/[onError] observe the + /// in-process connection. On Android a [background] subscription moves the connection to the + /// SDK's native plugin, which also resolves after SUBACK and forwards messages and errors (to + /// [onError]) but not its connection lifecycle, so [onOpen]/[onClose] do not fire for it. On + /// iOS it hands the connection to a background isolate, which subscribes asynchronously and + /// retries failures internally, so it resolves once the isolate has the subscription. + /// + /// [retry] chooses this subscription's delivery guarantee: `true` (the + /// default) subscribes at QoS 1 so the broker holds this topic's messages and redelivers + /// them on reconnect; `false` uses QoS 0 (at-most-once, may be lost). The connection + /// always keeps its session, so replay is a purely per-subscription choice. + /// + /// Set [background] to also keep receiving while the app is backgrounded or closed and post a + /// notification per message with [title] (defaulting to the message topic). Toggle these + /// later with [PushSubscription.update]. + /// + /// On Android the SDK's native plugin saves the subscription and keeps delivering after the + /// app is killed, the device restarts or the app updates, until it is unsubscribed or [close] + /// is called: a scheduled job and alarm wake the app every 15 to 60 seconds to reconnect, and + /// the broker replays what was sent in between ([retry]). [setForeground] adds a foreground + /// service for immediate delivery. It reconnects with the credential saved at subscribe time, + /// so use a session rather than a short-lived JWT. On iOS it runs the connection in a + /// background isolate via `flutter_background_service`; on the web it posts a browser + /// notification while the tab is open. + Future subscribe( + Object? topics, // String, Topic, ResolvedTopic, a List, or null (own user) + PushCallback callback, { + bool? background, + String? title, + bool retry, + }); + + /// Android: run background delivery in a foreground service (with a quiet ongoing + /// notification), for immediate delivery even after the app is killed and during Doze, + /// instead of only the scheduled wake-ups. Saved, so it applies after restarts too. Call it + /// while the app is in the foreground: Android 12+ refuses to start the service from the + /// background. It only affects [background] subscriptions. A no-op elsewhere. + Future setForeground(bool enabled); + + /// Tear down the connection and drop all subscriptions. On Android this also stops + /// background delivery, including subscriptions saved by an earlier run: call it on sign-out. + void close(); +} diff --git a/lib/src/mqtt_browser.dart b/lib/src/mqtt_browser.dart new file mode 100644 index 00000000..4e291b43 --- /dev/null +++ b/lib/src/mqtt_browser.dart @@ -0,0 +1,904 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +// ignore: avoid_web_libraries_in_flutter, deprecated_member_use +import 'dart:html' as html; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_browser_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_message.dart'; + +Push createPush(Client client) => PushWeb(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +/// Web push transport. A browser cannot open a raw TCP socket, so the connection is +/// MQTT over WebSocket (`ws://` / `wss://`) via [MqttBrowserClient]; the native +/// (`dart:io`) build in `mqtt_io.dart` uses a TCP socket instead. The API is identical. +class PushWeb implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final String _path; + + MqttBrowserClient? _mqtt; + Future? _connecting; + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across reloads; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushWeb(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "wss://host"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: WSS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = _pushEndpointPort(client) ?? (resolvedTls ? 443 : 80); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushWeb._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + path: _pushPath(client), + ); + } + + PushWeb._( + this.client, { + required String host, + required int port, + required bool tls, + required String path, + }) : _host = host, + _port = port, + _tls = tls, + _path = path; + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across reloads. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // The WebSocket path from an explicitly-set push endpoint, or the root path by + // default (the broker serves MQTT-over-WebSocket at the root; no "/mqtt" is appended). + static String _pushPath(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint != null) { + try { + final path = Uri.parse(endpoint).path; + if (path.isNotEmpty && path != '/') { + return path; + } + } catch (_) {} + } + return ''; + } + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + return this; + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + final MqttBrowserClient mqtt; + try { + topicList = _topicList(client, topics); + mqtt = await _connect(); + } catch (e) { + if (e is _Superseded) { + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + _notify(e); + rethrow; + } + final epoch = _connectionEpoch; + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + + if (wantsBackground) { + _requestNotificationPermission(); + } + + final ids = []; + final acks = >[]; + + void unsubscribe() { + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + // A filter that lost its last QoS-1 sub but still has QoS-0 subs must be re-subscribed + // lower, or the broker keeps replaying to at-most-once subs. + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + close(); + } + } + + // The broker only starts routing a topic once its subscription is registered, + // so publishing before the SUBACK races the message ahead of the subscription + // and it is dropped (no retained replay on MQTT). Awaiting makes it reliable. + // If any topic's SUBACK fails, roll this call's registrations back (and drop any + // now-unused broker filter) so a failed subscribe leaks no callback, then rethrow. + try { + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + + final completer = Completer(); + (_subAcks[topic] ??= >[]).add(completer); + acks.add(completer.future); + + final subscription = MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(topic), + _effectiveQos(topic), + ); + mqtt.subscribeWithSubscriptionList([subscription]); + } + await Future.wait(acks); + } catch (e) { + if (epoch != _connectionEpoch) { + for (final id in ids) { + _subscriptions.remove(id); + } + return subscribe( + topics, + callback, + background: background, + title: title, + retry: retry, + ); + } + unsubscribe(); + _notify(e); + rethrow; + } + + void update({bool? background, String? title, bool? retry}) { + final changedFilters = {}; + for (final id in ids) { + final entry = _subscriptions[id]; + if (entry == null) { + continue; + } + if (background != null) { + entry.background = background; + } + if (title != null) { + entry.title = title; + } + if (retry != null && retry != entry.retry) { + entry.retry = retry; + changedFilters.add(entry.filter); + } + } + if (background == true) { + _requestNotificationPermission(); + } + // Re-subscribe affected filters at their new effective QoS. + // A rejected SUBACK reaches onError through [_onSubscribeFail]. + for (final filter in changedFilters) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } catch (e) { + _report(e); + } + } + } + + return _SubscriptionHandle(unsubscribe, update); + } + + void _requestNotificationPermission() { + if (html.Notification.permission != 'granted') { + unawaited( + html.Notification.requestPermission().then( + (_) {}, + onError: _report, + ), + ); + } + } + + // Background delivery on the web is a notification while the tab is open; there is no + // foreground service. + @override + Future setForeground(bool enabled) async {} + + @override + void close() { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _subscriptions.clear(); + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + _mqtt?.disconnect(); + _mqtt = null; + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + _path, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + final clientId = _resolvedClientId; + + final scheme = _tls ? 'wss' : 'ws'; + final mqtt = MqttBrowserClient.withPort( + '$scheme://$_host$_path', + clientId, + _port, + ); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // The broker negotiates the "mqtt" WebSocket subprotocol; offer exactly that so the + // handshake succeeds (a browser rejects the socket when the subprotocol is not echoed). + mqtt.websocketProtocols = MqttConstants.protocolsSingleDefault; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + final filters = _subscriptions.values.map((s) => s.filter).toSet(); + for (final filter in filters) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + // Notification is per-subscription: only subs that opted in show one, each + // with its own title. + if (subscription.background && + html.Notification.permission == 'granted') { + html.Notification(subscription.title ?? topic, body: message.data); + } + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect or a QoS change), so + // onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_foreground.dart b/lib/src/mqtt_foreground.dart new file mode 100644 index 00000000..8636f355 --- /dev/null +++ b/lib/src/mqtt_foreground.dart @@ -0,0 +1,322 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' show DartPluginRegistrant; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; + +/// Android/iOS background delivery for the native (dart:io) push service. +/// +/// Flutter cannot keep the app's own isolate running once the app is closed, so a +/// subscription with `background: true` runs the push connection inside a background isolate +/// held alive by an Android foreground service ([FlutterBackgroundService]). That isolate +/// owns the single MQTT connection, posts a local notification per message +/// ([FlutterLocalNotificationsPlugin]) for the filters that opted into background, and +/// forwards every message back to the app (when it is alive) over a service event so in-app +/// callbacks still fire — mirroring the Android/React Native SDKs' foreground mode. +/// +/// Config is handed to the isolate through a small JSON file in the app documents +/// directory (the isolate does not share the app's memory), and the running isolate is kept +/// in sync via service events. The config file (which holds the credential) is deleted when +/// background delivery stops. + +const String _channelId = 'appwrite-push'; +const String _channelName = 'Notifications'; +const String _messageEvent = 'appwrite.push.message'; +const String _topicsEvent = 'appwrite.push.topics'; +const String _stopEvent = 'appwrite.push.stop'; +const String _errorEvent = 'appwrite.push.error'; + +// How long to wait before retrying a background subscription that failed (SUBACK/connect), +// so delivery converges instead of silently missing messages. +const Duration _retryDelay = Duration(seconds: 2); + +/// The service event the app listens on to forward background messages to callbacks. +String get pushForegroundMessageEvent => _messageEvent; + +/// The service event the isolate relays its errors on, so the app's onError sees them. +String get pushForegroundErrorEvent => _errorEvent; + +// Relay an isolate error to the app (if alive) as its message. +void _relayError(ServiceInstance service, Object error) { + service.invoke(_errorEvent, { + 'message': + error is AppwriteException + ? (error.message ?? error.toString()) + : error.toString(), + }); +} + +Future _configFile() async { + final dir = await getApplicationDocumentsDirectory(); + return File('${dir.path}/appwrite_push_foreground.json'); +} + +Future _writeConfig( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + final config = { + 'endpoint': client.endPoint, + 'endpointPush': client.config['endpointPush'], + 'project': client.config['project'] ?? '', + 'jwt': client.config['jwt'] ?? client.config['jWT'], + 'session': client.config['session'], + 'pushClientId': client.config['pushClientId'], + 'title': serviceTitle, + 'topics': topics, + 'notify': notify, + 'qos': qos, + }; + (await _configFile()).writeAsStringSync(jsonEncode(config)); +} + +// Delete the config file (which holds the credential) so it does not linger on disk after +// background delivery ends. +Future _deleteConfig() async { + try { + final file = await _configFile(); + if (file.existsSync()) { + file.deleteSync(); + } + } catch (_) {} +} + +/// Start the background service (or, if already running, update its topics/notify config +/// live). Called on the app isolate whenever the set of background subscriptions changes. +/// [topics] is the full union the single connection subscribes to; [notify] maps the filters +/// that opted into background to their notification titles. +Future syncPushForeground( + Client client, { + required String serviceTitle, + required List topics, + required Map notify, + required Map qos, +}) async { + await _writeConfig( + client, + serviceTitle: serviceTitle, + topics: topics, + notify: notify, + qos: qos, + ); + + final service = FlutterBackgroundService(); + if (await service.isRunning()) { + // The isolate is already up: hand it the new topic/notify/qos set so a later + // subscribe/unsubscribe/update takes effect without a restart. + service.invoke(_topicsEvent, { + 'topics': topics, + 'notify': notify, + 'qos': qos, + }); + return; + } + + await service.configure( + androidConfiguration: AndroidConfiguration( + onStart: pushForegroundEntry, + isForegroundMode: true, + autoStart: false, + notificationChannelId: _channelId, + initialNotificationTitle: serviceTitle, + initialNotificationContent: 'Listening for messages', + ), + iosConfiguration: IosConfiguration( + onForeground: pushForegroundEntry, + autoStart: false, + ), + ); + await service.startService(); +} + +/// Ask the background service to disconnect and stop, and delete the config file. +Future stopPushForeground() async { + FlutterBackgroundService().invoke(_stopEvent); + await _deleteConfig(); +} + +Map _notifyOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', '$value')); + } + return {}; +} + +Map _qosOf(dynamic raw) { + if (raw is Map) { + return raw.map((key, value) => MapEntry('$key', (value as num).toInt())); + } + return {}; +} + +/// Background isolate entry point: opens the connection, subscribes to the persisted +/// topics (kept in sync via [_topicsEvent]), posts a notification per message for the +/// filters that opted into background and forwards every message to the app. +@pragma('vm:entry-point') +Future pushForegroundEntry(ServiceInstance service) async { + WidgetsFlutterBinding.ensureInitialized(); + DartPluginRegistrant.ensureInitialized(); + + final notifications = FlutterLocalNotificationsPlugin(); + final Map config; + try { + await notifications.initialize( + const InitializationSettings( + android: AndroidInitializationSettings('@mipmap/ic_launcher'), + iOS: DarwinInitializationSettings(), + ), + ); + config = + jsonDecode((await _configFile()).readAsStringSync()) + as Map; + } catch (e) { + _relayError( + service, + AppwriteException('Background push failed to start: $e'), + ); + await _deleteConfig(); + service.stopSelf(); + return; + } + + final client = Client() + .setEndpoint(config['endpoint'] as String) + .setProject(config['project'] as String); + final jwt = config['jwt'] as String?; + final session = config['session'] as String?; + if (jwt != null && jwt.isNotEmpty) { + client.setJWT(jwt); + } else if (session != null && session.isNotEmpty) { + client.setSession(session); + } + final endpointPush = config['endpointPush'] as String?; + if (endpointPush != null && endpointPush.isNotEmpty) { + client.setPushEndpoint(endpointPush); + } + final pushClientId = config['pushClientId'] as String?; + if (pushClientId != null && pushClientId.isNotEmpty) { + client.setPushClientId(pushClientId); + } + + // Connection, subscribe and broker errors go to the app's onError. A failed subscribe + // reaches it through here and is then retried below. + final push = Push(client).onError((error) => _relayError(service, error)); + + // filter -> notification title, for the filters that opted into background. Reassigned on + // each [_topicsEvent]; the subscribe closures read the current map, so title/opt-in changes + // take effect without resubscribing. + var notify = _notifyOf(config['notify']); + // filter -> QoS (1 reliable / 0 not) requested by the app for each topic. + var qos = _qosOf(config['qos']); + + // One broker subscription per topic so topics can be added/removed independently as the + // app's subscriptions change, plus the QoS each is currently subscribed at (so a QoS + // change resubscribes rather than being skipped as "already subscribed"). + final subscriptions = {}; + final subscribedQos = {}; + + Future applyTopics(List topics) async { + final wanted = topics.toSet(); + for (final topic in subscriptions.keys.toList()) { + if (!wanted.contains(topic)) { + subscriptions.remove(topic)?.unsubscribe(); + subscribedQos.remove(topic); + } + } + for (final topic in wanted) { + final desiredQos = qos[topic] ?? 1; + if (subscriptions.containsKey(topic)) { + if (subscribedQos[topic] == desiredQos) { + continue; + } + // QoS changed for this topic: drop and resubscribe at the new level. + subscriptions.remove(topic)?.unsubscribe(); + } + final filter = topic; + subscribedQos[topic] = desiredQos; + subscriptions[topic] = await push.subscribe(topic, (message) { + // Notify only for filters that opted into background, each with its own title. + final title = notify[filter]; + if (title != null) { + notifications.show( + message.topic.hashCode, + title, + message.data, + const NotificationDetails( + android: AndroidNotificationDetails( + _channelId, + _channelName, + importance: Importance.high, + ), + iOS: DarwinNotificationDetails(), + ), + ); + } + // Forward to the app isolate (if alive) so in-app callbacks still fire. + service.invoke(_messageEvent, { + 'topic': message.topic, + 'payload': message.data, + 'qos': message.qos, + }); + }, retry: desiredQos == 1); + } + } + + // Serialize topic updates: applyTopics awaits push.subscribe, so overlapping runs could + // otherwise subscribe a topic twice (losing an unsubscribe handle) or apply out of order. + // Chaining runs them one at a time, in arrival order. + var topicQueue = Future.value(); + // The last requested topic set, so a failed subscribe can be retried against what is + // currently wanted (topics may have changed again by the time the retry fires). + var wantedTopics = []; + var retryScheduled = false; + + void queueTopics(List topics) { + wantedTopics = topics; + // A subscribe can fail (SUBACK refused, connection dropped mid-CONNECT); applyTopics + // skips already-subscribed topics, so retrying the current wanted set converges on the + // missing ones instead of silently dropping them. + topicQueue = topicQueue.then((_) => applyTopics(topics)).catchError(( + Object _, + ) { + if (retryScheduled) { + return; + } + retryScheduled = true; + Timer(_retryDelay, () { + retryScheduled = false; + queueTopics(wantedTopics); + }); + }); + } + + service.on(_topicsEvent).listen((data) { + notify = _notifyOf(data?['notify']); + qos = _qosOf(data?['qos']); + final topics = + ((data?['topics'] as List?) ?? const []).cast(); + queueTopics(topics); + }); + + service.on(_stopEvent).listen((_) async { + for (final subscription in subscriptions.values) { + subscription.unsubscribe(); + } + push.close(); + await _deleteConfig(); + service.stopSelf(); + }); + + queueTopics((config['topics'] as List).cast()); +} diff --git a/lib/src/mqtt_io.dart b/lib/src/mqtt_io.dart new file mode 100644 index 00000000..de665f10 --- /dev/null +++ b/lib/src/mqtt_io.dart @@ -0,0 +1,1333 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:mqtt5_client/mqtt5_client.dart'; +import 'package:mqtt5_client/mqtt5_server_client.dart'; +import 'package:typed_data/typed_data.dart' as typed; +import 'client.dart'; +import 'exception.dart'; +import 'mqtt.dart'; +import 'mqtt_foreground.dart'; +import 'mqtt_message.dart'; +import 'mqtt_native.dart'; + +Push createPush(Client client) => PushIO(client); + +class _Subscription { + final String filter; + final PushCallback callback; + bool background; + String? title; + bool retry; + + _Subscription( + this.filter, + this.callback, { + this.background = false, + this.title, + this.retry = true, + }); +} + +class _SubscriptionHandle implements PushSubscription { + final void Function() _unsubscribe; + final void Function({bool? background, String? title, bool? retry}) _update; + + _SubscriptionHandle(this._unsubscribe, this._update); + + @override + void unsubscribe() => _unsubscribe(); + + @override + void update({bool? background, String? title, bool? retry}) => + _update(background: background, title: title, retry: retry); +} + +// Fixed connection tuning — not exposed as an option. +const int _keepAliveSeconds = 60; + +class PushIO implements Push { + @override + final Client client; + + final String _host; + final int _port; + final bool _tls; + final bool _tlsInsecure; + + MqttServerClient? _mqtt; + Future? _connecting; + + void Function()? _onOpen; + void Function()? _onClose; + void Function(Object error)? _onError; + + // Resolved once per instance: a reconnect rebuilds the client, and if each rebuild drew a + // new random id the broker would treat it as a new session and drop this client's replay + // cursor. A stable id from Client.setPushClientId() resumes replay across restarts; + // otherwise a per-instance id is generated. Reusing one id keeps the session stable. + late final String _resolvedClientId = _pushClientId(); + + // Whether the connection currently lives in the background isolate (foreground service) + // rather than in-process. The connection relocates there while any subscription wants + // background delivery, and back in-process once none do — one connection either way, so + // the broker never sees two sessions with the same client id. + bool _isolateActive = false; + StreamSubscription?>? _serviceListener; + StreamSubscription?>? _serviceErrorListener; + + // On Android the native plugin hosts background delivery instead of the isolate, on the same + // core as the Android SDK. Null elsewhere. + final PushNative? _native = PushNative.instance; + // Whether the subscriptions currently live on the native plugin's connection. + bool _nativeActive = false; + // Bumped when the subscriptions move to the native host, or the credential changes, + // superseding an _open in flight. + int _connectionEpoch = 0; + Completer? _openCancel; + String _connectedKey = ''; + bool _resubscribeOnConnect = false; + StreamSubscription>? _nativeListener; + + // Every Push on Android shares the one native host (one connection per client id), which hosts + // the union of their subscriptions. Native calls run one at a time in call order, so a sign-out + // is never undone by a subscribe still on its way. + static final Set _nativeHosts = {}; + // Every Push with live subscriptions, so the native host can take over their connections. + static final Set _livePushes = {}; + static Future _nativeQueue = Future.value(); + + static Future _enqueueNative(Future Function() op) { + final result = _nativeQueue.then((_) => op()); + _nativeQueue = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Serializes background config writes (topic/notify syncs and stops). Each write is a + // file write plus a service event, so unserialized rapid calls could interleave and apply + // out of order. Chaining runs them in call order; each reads the current state when it + // runs, so the last requested value always wins. + Future _backgroundSync = Future.value(); + + // Local id -> subscription (filter + callback + per-sub options). The id is never sent to + // the broker; it only lets the same topic carry more than one callback. + final Map _subscriptions = {}; + // topic filter -> FIFO queue of completers resolved on each SUBACK. A queue (not a + // single completer) so two concurrent subscribes to the same topic both resolve. + final Map>> _subAcks = {}; + + factory PushIO(Client client) { + // The broker location comes from Client.setPushEndpoint() when set (e.g. + // "mqtts://host:8883"), otherwise from the regular endpoint. + final pushEndpoint = client.config['endpointPush'] ?? client.endPoint; + // Secure by default: TLS on when the endpoint scheme is secure, so the credential in the + // CONNECT packet is not sent over a plaintext socket. + final resolvedTls = _secureScheme(pushEndpoint); + final resolvedPort = + _pushEndpointPort(client) ?? (resolvedTls ? 8883 : 1883); + // When no explicit push endpoint is set, default to a `push.` host on the regular + // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). + final resolvedHost = + client.config['endpointPush'] != null + ? _hostOf(pushEndpoint) + : 'push.${_hostOf(pushEndpoint)}'; + return PushIO._( + client, + host: resolvedHost, + port: resolvedPort, + tls: resolvedTls, + tlsInsecure: _insecureFlag(client), + ); + } + + PushIO._( + this.client, { + required String host, + required int port, + required bool tls, + required bool tlsInsecure, + }) : _host = host, + _port = port, + _tls = tls, + _tlsInsecure = tlsInsecure { + // Resume background delivery saved by an earlier run now, instead of at its next + // scheduled wake-up. + unawaited(_native?.resume().catchError(_report)); + } + + // Empty when the app did not set one: the broker derives a stable id server-side (keyed on + // the credential/project) so the replay cursor resumes across restarts. + // Client.setPushClientId(id) overrides it with an explicit id. + String _pushClientId() => client.config['pushClientId'] ?? ''; + + static bool _secureScheme(String endpoint) { + try { + final scheme = Uri.parse(endpoint).scheme; + return scheme == 'https' || + scheme == 'wss' || + scheme == 'mqtts' || + scheme == 'ssl'; + } catch (_) { + return false; + } + } + + static String _hostOf(String endpoint) { + try { + final host = Uri.parse(endpoint).host; + return host.isEmpty ? 'localhost' : host; + } catch (_) { + return 'localhost'; + } + } + + // Take the port from an explicitly-set push endpoint only (a regular http/https + // endpoint's port is the API port, not the broker's). + static int? _pushEndpointPort(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return null; + } + try { + final port = Uri.parse(endpoint).port; + return port == 0 ? null : port; + } catch (_) { + return null; + } + } + + // Skip TLS cert verification (self-signed brokers / testing) via a query flag on the push + // endpoint, e.g. "mqtts://host:8883?tlsInsecure=true" — so the whole connection is + // described by one URL, not a second config knob. + static bool _insecureFlag(Client client) { + final endpoint = client.config['endpointPush']; + if (endpoint == null) { + return false; + } + try { + final value = Uri.parse(endpoint).queryParameters['tlsInsecure']; + return value == 'true' || value == '1'; + } catch (_) { + return false; + } + } + + @override + Push onOpen(void Function() callback) { + _onOpen = callback; + return this; + } + + @override + Push onClose(void Function() callback) { + _onClose = callback; + return this; + } + + @override + Push onError(void Function(Object error) callback) { + _onError = callback; + // On Android, a refused credential that stopped background delivery while no callback + // was registered is delivered now. + final native = _native; + if (native != null) { + unawaited(() async { + try { + final stopped = await native.setErrorCallback(true); + if (stopped != null) { + _report(AppwriteException(stopped)); + } + } catch (e) { + _report(e); + } + }()); + } + return this; + } + + @override + Future setForeground(bool enabled) async { + await _native?.setForeground(enabled); + } + + // Errors already handed to onError, so one failure reaching it through two paths (a + // refused CONNACK that also fails the subscribe waiting on it) is reported once. + final Expando _reported = Expando(); + + // Every error the service hits goes through here and reaches onError. It is never thrown + // from here, so an error outside any call cannot crash the app. + void _report(Object error) { + if (error is _Superseded) { + // Internal: a connection superseded by the native host, not a failure. + return; + } + try { + if (_reported[error] == true) { + return; + } + _reported[error] = true; + } catch (_) { + // Expando rejects strings/numbers; such an error is simply not de-duplicated. + } + final callback = _onError; + if (callback == null) { + // Never thrown (that would surface as an uncaught error from inside mqtt5_client): + // with no onError registered it is logged, like Realtime does. + developer.log('Push error', name: 'appwrite', error: error); + return; + } + try { + callback(error); + } catch (callbackError, stackTrace) { + developer.log( + 'Push onError threw', + name: 'appwrite', + error: callbackError, + stackTrace: stackTrace, + ); + } + } + + // An error that is also thrown to the caller: onError sees it too, but with no onError + // registered the caller's own throw is enough. + void _notify(Object error) { + if (_onError != null) { + _report(error); + } + } + + @override + Future subscribe( + Object? topics, + PushCallback callback, { + bool? background, + String? title, + bool retry = true, + }) async { + final List topicList; + try { + topicList = _topicList(client, topics); + } catch (e) { + _notify(e); + rethrow; + } + // The own-user topic (topics == null) defaults to background delivery, like FCM/APNs. + final wantsBackground = background ?? topics == null; + _livePushes.add(this); + + final ids = []; + for (final topic in topicList) { + final id = _randomId(); + ids.add(id); + _subscriptions[id] = _Subscription( + topic, + callback, + background: wantsBackground, + title: title, + retry: retry, + ); + } + + try { + final native = _native; + if (native != null && + (_backgroundWanted || + _nativeHosts.isNotEmpty || + await native.hasSaved())) { + // Android: the native plugin hosts the single connection while any subscription, live + // or saved by an earlier run, wants background. + await _hostNative(); + } else if (_backgroundWanted) { + // Any sub wants background: the isolate hosts the single connection (relocating + // off the in-process one if it was up) and covers the whole topic union. + await _hostInIsolate(); + } else { + while (true) { + try { + await _subscribeInProcess(ids); + break; + } on _Superseded { + // Another Push moved this one's subscriptions to the native host meanwhile: this + // subscribe goes there too. + if (_nativeActive) { + await _hostNative(); + break; + } + } + } + } + } catch (e) { + for (final id in ids) { + _subscriptions.remove(id); + } + // Return to a consistent host for whatever subscriptions remain. + _reconcile(); + _notify(e); + rethrow; + } + + return _SubscriptionHandle( + () => _unsubscribeIds(ids), + ({bool? background, String? title, bool? retry}) => + _updateIds(ids, background: background, title: title, retry: retry), + ); + } + + // In-process host: connect and register this call's new filters, awaiting each SUBACK. + Future _subscribeInProcess(List ids) async { + final mqtt = await _connect(); + final acks = >[]; + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + final completer = Completer(); + (_subAcks[sub.filter] ??= >[]).add(completer); + acks.add(completer.future); + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(sub.filter), + _effectiveQos(sub.filter), + ), + ]); + } + // The broker only starts routing a topic once its subscription is registered, so + // publishing before the SUBACK races the message ahead of it. Awaiting makes it reliable. + await Future.wait(acks); + } + + // Host every subscription of every Push on the native plugin's connection (Android), closing + // this one's in-process connection. Completes once the connection is up and every filter is + // subscribed (SUBACK), or throws why not. + Future _hostNative() { + final native = _native!; + final key = _credentialKey; + // The native host carries one connection, so it serves one credential: instances hosted for + // another move back to their own connection. Instances with this credential share its client + // id, so their in-process connections would take over the broker session: they move to the + // native host too. + for (final push in _nativeHosts.toList()) { + if (push._credentialKey != key) { + push._leaveToInProcess(); + if (push._backgroundWanted) { + push._report(AppwriteException(_backgroundDisplaced)); + } + } + } + // Once moved, they stay: if hosting fails, the native host keeps their subscriptions and + // retries on its scheduled runs, and a second connection with the same client id would take + // over its broker session. + for (final push in _livePushes.toList()) { + if (push._subscriptions.isNotEmpty && push._credentialKey == key) { + push._joinNative(native); + } + } + _joinNative(native); + return _enqueueNative(() => _sendToNative(native)); + } + + // Host every native host's subscriptions with this Push's credential. + Future _sendToNative(PushNative native) async { + // Host what is subscribed when this runs, so a close() or an unsubscribe queued meanwhile + // is not undone by an older request. + final subscriptions = [ + for (final push in _nativeHosts) ...push._nativeEntries, + ]; + if (subscriptions.isEmpty) { + return; + } + final (authMethod, credential) = _credential(); + final config = { + 'host': _host, + 'port': _port, + 'tls': _tls, + 'tlsInsecure': _tlsInsecure, + 'clientId': _resolvedClientId, + 'authMethod': authMethod, + 'credential': credential, + 'project': client.config['project'] ?? '', + }; + await native.setErrorCallback( + _nativeHosts.any((push) => push._onError != null), + ); + await native.host(jsonEncode(config), jsonEncode(subscriptions)); + } + + // Move this Push's subscriptions onto the native host, closing its own connection. + void _joinNative(PushNative native) { + // An _open still in flight sees this and closes what it opened, and a subscribe still waiting + // for its SUBACK continues on the native host. + _dropConnection(); + _nativeListener ??= native.listen( + onMessage: (message) { + final sub = _subscriptions[message.id]; + if (sub == null) { + return; + } + try { + sub.callback( + PushMessage( + topic: message.topic, + payload: message.payload, + qos: message.qos, + ), + ); + } catch (e) { + _report(e); + } + // Acknowledged once its callback has run, as on the in-process connection. + unawaited(native.ack(message.ackToken).catchError(_report)); + }, + onError: (message) => _report(AppwriteException(message)), + ); + _nativeHosts.add(this); + _nativeActive = true; + } + + void _dropConnection() { + _connectionEpoch++; + _connecting = null; + _openCancel?.complete(); + _openCancel = null; + for (final waiting in _subAcks.values) { + for (final completer in waiting) { + if (!completer.isCompleted) { + completer.completeError(const _Superseded()); + } + } + } + _subAcks.clear(); + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + } + } + + // Move this Push's subscriptions back onto its own connection. + void _leaveToInProcess() { + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + + // Identifies the connection this Push authenticates: one native host serves one. + String get _credentialKey { + try { + final (authMethod, credential) = _credential(); + return [ + _host, + _port, + client.config['project'] ?? '', + _resolvedClientId, + authMethod, + credential, + ].join('|'); + } catch (_) { + return ''; + } + } + + // This Push's subscriptions in the native plugin's format. + List> get _nativeEntries => [ + for (final entry in _subscriptions.entries) + { + 'id': entry.key, + 'topic': entry.value.filter, + 'background': entry.value.background, + 'title': entry.value.title, + 'retry': entry.value.retry, + }, + ]; + + // After an unsubscribe or update on Android: keep the native plugin hosting while any + // subscription, live (of any Push) or saved, wants background, else move the live ones back + // in-process. + Future _reconcileNative(PushNative native) async { + if (_subscriptions.isEmpty) { + // This Push has nothing left; saved subscriptions keep delivering in the background. + if (_nativeActive) { + await _leaveNative(native); + } + return; + } + final wanted = + {..._nativeHosts, this}.any((push) => push._backgroundWanted) || + await native.hasSaved(); + if (wanted) { + await _hostNative(); + return; + } + // Nothing wants background: every Push moves back to its own connection. + final hosts = _nativeHosts.toList(); + _nativeHosts.clear(); + for (final push in hosts) { + push._nativeActive = false; + } + await _enqueueNative(() => native.release()); + for (final push in {...hosts, this}) { + if (push._subscriptions.isNotEmpty) { + await push._ensureInProcessSubscribed(); + } + } + } + + // Stop hosting this Push natively; the others' subscriptions stay hosted. + Future _leaveNative(PushNative native) { + _nativeHosts.remove(this); + _nativeActive = false; + if (_nativeHosts.isNotEmpty) { + return _nativeHosts.first._hostNative(); + } + return _enqueueNative(() => native.release()); + } + + // Relocate the connection into the background isolate and sync it with the current topic + // union and per-subscription notification config. + Future _hostInIsolate() async { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + await _syncBackground(); + } + + // Listen for messages the background isolate relays back and forward them to every + // matching in-app callback (so callbacks still fire while the app is alive, background or + // not). Idempotent. + void _attachServiceListener() { + _serviceListener ??= FlutterBackgroundService() + .on(pushForegroundMessageEvent) + .listen((data) { + if (data == null) { + return; + } + final topic = data['topic'] as String? ?? ''; + final payload = Uint8List.fromList( + utf8.encode(data['payload'] as String? ?? ''), + ); + final message = PushMessage( + topic: topic, + payload: payload, + qos: data['qos'] as int? ?? 0, + ); + for (final sub in _subscriptions.values) { + if (_matches(sub.filter, topic)) { + sub.callback(message); + } + } + }); + // The isolate's own connection/subscribe errors, relayed as their message. + _serviceErrorListener ??= FlutterBackgroundService() + .on(pushForegroundErrorEvent) + .listen((data) { + _report( + AppwriteException( + data?['message'] as String? ?? 'Background push failed', + ), + ); + }); + } + + void _detachServiceListener() { + _serviceListener?.cancel(); + _serviceListener = null; + _serviceErrorListener?.cancel(); + _serviceErrorListener = null; + } + + bool get _backgroundWanted => _subscriptions.values.any((s) => s.background); + + // The union of every subscription's filter (the isolate hosts one connection for all). + List get _backgroundTopics => + _subscriptions.values.map((s) => s.filter).toSet().toList(); + + // filter -> notification title, for filters that have at least one background subscription + // (those are the only ones that post a notification, each with its own title). + Map get _notifyConfig { + final map = {}; + for (final sub in _subscriptions.values) { + if (sub.background) { + map[sub.filter] = sub.title ?? _defaultTitle; + } + } + return map; + } + + String get _defaultTitle => 'Appwrite'; + + // The broker subscription for a filter uses the highest QoS any subscription on it wants, + // so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. + MqttQos _effectiveQos(String filter) { + final reliable = _subscriptions.values.any( + (s) => s.filter == filter && s.retry, + ); + return reliable ? MqttQos.atLeastOnce : MqttQos.atMostOnce; + } + + // filter -> QoS (1 reliable / 0 not), handed to the isolate so it subscribes each topic + // at the right level. + Map get _qosConfig { + final map = {}; + for (final filter in _backgroundTopics) { + map[filter] = _effectiveQos(filter) == MqttQos.atLeastOnce ? 1 : 0; + } + return map; + } + + // Run a background config write after any already-queued one, so writes never interleave + // or reorder. The returned future carries this write's own result to its caller, while the + // chain itself never rejects (a failed write must not stall later ones). + Future _enqueueBackground(Future Function() op) { + final result = _backgroundSync.then((_) => op()); + _backgroundSync = result.then((_) {}, onError: (Object _) {}); + return result; + } + + // Sync the running/started isolate with the current topic union and notify config. + Future _syncBackground() => _enqueueBackground(() async { + // Skip if background was turned off after this was queued, so a stale write can't + // recreate the credential file after shutdown deleted it. + if (!_backgroundWanted) { + return; + } + await syncPushForeground( + client, + serviceTitle: _defaultTitle, + topics: _backgroundTopics, + notify: _notifyConfig, + qos: _qosConfig, + ); + }); + + // Enqueue the background stop after any pending config write, so the credential file is + // always deleted last — a write queued just before shutdown cannot recreate it afterwards. + void _enqueueStop() { + unawaited( + _enqueueBackground(() async { + // Skip if background is wanted again by the time this runs, so a stale stop can't + // tear down a live connection or delete a credential config that is still in use. + if (_backgroundWanted) { + return; + } + await stopPushForeground(); + }).catchError(_report), + ); + } + + // Ensure the correct host (in-process vs isolate) for whatever subscriptions remain, and + // sync it. Called after an unsubscribe/update may have flipped whether background is wanted. + void _reconcile() { + final native = _native; + if (native != null) { + unawaited(_reconcileNative(native).catchError(_report)); + return; + } + if (_subscriptions.isEmpty) { + return; + } + if (_backgroundWanted) { + if (_mqtt != null) { + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + } + _isolateActive = true; + _attachServiceListener(); + unawaited(_syncBackground().catchError(_report)); + } else { + if (_isolateActive) { + _isolateActive = false; + _detachServiceListener(); + _enqueueStop(); + } + unawaited(_ensureInProcessSubscribed().catchError(_report)); + } + } + + // Bring up the in-process connection and (re)register every filter — used when the last + // background subscription goes away and the connection relocates back in-process. Nobody + // awaits it, so a rejected SUBACK reaches onError through [_onSubscribeFail]. + Future _ensureInProcessSubscribed() async { + final mqtt = await _connect(); + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + + void _unsubscribeIds(List ids) { + // Filters whose removed sub was QoS 1: their effective QoS may now drop. + final maybeDowngrade = {}; + for (final id in ids) { + final entry = _subscriptions.remove(id); + if (entry != null && entry.retry) { + maybeDowngrade.add(entry.filter); + } + // Only unsubscribe the broker filter once its last local callback is gone. + final stillUsed = _subscriptions.values.any( + (s) => s.filter == entry?.filter, + ); + if (entry != null && !stillUsed && _mqtt != null) { + try { + _mqtt?.unsubscribeStringTopic(entry.filter); + } catch (e) { + _report(e); + } + } + } + if (_subscriptions.isEmpty) { + // The last live subscription is gone; on Android, saved ones keep delivering. + _teardown(); + _reconcile(); + return; + } + // A removed sub may have been the last background one (relocate in-process) or just + // change the isolate's topic/notify set (the isolate re-sync carries the new QoS map). + _reconcile(); + // In-process, a filter that lost its last QoS-1 sub but still has QoS-0 subs must be + // re-subscribed lower, or the broker keeps replaying to at-most-once subs. + if (!_backgroundWanted && !_nativeActive && _mqtt != null) { + for (final filter in maybeDowngrade) { + final stillUsed = _subscriptions.values.any((s) => s.filter == filter); + if (stillUsed && _effectiveQos(filter) == MqttQos.atMostOnce) { + try { + _mqtt?.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + MqttQos.atMostOnce, + ), + ]); + } catch (e) { + _report(e); + } + } + } + } + } + + void _updateIds( + List ids, { + bool? background, + String? title, + bool? retry, + }) { + for (final id in ids) { + final sub = _subscriptions[id]; + if (sub == null) { + continue; + } + if (background != null) { + sub.background = background; + } + if (title != null) { + sub.title = title; + } + if (retry != null) { + sub.retry = retry; + } + } + // reconcile re-subscribes (in-process) / re-syncs the isolate at the new effective QoS. + _reconcile(); + } + + /// Tear down the connection and drop all subscriptions. On Android, closing the last Push that + /// uses background delivery also stops it, including subscriptions saved by an earlier run: + /// call it on sign-out. While other Push instances still use it, it keeps delivering their + /// subscriptions and the saved ones. + @override + void close() { + _teardown(); + final native = _native; + if (native == null) { + return; + } + _nativeHosts.remove(this); + _nativeActive = false; + unawaited(_nativeListener?.cancel()); + _nativeListener = null; + if (_nativeHosts.isNotEmpty) { + final other = _nativeHosts.first; + unawaited(other._hostNative().catchError(other._report)); + return; + } + unawaited(_enqueueNative(() => native.stop()).catchError(_report)); + } + + // Close the in-process connection (and the isolate host) and drop the live subscriptions. + void _teardown() { + _livePushes.remove(this); + _mqtt?.disconnect(); + _mqtt = null; + _connecting = null; + _detachServiceListener(); + _subscriptions.clear(); + if (_isolateActive) { + _isolateActive = false; + _enqueueStop(); + } + } + + Future _connect() { + if ((_mqtt != null || _connecting != null) && + _connectedKey != _credentialKey) { + _dropConnection(); + _resubscribeOnConnect = _subscriptions.isNotEmpty; + } + final mqtt = _mqtt; + if (mqtt != null && + mqtt.connectionStatus?.state == MqttConnectionState.connected) { + return Future.value(mqtt); + } + var connecting = _connecting; + if (connecting == null) { + connecting = _open(); + _connecting = connecting; + // A failed open must not poison future attempts — clear the cached in-flight + // future so a later subscribe/publish can retry. + final pending = connecting; + unawaited( + pending.catchError((Object _) { + if (identical(_connecting, pending)) { + _connecting = null; + } + }), + ); + } + return connecting.then((_) => _mqtt!); + } + + // The credential set on the client (via Client.setJWT / setSession), as (method, credential). + (String, String) _credential() { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + if (jwt != null && jwt.isNotEmpty) { + return ('appwrite-jwt', jwt); + } + if (session != null && session.isNotEmpty) { + return ('appwrite-session', session); + } + throw AppwriteException( + 'No credential set on the client; call Client.setJWT() or Client.setSession() first.', + ); + } + + Future _open() async { + final (authMethod, credential) = _credential(); + _connectedKey = _credentialKey; + final epoch = _connectionEpoch; + + final project = client.config['project'] ?? ''; + // An empty client id makes the broker derive a stable id server-side (keyed on the + // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) + // overrides with an explicit id. Resolved once per instance (see [_resolvedClientId]) so a + // reconnect rebuild reuses the same id and resumes the same session. + // On Android the native plugin's per-user-and-install id is used when none was set, so this + // connection and the background one share the broker session. + final native = _native; + final clientId = + _resolvedClientId.isEmpty && native != null + ? await native.defaultClientId(authMethod, credential) + : _resolvedClientId; + // The subscriptions moved to the native host while this was waiting: its connection would + // share the host's client id and take over the broker session. + if (epoch != _connectionEpoch) { + throw const _Superseded(); + } + + final mqtt = MqttServerClient.withPort(_host, clientId, _port); + mqtt.keepAlivePeriod = _keepAliveSeconds; + // Re-register every subscription automatically after a dropped connection. + mqtt.autoReconnect = true; + mqtt.resubscribeOnAutoReconnect = true; + mqtt.onSubscribed = _onSubscribed; + mqtt.onSubscribeFail = _onSubscribeFail; + mqtt.onConnected = () => _onOpen?.call(); + final reconnects = _ReconnectWatch(mqtt, _report); + mqtt.onAutoReconnect = reconnects.attemptStarted; + mqtt.onAutoReconnected = reconnects.stop; + mqtt.onDisconnected = () { + reconnects.stop(); + // A DISCONNECT from the broker with an error reason code explains itself in its + // MQTT 5 Reason String. + final error = _brokerDisconnectError(mqtt); + if (error != null) { + _report(error); + } + _onClose?.call(); + }; + + if (_tls) { + mqtt.secure = true; + if (_tlsInsecure) { + mqtt.onBadCertificate = (dynamic certificate) => true; + } + } + + // Enhanced auth carried in the CONNECT properties, plus the project id as a + // user property — exactly like the Python and React Native clients. + final authData = typed.Uint8Buffer()..addAll(utf8.encode(credential)); + final connectMessage = MqttConnectMessage() + .withClientIdentifier(clientId) + .keepAliveFor(_keepAliveSeconds) + .withAuthenticationMethod(authMethod) + .withAuthenticationData(authData); + // Clean start is always off (never call startClean), so the broker keeps this client's + // session and can redeliver missed messages to QoS-1 subscriptions on reconnect. The + // replay window itself is the broker's concern — we set no session expiry. + connectMessage.addUserPropertyPair('projectId', project); + mqtt.connectionMessage = connectMessage; + + _mqtt = mqtt; + + final cancel = Completer(); + _openCancel = cancel; + final failure = await _connectOrFail(mqtt, cancel.future, (error) { + // Superseded by the native host, which closed this connection on purpose. + if (epoch != _connectionEpoch) { + return; + } + // Let go of the client first: it is still being wound down, and a close() from + // onError must not touch it. + if (identical(_mqtt, mqtt)) { + _mqtt = null; + } + _notify(error); + }); + if (epoch != _connectionEpoch) { + mqtt.disconnect(); + throw const _Superseded(); + } + if (failure != null) { + throw failure; + } + + // Attach the delivery listener only after CONNACK — the `updates` stream is not + // available until the connection is established. + mqtt.updates.listen(_onData); + + if (_resubscribeOnConnect) { + _resubscribeOnConnect = false; + for (final filter in _backgroundTopics) { + mqtt.subscribeWithSubscriptionList([ + MqttSubscription.withMaximumQos( + MqttSubscriptionTopic(filter), + _effectiveQos(filter), + ), + ]); + } + } + } + + void _onData(List> events) { + for (final received in events) { + final publish = received.payload; + if (publish is! MqttPublishMessage) { + continue; + } + final topic = received.topic ?? ''; + final bytes = publish.payload.message; + final payload = + bytes == null ? Uint8List(0) : Uint8List.fromList(bytes.toList()); + final message = PushMessage( + topic: topic, + payload: payload, + qos: publish.header?.qos.index ?? 0, + ); + for (final subscription in _subscriptions.values) { + if (_matches(subscription.filter, topic)) { + subscription.callback(message); + } + } + } + } + + Completer? _takeSubAck(String? topic) { + final queue = _subAcks[topic]; + if (queue == null || queue.isEmpty) { + return null; + } + final completer = queue.removeAt(0); + if (queue.isEmpty) { + _subAcks.remove(topic); + } + return completer; + } + + void _onSubscribed(MqttSubscription subscription) { + final completer = _takeSubAck(subscription.topic.rawTopic); + if (completer != null && !completer.isCompleted) { + completer.complete(); + } + } + + void _onSubscribeFail(MqttSubscription subscription) { + final topic = subscription.topic.rawTopic; + final completer = _takeSubAck(topic); + final error = AppwriteException('Failed to subscribe to $topic'); + if (completer != null && !completer.isCompleted) { + // The subscribe waiting on this SUBACK throws it (and reports it to onError). + completer.completeError(error); + } else { + // Nobody awaits this SUBSCRIBE (a resubscribe after reconnect, a QoS change or a + // relocation back in-process), so onError is the only place it can surface. + _report(error); + } + } +} + +/// Connect [mqtt]. Resolves to null once connected, or to the error the connect failed +/// with after handing it to [failed] and disconnecting [mqtt]: a refused CONNECT carries +/// the broker's MQTT 5 Reason String when it sent one. +/// +/// mqtt5_client alone would not finish here: after a refused CONNECT that carries enhanced +/// auth, its connect() keeps waiting for a successful CONNACK. So the connection status is +/// watched for the refusal as well, and the pending connect() is then let go. +Future _connectOrFail( + MqttClient mqtt, + Future cancelled, + void Function(Object error) failed, +) async { + final connecting = mqtt.connect(); + final refused = Completer(); + final watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (!refused.isCompleted && _refused(mqtt.connectionStatus)) { + refused.complete(); + } + }); + Object? failure; + try { + await Future.any([connecting, refused.future, cancelled]); + } catch (e) { + failure = e; + } finally { + watch.cancel(); + } + final status = mqtt.connectionStatus; + if (failure == null && status?.state == MqttConnectionState.connected) { + return null; + } + final error = AppwriteException( + status != null && _refused(status) + ? _refusalMessage(status) + : failure?.toString() ?? 'MQTT connection failed (${status?.state})', + ); + failed(error); + // Fail the caller now; winding down the library's pending connect() happens after. + unawaited(_teardown(mqtt, connecting, refused.isCompleted ? status : null)); + return error; +} + +/// Tear down a client whose connect failed. After a refusal [refusedStatus] is its status: +/// connect() only stops waiting once the status reads connected, so mark it so until +/// connect() returns, then disconnected again. +Future _teardown( + MqttClient mqtt, + Future connecting, + MqttConnectionStatus? refusedStatus, +) async { + if (refusedStatus != null) { + refusedStatus.state = MqttConnectionState.connected; + try { + await connecting.timeout(const Duration(seconds: 10)); + } catch (_) { + // The refusal is the error; how connect() ends no longer matters. + } + refusedStatus.state = MqttConnectionState.disconnected; + } + try { + mqtt.disconnect(); + } catch (_) { + // Already torn down; the connect failure is the error. + } +} + +/// Whether [status] holds a CONNACK the broker refused the connection with. +bool _refused(MqttConnectionStatus? status) { + final code = status?.reasonCode; + return status != null && + status.state != MqttConnectionState.connected && + code != null && + code != MqttConnectReasonCode.notSet && + code != MqttConnectReasonCode.success; +} + +/// The broker's Reason String for a refused CONNECT, or a message naming the reason code. +String _refusalMessage(MqttConnectionStatus status) { + final reason = status.reasonString; + return reason != null && reason.isNotEmpty + ? reason + : 'MQTT authentication failed (CONNACK reason ${status.reasonCode})'; +} + +/// The error for a DISCONNECT the broker sent with an error reason code: its MQTT 5 Reason +/// String when present, else a message naming the reason code. Null for any other close. +AppwriteException? _brokerDisconnectError(MqttClient mqtt) { + final status = mqtt.connectionStatus; + if (status == null || + status.disconnectionOrigin != MqttDisconnectionOrigin.brokerSolicited) { + return null; + } + final disconnect = status.disconnectMessage; + final code = disconnect.reasonCode; + if (code == null || + code == MqttDisconnectReasonCode.notSet || + code == MqttDisconnectReasonCode.normalDisconnection) { + return null; + } + final reason = disconnect.reasonString; + return AppwriteException( + reason != null && reason.isNotEmpty + ? reason + : 'Disconnected by the broker (reason ${MqttDisconnectReasonCodeSupport.mqttDisconnectReasonCode.asInt(code)})', + ); +} + +/// Reports failed automatic reconnects, which mqtt5_client retries internally without +/// throwing: a refused CONNECT (with the broker's Reason String) as soon as its CONNACK +/// arrives, any other failure when the next attempt starts. +class _ReconnectWatch { + final MqttClient _mqtt; + final void Function(Object error) _report; + Timer? _timer; + bool _attempting = false; + bool _attemptReported = false; + + _ReconnectWatch(this._mqtt, this._report); + + void attemptStarted() { + if (_attempting && !_attemptReported) { + _report(AppwriteException('Push reconnect attempt failed')); + } + _attempting = true; + _attemptReported = false; + // Forget the last CONNACK so an earlier refusal is not reported for this attempt. + _mqtt.connectionStatus?.reasonCode = MqttConnectReasonCode.notSet; + _timer ??= Timer.periodic(const Duration(milliseconds: 50), (_) { + final status = _mqtt.connectionStatus; + if (_attempting && !_attemptReported && _refused(status)) { + _attemptReported = true; + _report(AppwriteException(_refusalMessage(status!))); + } + }); + } + + void stop() { + _attempting = false; + _timer?.cancel(); + _timer = null; + } +} + +/// A hex id, uuid4-like enough for a client-generated subId / client id suffix. +String _randomId() { + final random = Random(); + final buffer = StringBuffer(); + for (var i = 0; i < 32; i++) { + buffer.write(random.nextInt(16).toRadixString(16)); + } + return buffer.toString(); +} + +/// MQTT topic-filter match with '+' (single level) and '#' (multi level). +bool _matches(String filter, String topic) { + final filterParts = filter.split('/'); + final topicParts = topic.split('/'); + for (var i = 0; i < filterParts.length; i++) { + final part = filterParts[i]; + if (part == '#') { + return true; + } + if (i >= topicParts.length) { + return false; + } + if (part != '+' && part != topicParts[i]) { + return false; + } + } + return filterParts.length == topicParts.length; +} + +/// Resolve [Push.subscribe]'s `topics`: a String, Topic or ResolvedTopic, or a List of +/// them, or null for the signed-in user's own `users/` topic. +List _topicList(Client client, Object? topics) { + if (topics == null) { + return [_userTopic(client)]; + } + // A topic is a String or a Topic / ResolvedTopic builder (via toString()). + return topics is List + ? topics.map((topic) => topic.toString()).toList() + : [topics.toString()]; +} + +/// The signed-in user's own topic, `users/`, read off the client's +/// credential (JWT first, then session) without a network call. +String _userTopic(Client client) { + final jwt = client.config['jwt'] ?? client.config['jWT']; + final session = client.config['session']; + // The credential the connection authenticates with: the JWT when one is set (never the + // session, which could belong to a different user), else the session. + final userId = + (jwt != null && jwt.isNotEmpty) + ? _userIdFromJwt(jwt) + : _userIdFromSession(session); + if (userId == null) { + throw AppwriteException( + 'subscribe() without a topic needs a signed-in user: set a JWT or session on the client', + ); + } + return 'users/$userId'; +} + +/// The `userId` claim of a JWT's payload, or null when it has none. +String? _userIdFromJwt(String? jwt) { + final parts = jwt?.split('.') ?? const []; + if (parts.length < 2) { + return null; + } + return _stringField(parts[1], 'userId'); +} + +/// The user id inside a session secret, which is base64 of JSON +/// `{"id": , "secret": ...}`, or null when it is not such a secret. +String? _userIdFromSession(String? session) { + if (session == null || session.isEmpty) { + return null; + } + return _stringField(session, 'id'); +} + +/// Decode base64 (standard or url-safe) JSON and read a non-empty string [key]. +String? _stringField(String encoded, String key) { + try { + final json = jsonDecode( + utf8.decode(base64.decode(base64.normalize(encoded))), + ); + final value = json is Map ? json[key] : null; + return value is String && value.isNotEmpty ? value : null; + } catch (_) { + return null; + } +} + +// Reported to a Push whose background delivery stopped because a Push with another credential +// took over the native host, which carries one connection and so serves one credential. +const String _backgroundDisplaced = + 'Background delivery stopped: a Push with another credential started background delivery, ' + 'and the device hosts one. These subscriptions still deliver while the app runs.'; + +// An in-process connect superseded by moving the subscriptions to the native host, or by a +// connect with another credential. +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/mqtt_message.dart b/lib/src/mqtt_message.dart new file mode 100644 index 00000000..9faa825a --- /dev/null +++ b/lib/src/mqtt_message.dart @@ -0,0 +1,24 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// A message delivered on a subscribed topic — the MQTT push analog of a +/// realtime event. +class PushMessage { + /// The topic the message was published to. + final String topic; + + /// The raw message payload. + final Uint8List payload; + + /// The MQTT quality of service the message was delivered with. + final int qos; + + const PushMessage({ + required this.topic, + required this.payload, + required this.qos, + }); + + /// The payload decoded as UTF-8 text, as it was sent. + String get data => utf8.decode(payload); +} diff --git a/lib/src/mqtt_native.dart b/lib/src/mqtt_native.dart new file mode 100644 index 00000000..11509936 --- /dev/null +++ b/lib/src/mqtt_native.dart @@ -0,0 +1,128 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// A message the native Android plugin delivers for a hosted subscription. +class NativePushMessage { + final String id; + final String topic; + final Uint8List payload; + final int qos; + + /// Passed to [PushNative.ack] once the callback has run; the broker's PUBACK waits for it. + final String ackToken; + + NativePushMessage(this.id, this.topic, this.payload, this.qos, this.ackToken); +} + +/// The SDK's native Android plugin (see android/), which hosts background delivery on the same +/// core as the Appwrite Android SDK: saved subscriptions, scheduled wake-ups after +/// the app is killed, reboot resume, notifications and foreground mode. +class PushNative { + static const String _methodChannel = 'appwrite.push'; + static const String _eventChannel = 'appwrite.push/events'; + static final PushNative _plugin = PushNative._( + const MethodChannel(_methodChannel), + const EventChannel(_eventChannel), + ); + + final MethodChannel _methods; + final EventChannel _events; + Stream>? _stream; + + PushNative._(this._methods, this._events); + + /// The plugin's channels on [messenger] instead of the engine's, for tests that stand in for + /// the plugin. + @visibleForTesting + PushNative.forMessenger(BinaryMessenger messenger) + : _methods = MethodChannel( + _methodChannel, + const StandardMethodCodec(), + messenger, + ), + _events = EventChannel( + _eventChannel, + const StandardMethodCodec(), + messenger, + ); + + /// Used instead of the plugin by [Push] instances created while it is set, in tests. + @visibleForTesting + static PushNative? debugInstance; + + /// The plugin on Android, else null. + static PushNative? get instance => + debugInstance ?? (Platform.isAndroid ? _plugin : null); + + /// Host [subscriptionsJson] on the background connection described by [configJson]. Completes + /// once the connection is up and every filter is subscribed, or throws why not. + Future host(String configJson, String subscriptionsJson) => + _methods.invokeMethod('host', { + 'config': configJson, + 'subscriptions': subscriptionsJson, + }); + + /// Acknowledge a message once its callback has run. + Future ack(String token) => + _methods.invokeMethod('ack', {'token': token}); + + /// Stop hosting the live subscriptions, keeping the ones saved by an earlier run. + Future release() => _methods.invokeMethod('release'); + + /// Stop background delivery and forget every saved subscription. + Future stop() => _methods.invokeMethod('stop'); + + /// Run background delivery in a foreground service; saved across restarts. + Future setForeground(bool enabled) => + _methods.invokeMethod('setForeground', {'enabled': enabled}); + + /// Whether an earlier run saved background subscriptions that are still delivered. + Future hasSaved() async => + await _methods.invokeMethod('hasSaved') ?? false; + + /// Resume saved background delivery now instead of at the next scheduled run. + Future resume() => _methods.invokeMethod('resume'); + + /// Record whether onError is registered; returns a refusal kept while it was not, once. + Future setErrorCallback(bool registered) => _methods + .invokeMethod('setErrorCallback', {'registered': registered}); + + /// The default client id for a credential, so a foreground connection shares its session. + Future defaultClientId(String authMethod, String credential) async => + await _methods.invokeMethod('defaultClientId', { + 'authMethod': authMethod, + 'credential': credential, + }) ?? + ''; + + /// Listen to the plugin's messages and errors. + StreamSubscription> listen({ + required void Function(NativePushMessage message) onMessage, + required void Function(String message) onError, + }) { + final stream = + _stream ??= + _events + .receiveBroadcastStream() + .map((event) => event as Map) + .asBroadcastStream(); + return stream.listen((event) { + if (event['type'] == 'message') { + onMessage( + NativePushMessage( + event['id'] as String, + event['topic'] as String, + event['payload'] as Uint8List, + event['qos'] as int, + event['ackToken'] as String, + ), + ); + } else if (event['type'] == 'error') { + onError(event['message'] as String? ?? 'Background push failed'); + } + }); + } +} diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index a0f4193a..e56b7ddd 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -25,10 +25,12 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { final jwt = client.config['jwt']; if (jwt != null && jwt.isNotEmpty) { - uri = uri.replace(queryParameters: { - ...uri.queryParameters, - 'jwt': jwt, - }); + uri = uri.replace( + queryParameters: { + ...uri.queryParameters, + 'jwt': jwt, + }, + ); } return HtmlWebSocketChannel.connect(uri); diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 0ed367a6..ab1c3b42 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -37,9 +37,11 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { headers['x-appwrite-jwt'] = jwt; } - final websok = IOWebSocketChannel((client as ClientIO).selfSigned - ? await _connectForSelfSignedCert(uri, headers) - : await WebSocket.connect(uri.toString(), headers: headers)); + final websok = IOWebSocketChannel( + (client as ClientIO).selfSigned + ? await _connectForSelfSignedCert(uri, headers) + : await WebSocket.connect(uri.toString(), headers: headers), + ); return websok; } @@ -73,13 +75,18 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { // https://github.com/jonataslaw/getsocket/blob/f25b3a264d8cc6f82458c949b86d286cd0343792/lib/src/io.dart#L104 // and from official dart sdk websocket_impl.dart connect method Future _connectForSelfSignedCert( - Uri uri, Map headers) async { + Uri uri, + Map headers, + ) async { try { var r = Random(); var key = base64.encode(List.generate(16, (_) => r.nextInt(255))); var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = - (X509Certificate cert, String host, int port) { + client.badCertificateCallback = ( + X509Certificate cert, + String host, + int port, + ) { return true; }; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index ee4c4c30..e1a32db8 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -100,74 +100,80 @@ mixin RealtimeMixin { _websok = await getWebSocket(uri); } _retries = 0; - _websocketSubscription = _websok?.stream.listen((response) { - final data = RealtimeResponse.fromJson(response); - switch (data.type) { - case 'error': - handleError(data); - break; - case 'connected': - final message = RealtimeResponseConnected.fromMap(data.data); - - if (message.user.isEmpty) { - // send fallback cookie if exists - final cookie = getFallbackCookie?.call(); - if (cookie != null) { - _websok?.sink.add(jsonEncode({ - "type": "authentication", - "data": { - "session": cookie, - }, - })); + _websocketSubscription = _websok?.stream.listen( + (response) { + final data = RealtimeResponse.fromJson(response); + switch (data.type) { + case 'error': + handleError(data); + break; + case 'connected': + final message = RealtimeResponseConnected.fromMap(data.data); + + if (message.user.isEmpty) { + // send fallback cookie if exists + final cookie = getFallbackCookie?.call(); + if (cookie != null) { + _websok?.sink.add( + jsonEncode({ + "type": "authentication", + "data": { + "session": cookie, + }, + }), + ); + } + } + for (var entry in _subscriptions.entries) { + _pendingSubscribes[entry.key] = { + 'subscriptionId': entry.key, + 'channels': entry.value.channels, + 'queries': entry.value.queries, + }; } - } - for (var entry in _subscriptions.entries) { - _pendingSubscribes[entry.key] = { - 'subscriptionId': entry.key, - 'channels': entry.value.channels, - 'queries': entry.value.queries, - }; - } - _appConnected = true; - _sendPendingSubscribes(); - _flushPendingPresence(); - _startHeartbeat(); // Start heartbeat after successful connection - break; - case 'pong': - break; - case 'event': - final messageData = data.data as Map; - final message = RealtimeMessage.fromMap(messageData); - final subscriptions = - (messageData['subscriptions'] as List?) - ?.map((x) => x.toString()) - .toList() ?? - []; - - if (subscriptions.isEmpty) { + _appConnected = true; + _sendPendingSubscribes(); + _flushPendingPresence(); + _startHeartbeat(); // Start heartbeat after successful connection + break; + case 'pong': break; - } + case 'event': + final messageData = data.data as Map; + final message = RealtimeMessage.fromMap(messageData); + final subscriptions = + (messageData['subscriptions'] as List?) + ?.map((x) => x.toString()) + .toList() ?? + []; + + if (subscriptions.isEmpty) { + break; + } - for (var subscriptionId in subscriptions) { - final subscription = _subscriptions[subscriptionId]; - if (subscription != null) { - subscription.controller.add(message); + for (var subscriptionId in subscriptions) { + final subscription = _subscriptions[subscriptionId]; + if (subscription != null) { + subscription.controller.add(message); + } } - } - break; - } - }, onDone: () { - _appConnected = false; - _stopHeartbeat(); - _retry(); - }, onError: (err, stack) { - _appConnected = false; - _stopHeartbeat(); - for (var subscription in _subscriptions.values) { - subscription.controller.addError(err, stack); - } - _retry(); - }); + break; + } + }, + onDone: () { + _appConnected = false; + _stopHeartbeat(); + _retry(); + }, + onError: (err, stack) { + _appConnected = false; + _stopHeartbeat(); + for (var subscription in _subscriptions.values) { + subscription.controller.addError(err, stack); + } + _retry(); + }, + ); } catch (e) { if (e is AppwriteException) { rethrow; @@ -197,27 +203,30 @@ mixin RealtimeMixin { return _retries < 5 ? 1 : _retries < 15 - ? 5 - : _retries < 100 - ? 10 - : 60; + ? 5 + : _retries < 100 + ? 10 + : 60; } Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( - "Please set endPointRealtime to connect to realtime server"); + "Please set endPointRealtime to connect to realtime server", + ); } var uri = Uri.parse(client.endPointRealtime!); var queryParams = "project=${Uri.encodeComponent(client.config['project']!)}"; - final portPart = (uri.hasPort && uri.port != 80 && uri.port != 443) - ? ':${uri.port}' - : ''; + final portPart = + (uri.hasPort && uri.port != 80 && uri.port != 443) + ? ':${uri.port}' + : ''; return Uri.parse( - "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams"); + "${uri.scheme}://${uri.host}$portPart${uri.path}/realtime?$queryParams", + ); } void _sendUnsubscribeMessage(List subscriptionIds) { @@ -227,10 +236,12 @@ mixin RealtimeMixin { if (_websok == null || _websok?.closeCode != null) { return; } - _websok!.sink.add(jsonEncode({ - 'type': 'unsubscribe', - 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'unsubscribe', + 'data': subscriptionIds.map((id) => {'subscriptionId': id}).toList(), + }), + ); } String _generateUniqueSubscriptionId() { @@ -292,10 +303,12 @@ mixin RealtimeMixin { final rows = _pendingSubscribes.values.toList(); _pendingSubscribes.clear(); - _websok!.sink.add(jsonEncode({ - 'type': 'subscribe', - 'data': rows, - })); + _websok!.sink.add( + jsonEncode({ + 'type': 'subscribe', + 'data': rows, + }), + ); } void _flushPendingPresence() { @@ -312,8 +325,10 @@ mixin RealtimeMixin { return channel is String ? channel : channel.toString(); } - RealtimeSubscription subscribeTo(List channels, - [List queries = const []]) { + RealtimeSubscription subscribeTo( + List channels, [ + List queries = const [], + ]) { StreamController controller = StreamController.broadcast(); final channelStrings = channels.map((ch) => _channelToString(ch)).toList().cast(); @@ -383,7 +398,9 @@ mixin RealtimeMixin { void handleError(RealtimeResponse response) { if (response.data['code'] == status.policyViolation) { final error = AppwriteException( - response.data["message"], response.data["code"]); + response.data["message"], + response.data["code"], + ); for (var subscription in _subscriptions.values) { subscription.controller.addError(error); } diff --git a/lib/src/realtime_stub.dart b/lib/src/realtime_stub.dart index 3aab4e03..631afe31 100644 --- a/lib/src/realtime_stub.dart +++ b/lib/src/realtime_stub.dart @@ -2,6 +2,7 @@ import 'realtime_base.dart'; import 'client.dart'; /// Implemented in `realtime_browser.dart` and `realtime_io.dart`. -RealtimeBase createRealtime(Client client) => throw UnsupportedError( +RealtimeBase createRealtime(Client client) => + throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.', ); diff --git a/lib/src/realtime_subscription.dart b/lib/src/realtime_subscription.dart index e572b519..6461e344 100644 --- a/lib/src/realtime_subscription.dart +++ b/lib/src/realtime_subscription.dart @@ -21,7 +21,7 @@ class RealtimeSubscription { /// Replace the channels and/or queries on this subscription without recreating it. final Future Function({List? channels, List? queries}) - update; + update; /// Alias of [unsubscribe] that also closes the socket when this was the last active /// subscription. Prefer [unsubscribe] plus [Realtime.disconnect] for explicit control. diff --git a/lib/topic.dart b/lib/topic.dart new file mode 100644 index 00000000..e3c43a55 --- /dev/null +++ b/lib/topic.dart @@ -0,0 +1,85 @@ +part of 'appwrite.dart'; + +/// Helper to build MQTT topics for `Push`, level by level. +/// +/// ```dart +/// Topic.path(['user', userId, 'notification']); // "user/123/notification" +/// Topic.path(['user']).any().path(['notification']); // "user/+/notification" +/// Topic.path(['org']).any().path(['logs']).all(); // "org/+/logs/#" +/// ``` +/// +/// `any()` matches exactly one level and `all()` everything below, at any depth +/// (including the parent itself). `all()` ends the topic, so it returns a +/// [ResolvedTopic]. +class Topic { + final List _levels; + + Topic._(this._levels); + + /// Start a topic with the given levels, e.g. `Topic.path(['user', userId])`. + static Topic path(List levels) => Topic._(_topicLevelsOf(levels)); + + /// Start a topic with a single-level wildcard (`+`). + static Topic any() => Topic._(const ['+']); + + /// The multi-level wildcard alone (`#`): matches every topic. + static ResolvedTopic all() => ResolvedTopic._(const ['#']); + + @override + String toString() => _levels.join('/'); +} + +/// Appends levels to a [Topic]: `Topic.path(['user']).any().path(['notification'])`. +extension TopicLevels on Topic { + /// Append the given levels. + Topic path(List levels) => + Topic._([..._levels, ..._topicLevelsOf(levels)]); + + /// Append a single-level wildcard (`+`): matches exactly one level. + Topic any() => Topic._([..._levels, '+']); + + /// Append the multi-level wildcard (`#`) and end the topic. + ResolvedTopic all() => ResolvedTopic._([..._levels, '#']); +} + +/// A topic ended by `all()`: nothing can be appended after the `#` wildcard. +class ResolvedTopic { + final List _levels; + + ResolvedTopic._(this._levels); + + @override + String toString() => _levels.join('/'); +} + +/// Validate the levels passed to `path()`: a non-empty list of non-empty +/// strings, none holding the level separator `/` or the wildcards `+` and `#` +/// (use `any()` and `all()` for those). +List _topicLevelsOf(List levels) { + if (levels.isEmpty) { + throw ArgumentError('path() needs at least one level'); + } + for (var index = 0; index < levels.length; index++) { + final level = levels[index]; + if (level.isEmpty) { + throw ArgumentError('empty level at index $index'); + } + if (level.contains('/')) { + final parts = level.split('/').map((part) => "'$part'").join(', '); + throw ArgumentError('"$level" contains "/", split it: path([$parts])'); + } + if (level == '+') { + throw ArgumentError('"+" is reserved, use any()'); + } + if (level.contains('+')) { + throw ArgumentError('"$level" contains "+", use any() for wildcards'); + } + if (level == '#') { + throw ArgumentError('"#" is reserved, use all()'); + } + if (level.contains('#')) { + throw ArgumentError('"$level" contains "#", use all() for wildcards'); + } + } + return List.unmodifiable(levels); +} diff --git a/pubspec.yaml b/pubspec.yaml index b04bee5a..21f452d7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 27.0.0 +version: 27.1.0-rc.0 description: Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -23,8 +23,12 @@ dependencies: device_info_plus: '>=11.5.0 <14.0.0' flutter_web_auth_2: ^5.0.0 http: '>=0.13.6 <2.0.0' + mqtt5_client: ^4.12.0 + flutter_background_service: ^5.0.5 + flutter_local_notifications: ^18.0.1 package_info_plus: '>=8.0.2 <11.0.0' path_provider: ^2.1.4 + typed_data: ^1.3.2 web_socket_channel: ^3.0.1 web: ^1.0.0 @@ -34,3 +38,12 @@ dev_dependencies: flutter_test: sdk: flutter mockito: ^5.4.4 + +# Android: the native half of Push, which runs background delivery on the same core as the +# Appwrite Android SDK. Other platforms need no native code. +flutter: + plugin: + platforms: + android: + package: io.appwrite.flutter + pluginClass: AppwritePushPlugin diff --git a/test/channel_test.dart b/test/channel_test.dart index 9e0e11d3..5ed52b81 100644 --- a/test/channel_test.dart +++ b/test/channel_test.dart @@ -8,28 +8,28 @@ void main() { }); test('returns database channel with specific IDs', () { - expect(Channel.database('db1').collection('col1').document().toString(), - 'databases.db1.collections.col1.documents'); + expect( + Channel.database('db1').collection('col1').document().toString(), + 'databases.db1.collections.col1.documents', + ); }); test('returns database channel with action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .create() - .toString(), - 'databases.db1.collections.col1.documents.doc1.create'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').create().toString(), + 'databases.db1.collections.col1.documents.doc1.create', + ); }); test('returns database channel with upsert action', () { expect( - Channel.database('db1') - .collection('col1') - .document('doc1') - .upsert() - .toString(), - 'databases.db1.collections.col1.documents.doc1.upsert'); + Channel.database( + 'db1', + ).collection('col1').document('doc1').upsert().toString(), + 'databases.db1.collections.col1.documents.doc1.upsert', + ); }); }); @@ -39,18 +39,17 @@ void main() { }); test('returns tablesdb channel with specific IDs', () { - expect(Channel.tablesdb('db1').table('table1').row().toString(), - 'tablesdb.db1.tables.table1.rows'); + expect( + Channel.tablesdb('db1').table('table1').row().toString(), + 'tablesdb.db1.tables.table1.rows', + ); }); test('returns tablesdb channel with action', () { expect( - Channel.tablesdb('db1') - .table('table1') - .row('row1') - .update() - .toString(), - 'tablesdb.db1.tables.table1.rows.row1.update'); + Channel.tablesdb('db1').table('table1').row('row1').update().toString(), + 'tablesdb.db1.tables.table1.rows.row1.update', + ); }); }); @@ -67,12 +66,16 @@ void main() { test('returns buckets channel with specific IDs', () { expect( - Channel.bucket('bucket1').file().toString(), 'buckets.bucket1.files'); + Channel.bucket('bucket1').file().toString(), + 'buckets.bucket1.files', + ); }); test('returns buckets channel with action', () { - expect(Channel.bucket('bucket1').file('file1').delete().toString(), - 'buckets.bucket1.files.file1.delete'); + expect( + Channel.bucket('bucket1').file('file1').delete().toString(), + 'buckets.bucket1.files.file1.delete', + ); }); }); @@ -116,13 +119,17 @@ void main() { }); test('returns memberships channel with specific membership ID', () { - expect(Channel.membership('membership1').toString(), - 'memberships.membership1'); + expect( + Channel.membership('membership1').toString(), + 'memberships.membership1', + ); }); test('returns memberships channel with action', () { - expect(Channel.membership('membership1').update().toString(), - 'memberships.membership1.update'); + expect( + Channel.membership('membership1').update().toString(), + 'memberships.membership1.update', + ); }); }); @@ -140,23 +147,31 @@ void main() { }); test('returns presence channel with create action', () { - expect(Channel.presence('presence1').create().toString(), - 'presences.presence1.create'); + expect( + Channel.presence('presence1').create().toString(), + 'presences.presence1.create', + ); }); test('returns presence channel with upsert action', () { - expect(Channel.presence('presence1').upsert().toString(), - 'presences.presence1.upsert'); + expect( + Channel.presence('presence1').upsert().toString(), + 'presences.presence1.upsert', + ); }); test('returns presence channel with update action', () { - expect(Channel.presence('presence1').update().toString(), - 'presences.presence1.update'); + expect( + Channel.presence('presence1').update().toString(), + 'presences.presence1.update', + ); }); test('returns presence channel with delete action', () { - expect(Channel.presence('presence1').delete().toString(), - 'presences.presence1.delete'); + expect( + Channel.presence('presence1').delete().toString(), + 'presences.presence1.delete', + ); }); }); } diff --git a/test/services/account_test.dart b/test/services/account_test.dart index ef1bc31b..25047e20 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/apps_test.dart b/test/services/apps_test.dart new file mode 100644 index 00000000..a60f0d67 --- /dev/null +++ b/test/services/apps_test.dart @@ -0,0 +1,524 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Apps test', () { + late MockClient client; + late Apps apps; + + setUp(() { + client = MockClient(); + apps = Apps(client); + }); + + test('test method list()', () async { + final Map data = { + 'total': 5, + 'apps': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.list(); + expect(response, isA()); + }); + + test('test method create()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.create( + appId: "", + name: "", + redirectUris: [], + ); + expect(response, isA()); + }); + + test('test method listInstallationScopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallationScopes(); + expect(response, isA()); + }); + + test('test method listOAuth2Scopes()', () async { + final Map data = { + 'total': 5, + 'scopes': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listOAuth2Scopes(); + expect(response, isA()); + }); + + test('test method get()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.get( + appId: "", + ); + expect(response, isA()); + }); + + test('test method update()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.put), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.update( + appId: "", + name: "", + ); + expect(response, isA()); + }); + + test('test method delete()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.delete( + appId: "", + ); + }); + + test('test method listInstallations()', () async { + final Map data = { + 'total': 5, + 'installations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listInstallations( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getInstallation()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'teamId': "5e5ea5c16897e", + 'scopes': [], + 'authorizationDetails': [], + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getInstallation( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method deleteInstallation()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteInstallation( + appId: "", + installationId: "", + ); + }); + + test('test method createInstallationToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createInstallationToken( + appId: "", + installationId: "", + ); + expect(response, isA()); + }); + + test('test method listKeys()', () async { + final Map data = { + 'total': 5, + 'keys': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listKeys( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createKey( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getKey()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getKey( + appId: "", + keyId: "", + ); + expect(response, isA()); + }); + + test('test method deleteKey()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteKey( + appId: "", + keyId: "", + ); + }); + + test('test method listSecrets()', () async { + final Map data = { + 'total': 5, + 'secrets': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.listSecrets( + appId: "", + ); + expect(response, isA()); + }); + + test('test method createSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.createSecret( + appId: "", + ); + expect(response, isA()); + }); + + test('test method getSecret()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'appId': "5e5ea5c16897e", + 'secret': "", + 'hint': "f5c6c7", + 'createdById': "5e5ea5c16897e", + 'createdByName': "Walter White", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.getSecret( + appId: "", + secretId: "", + ); + expect(response, isA()); + }); + + test('test method deleteSecret()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteSecret( + appId: "", + secretId: "", + ); + }); + + test('test method updateTeam()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "My Application", + 'description': "Connect your workspace to My Application.", + 'clientUri': "https://example.com", + 'logoUri': "https://example.com/logo.png", + 'privacyPolicyUrl': "https://example.com/privacy", + 'termsUrl': "https://example.com/terms", + 'contacts': [], + 'tagline': "Automate your workspace.", + 'tags': [], + 'labels': [], + 'images': [], + 'supportUrl': "https://example.com/support", + 'dataDeletionUrl': "https://example.com/data-deletion", + 'redirectUris': [], + 'postLogoutRedirectUris': [], + 'enabled': true, + 'type': "confidential", + 'deviceFlow': true, + 'teamId': "5e5ea5c16897e", + 'userId': "5e5ea5c16897e", + 'installationScopes': [], + 'installationRedirectUrl': "https://example.com/setup", + 'secrets': [], + }; + + when( + client.call(HttpMethod.patch), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.updateTeam( + appId: "", + teamId: "", + ); + expect(response, isA()); + }); + + test('test method deleteTokens()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await apps.deleteTokens( + appId: "", + ); + }); + }); +} diff --git a/test/services/avatars_test.dart b/test/services/avatars_test.dart index 835e2951..18c4d03d 100644 --- a/test/services/avatars_test.dart +++ b/test/services/avatars_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ @@ -152,6 +154,52 @@ void main() { expect(response, isA()); }); + test('test method updatePhoto()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'name': "John Doe", + 'registration': "2020-10-15T06:38:00.000+00:00", + 'status': true, + 'labels': [], + 'passwordUpdate': "2020-10-15T06:38:00.000+00:00", + 'email': "john@appwrite.io", + 'phone': "+4930901820", + 'emailVerification': true, + 'phoneVerification': true, + 'mfa': true, + 'prefs': {}, + 'targets': [], + 'accessedAt': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), + ), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.updatePhoto( + file: InputFile.fromPath(path: './image.png'), + ); + expect(response, isA()); + }); + + test('test method deletePhoto()', () async { + final data = ''; + + when( + client.call(HttpMethod.delete), + ).thenAnswer((_) async => Response(data: data)); + + final response = await avatars.deletePhoto(); + }); + test('test method getQR()', () async { final Uint8List data = Uint8List.fromList([]); diff --git a/test/services/databases_test.dart b/test/services/databases_test.dart index d92a7381..eb03954a 100644 --- a/test/services/databases_test.dart +++ b/test/services/databases_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/documents_db_test.dart b/test/services/documents_db_test.dart index 6e7d3a62..4312cced 100644 --- a/test/services/documents_db_test.dart +++ b/test/services/documents_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 75d34f13..93a7bc81 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/graphql_test.dart b/test/services/graphql_test.dart index 779767e3..3333a66e 100644 --- a/test/services/graphql_test.dart +++ b/test/services/graphql_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/locale_test.dart b/test/services/locale_test.dart index c9bb5236..77ee7ddd 100644 --- a/test/services/locale_test.dart +++ b/test/services/locale_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/messaging_test.dart b/test/services/messaging_test.dart index 823af01e..5bf1cbd3 100644 --- a/test/services/messaging_test.dart +++ b/test/services/messaging_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/oauth2_test.dart b/test/services/oauth2_test.dart new file mode 100644 index 00000000..41976a32 --- /dev/null +++ b/test/services/oauth2_test.dart @@ -0,0 +1,300 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:appwrite/models.dart' as models; +import 'package:appwrite/enums.dart' as enums; +import 'package:appwrite/src/enums.dart'; +import 'package:appwrite/src/response.dart'; +import 'dart:typed_data'; +import 'package:appwrite/appwrite.dart'; + +class MockClient extends Mock implements Client { + Map config = {'project': 'testproject'}; + String endPoint = 'https://localhost/v1'; + + @override + Future call( + HttpMethod? method, { + String path = '', + Map headers = const {}, + Map params = const {}, + ResponseType? responseType, + }) async { + return super.noSuchMethod( + Invocation.method(#call, [method]), + returnValue: Response(), + ); + } + + @override + Future webAuth(Uri? url, {String? callbackUrlScheme}) async { + return super.noSuchMethod( + Invocation.method(#webAuth, [url]), + returnValue: 'done', + ); + } + + @override + Future chunkedUpload({ + String? path, + Map? params, + String? paramName, + String? idParamName, + Map? headers, + Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, + }) async { + return super.noSuchMethod( + Invocation.method(#chunkedUpload, [ + path, + params, + paramName, + idParamName, + headers, + ]), + returnValue: Response(data: {}), + ); + } +} + +void main() { + group('Oauth2 test', () { + late MockClient client; + late Oauth2 oauth2; + + setUp(() { + client = MockClient(); + oauth2 = Oauth2(client); + }); + + test('test method approve()', () async { + final Map data = { + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.approve( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method authorize()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorize(); + expect(response, isA()); + }); + + test('test method authorizePost()', () async { + final Map data = { + 'grantId': "5e5ea5c16897e", + 'redirectUrl': "https://example.com/callback?code=abcde&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.authorizePost(); + expect(response, isA()); + }); + + test('test method createDeviceAuthorization()', () async { + final Map data = { + 'device_code': + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + 'user_code': "ABCD-EFGH", + 'verification_uri': "https://appwrite.io/oauth2/device", + 'verification_uri_complete': + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + 'expires_in': 900, + 'interval': 5, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createDeviceAuthorization(); + expect(response, isA()); + }); + + test('test method createGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createGrant( + userCode: "", + ); + expect(response, isA()); + }); + + test('test method getGrant()', () async { + final Map data = { + '\$id': "5e5ea5c16897e", + '\$createdAt': "2020-10-15T06:38:00.000+00:00", + '\$updatedAt': "2020-10-15T06:38:00.000+00:00", + 'userId': "5e5ea5c16897e", + 'appId': "5e5ea5c16897e", + 'scopes': [], + 'resources': [], + 'authorizationDetails': + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + 'prompt': "login", + 'redirectUri': "https://example.com/callback", + 'authTime': 1592981250, + 'expire': "2020-10-15T06:38:00.000+00:00", + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.getGrant( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method logout()', () async { + final data = ''; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logout(); + }); + + test('test method logoutPost()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.logoutPost(); + }); + + test('test method listOrganizations()', () async { + final Map data = { + 'total': 5, + 'organizations': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listOrganizations(); + expect(response, isA()); + }); + + test('test method createPAR()', () async { + final Map data = { + 'request_uri': "urn:appwrite:oauth2:request:5e5ea5c16897e", + 'expires_in': 600, + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createPAR( + clientId: "", + redirectUri: "https://example.com", + responseType: "code", + ); + expect(response, isA()); + }); + + test('test method listProjects()', () async { + final Map data = { + 'total': 5, + 'projects': [], + }; + + when( + client.call(HttpMethod.get), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.listProjects(); + expect(response, isA()); + }); + + test('test method reject()', () async { + final Map data = { + 'redirectUrl': + "https://example.com/callback?error=access_denied&state=fghij", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.reject( + grantId: "", + ); + expect(response, isA()); + }); + + test('test method revoke()', () async { + final data = ''; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.revoke( + token: "", + ); + }); + + test('test method createToken()', () async { + final Map data = { + 'access_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + 'token_type': "Bearer", + 'expires_in': 3600, + 'refresh_token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + 'scope': "openid email profile", + }; + + when( + client.call(HttpMethod.post), + ).thenAnswer((_) async => Response(data: data)); + + final response = await oauth2.createToken( + grantType: "", + ); + expect(response, isA()); + }); + }); +} diff --git a/test/services/organization_test.dart b/test/services/organization_test.dart index a6ea2c70..7354def0 100644 --- a/test/services/organization_test.dart +++ b/test/services/organization_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/presences_test.dart b/test/services/presences_test.dart index 9de09725..9f160e79 100644 --- a/test/services/presences_test.dart +++ b/test/services/presences_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/storage_test.dart b/test/services/storage_test.dart index 92d858ee..d1e6f09b 100644 --- a/test/services/storage_test.dart +++ b/test/services/storage_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/tables_db_test.dart b/test/services/tables_db_test.dart index 47f0eee8..90a55af7 100644 --- a/test/services/tables_db_test.dart +++ b/test/services/tables_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/teams_test.dart b/test/services/teams_test.dart index cafe8858..7c9f2faf 100644 --- a/test/services/teams_test.dart +++ b/test/services/teams_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/services/vectors_db_test.dart b/test/services/vectors_db_test.dart index 14660ed0..dc13e38d 100644 --- a/test/services/vectors_db_test.dart +++ b/test/services/vectors_db_test.dart @@ -41,6 +41,8 @@ class MockClient extends Mock implements Client { String? idParamName, Map? headers, Function(UploadProgress)? onProgress, + ResponseType? responseType, + HttpMethod method = HttpMethod.post, }) async { return super.noSuchMethod( Invocation.method(#chunkedUpload, [ diff --git a/test/src/input_file_test.dart b/test/src/input_file_test.dart index 3d301a85..bc1c08ae 100644 --- a/test/src/input_file_test.dart +++ b/test/src/input_file_test.dart @@ -7,22 +7,26 @@ void main() { test('throws exception when neither path nor bytes are provided', () { expect( () => InputFile(), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); test('throws exception when path and bytes are both null', () { expect( () => InputFile(path: null, bytes: null), - throwsA(isA().having( - (e) => e.message, - 'message', - 'One of `path` or `bytes` is required', - )), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'One of `path` or `bytes` is required', + ), + ), ); }); @@ -30,11 +34,40 @@ void main() { final inputFile = InputFile.fromPath(path: '/path/to/file'); expect(inputFile.path, '/path/to/file'); - expect(inputFile.filename, isNull); + expect(inputFile.filename, 'file'); expect(inputFile.contentType, isNull); expect(inputFile.bytes, isNull); }); + test('derives filename from path when none is given', () { + expect( + InputFile.fromPath(path: '/path/to/video.mp4').filename, + 'video.mp4', + reason: 'chunks of a file over 5MB are sent as bytes, and without a ' + 'filename the server rejects them as an empty file', + ); + expect(InputFile.fromPath(path: './relative/image.png').filename, + 'image.png'); + expect(InputFile.fromPath(path: 'video.mp4').filename, 'video.mp4'); + }); + + test('keeps an explicitly provided filename', () { + final inputFile = InputFile.fromPath( + path: '/path/to/video.mp4', + filename: 'renamed.mp4', + ); + + expect(inputFile.filename, 'renamed.mp4'); + }); + + test('derives filename from path on the deprecated constructor', () { + expect(InputFile(path: '/path/to/video.mp4').filename, 'video.mp4'); + }); + + test('leaves filename null when the path has no final segment', () { + expect(InputFile.fromPath(path: '/path/to/').filename, isNull); + }); + test('creates InputFile from bytes', () { final inputFile = InputFile.fromBytes( bytes: [1, 2, 3], diff --git a/test/src/models/account_test.dart b/test/src/models/account_test.dart new file mode 100644 index 00000000..9c4da2e1 --- /dev/null +++ b/test/src/models/account_test.dart @@ -0,0 +1,46 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Account', () { + test('model', () { + final model = Account( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "John Doe", + registration: "2020-10-15T06:38:00.000+00:00", + status: true, + labels: [], + passwordUpdate: "2020-10-15T06:38:00.000+00:00", + email: "john@appwrite.io", + phone: "+4930901820", + emailVerification: true, + phoneVerification: true, + mfa: true, + prefs: Preferences(data: {}), + targets: [], + accessedAt: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Account.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "John Doe"); + expect(result.registration, "2020-10-15T06:38:00.000+00:00"); + expect(result.status, true); + expect(result.labels, []); + expect(result.passwordUpdate, "2020-10-15T06:38:00.000+00:00"); + expect(result.email, "john@appwrite.io"); + expect(result.phone, "+4930901820"); + expect(result.emailVerification, true); + expect(result.phoneVerification, true); + expect(result.mfa, true); + expect(result.targets, []); + expect(result.accessedAt, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/app_key_list_test.dart b/test/src/models/app_key_list_test.dart new file mode 100644 index 00000000..556e98a1 --- /dev/null +++ b/test/src/models/app_key_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKeyList', () { + test('model', () { + final model = AppKeyList( + total: 5, + keys: [], + ); + + final map = model.toMap(); + final result = AppKeyList.fromMap(map); + + expect(result.total, 5); + expect(result.keys, []); + }); + }); +} diff --git a/test/src/models/app_key_test.dart b/test/src/models/app_key_test.dart new file mode 100644 index 00000000..a4aedc6a --- /dev/null +++ b/test/src/models/app_key_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppKey', () { + test('model', () { + final model = AppKey( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppKey.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_scope_list_test.dart b/test/src/models/app_scope_list_test.dart new file mode 100644 index 00000000..f14fe488 --- /dev/null +++ b/test/src/models/app_scope_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScopeList', () { + test('model', () { + final model = AppScopeList( + total: 5, + scopes: [], + ); + + final map = model.toMap(); + final result = AppScopeList.fromMap(map); + + expect(result.total, 5); + expect(result.scopes, []); + }); + }); +} diff --git a/test/src/models/app_scope_test.dart b/test/src/models/app_scope_test.dart new file mode 100644 index 00000000..edf43230 --- /dev/null +++ b/test/src/models/app_scope_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppScope', () { + test('model', () { + final model = AppScope( + value: "organization:organization.read", + description: "Access to read the organization", + type: "organization", + category: "Organization", + deprecated: true, + ); + + final map = model.toMap(); + final result = AppScope.fromMap(map); + + expect(result.value, "organization:organization.read"); + expect(result.description, "Access to read the organization"); + expect(result.type, "organization"); + expect(result.category, "Organization"); + expect(result.deprecated, true); + }); + }); +} diff --git a/test/src/models/app_secret_list_test.dart b/test/src/models/app_secret_list_test.dart new file mode 100644 index 00000000..7e77552a --- /dev/null +++ b/test/src/models/app_secret_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretList', () { + test('model', () { + final model = AppSecretList( + total: 5, + secrets: [], + ); + + final map = model.toMap(); + final result = AppSecretList.fromMap(map); + + expect(result.total, 5); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/app_secret_plaintext_test.dart b/test/src/models/app_secret_plaintext_test.dart new file mode 100644 index 00000000..801dfc74 --- /dev/null +++ b/test/src/models/app_secret_plaintext_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecretPlaintext', () { + test('model', () { + final model = AppSecretPlaintext( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecretPlaintext.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect( + result.secret, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_secret_test.dart b/test/src/models/app_secret_test.dart new file mode 100644 index 00000000..856e8c33 --- /dev/null +++ b/test/src/models/app_secret_test.dart @@ -0,0 +1,31 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppSecret', () { + test('model', () { + final model = AppSecret( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + appId: "5e5ea5c16897e", + secret: "", + hint: "f5c6c7", + createdById: "5e5ea5c16897e", + createdByName: "Walter White", + ); + + final map = model.toMap(); + final result = AppSecret.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.secret, ""); + expect(result.hint, "f5c6c7"); + expect(result.createdById, "5e5ea5c16897e"); + expect(result.createdByName, "Walter White"); + }); + }); +} diff --git a/test/src/models/app_test.dart b/test/src/models/app_test.dart new file mode 100644 index 00000000..a1cf013a --- /dev/null +++ b/test/src/models/app_test.dart @@ -0,0 +1,67 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('App', () { + test('model', () { + final model = App( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + name: "My Application", + description: "Connect your workspace to My Application.", + clientUri: "https://example.com", + logoUri: "https://example.com/logo.png", + privacyPolicyUrl: "https://example.com/privacy", + termsUrl: "https://example.com/terms", + contacts: [], + tagline: "Automate your workspace.", + tags: [], + labels: [], + images: [], + supportUrl: "https://example.com/support", + dataDeletionUrl: "https://example.com/data-deletion", + redirectUris: [], + postLogoutRedirectUris: [], + enabled: true, + type: "confidential", + deviceFlow: true, + teamId: "5e5ea5c16897e", + userId: "5e5ea5c16897e", + installationScopes: [], + installationRedirectUrl: "https://example.com/setup", + secrets: [], + ); + + final map = model.toMap(); + final result = App.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.name, "My Application"); + expect(result.description, "Connect your workspace to My Application."); + expect(result.clientUri, "https://example.com"); + expect(result.logoUri, "https://example.com/logo.png"); + expect(result.privacyPolicyUrl, "https://example.com/privacy"); + expect(result.termsUrl, "https://example.com/terms"); + expect(result.contacts, []); + expect(result.tagline, "Automate your workspace."); + expect(result.tags, []); + expect(result.labels, []); + expect(result.images, []); + expect(result.supportUrl, "https://example.com/support"); + expect(result.dataDeletionUrl, "https://example.com/data-deletion"); + expect(result.redirectUris, []); + expect(result.postLogoutRedirectUris, []); + expect(result.enabled, true); + expect(result.type, "confidential"); + expect(result.deviceFlow, true); + expect(result.teamId, "5e5ea5c16897e"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.installationScopes, []); + expect(result.installationRedirectUrl, "https://example.com/setup"); + expect(result.secrets, []); + }); + }); +} diff --git a/test/src/models/apps_list_test.dart b/test/src/models/apps_list_test.dart new file mode 100644 index 00000000..19150689 --- /dev/null +++ b/test/src/models/apps_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppsList', () { + test('model', () { + final model = AppsList( + total: 5, + apps: [], + ); + + final map = model.toMap(); + final result = AppsList.fromMap(map); + + expect(result.total, 5); + expect(result.apps, []); + }); + }); +} diff --git a/test/src/models/oauth2_approve_test.dart b/test/src/models/oauth2_approve_test.dart new file mode 100644 index 00000000..a045bfcf --- /dev/null +++ b/test/src/models/oauth2_approve_test.dart @@ -0,0 +1,20 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Approve', () { + test('model', () { + final model = Oauth2Approve( + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Approve.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_authorize_test.dart b/test/src/models/oauth2_authorize_test.dart new file mode 100644 index 00000000..f1546316 --- /dev/null +++ b/test/src/models/oauth2_authorize_test.dart @@ -0,0 +1,22 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Authorize', () { + test('model', () { + final model = Oauth2Authorize( + grantId: "5e5ea5c16897e", + redirectUrl: "https://example.com/callback?code=abcde&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Authorize.fromMap(map); + + expect(result.grantId, "5e5ea5c16897e"); + expect( + result.redirectUrl, + "https://example.com/callback?code=abcde&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_device_authorization_test.dart b/test/src/models/oauth2_device_authorization_test.dart new file mode 100644 index 00000000..d68181a5 --- /dev/null +++ b/test/src/models/oauth2_device_authorization_test.dart @@ -0,0 +1,35 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2DeviceAuthorization', () { + test('model', () { + final model = Oauth2DeviceAuthorization( + device_code: + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + user_code: "ABCD-EFGH", + verification_uri: "https://appwrite.io/oauth2/device", + verification_uri_complete: + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + expires_in: 900, + interval: 5, + ); + + final map = model.toMap(); + final result = Oauth2DeviceAuthorization.fromMap(map); + + expect( + result.device_code, + "5f3c8d2a1b9e4f7a6c8b2d1e9f4a7b3c5d8e1f2a9b4c7d6e3f5a8b1c4d7e2f9a", + ); + expect(result.user_code, "ABCD-EFGH"); + expect(result.verification_uri, "https://appwrite.io/oauth2/device"); + expect( + result.verification_uri_complete, + "https://appwrite.io/oauth2/device?user_code=ABCD-EFGH", + ); + expect(result.expires_in, 900); + expect(result.interval, 5); + }); + }); +} diff --git a/test/src/models/oauth2_grant_test.dart b/test/src/models/oauth2_grant_test.dart new file mode 100644 index 00000000..65a866a9 --- /dev/null +++ b/test/src/models/oauth2_grant_test.dart @@ -0,0 +1,43 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Grant', () { + test('model', () { + final model = Oauth2Grant( + $id: "5e5ea5c16897e", + $createdAt: "2020-10-15T06:38:00.000+00:00", + $updatedAt: "2020-10-15T06:38:00.000+00:00", + userId: "5e5ea5c16897e", + appId: "5e5ea5c16897e", + scopes: [], + resources: [], + authorizationDetails: + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + prompt: "login", + redirectUri: "https://example.com/callback", + authTime: 1592981250, + expire: "2020-10-15T06:38:00.000+00:00", + ); + + final map = model.toMap(); + final result = Oauth2Grant.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.$createdAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.$updatedAt, "2020-10-15T06:38:00.000+00:00"); + expect(result.userId, "5e5ea5c16897e"); + expect(result.appId, "5e5ea5c16897e"); + expect(result.scopes, []); + expect(result.resources, []); + expect( + result.authorizationDetails, + "[{\"type\":\"calendar\",\"identifier\":\"primary\",\"actions\":[\"read_events\",\"create_event\"]}]", + ); + expect(result.prompt, "login"); + expect(result.redirectUri, "https://example.com/callback"); + expect(result.authTime, 1592981250); + expect(result.expire, "2020-10-15T06:38:00.000+00:00"); + }); + }); +} diff --git a/test/src/models/oauth2_organization_list_test.dart b/test/src/models/oauth2_organization_list_test.dart new file mode 100644 index 00000000..e55d8efd --- /dev/null +++ b/test/src/models/oauth2_organization_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2OrganizationList', () { + test('model', () { + final model = Oauth2OrganizationList( + total: 5, + organizations: [], + ); + + final map = model.toMap(); + final result = Oauth2OrganizationList.fromMap(map); + + expect(result.total, 5); + expect(result.organizations, []); + }); + }); +} diff --git a/test/src/models/oauth2_organization_test.dart b/test/src/models/oauth2_organization_test.dart new file mode 100644 index 00000000..7d56d71c --- /dev/null +++ b/test/src/models/oauth2_organization_test.dart @@ -0,0 +1,17 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Organization', () { + test('model', () { + final model = Oauth2Organization( + $id: "5e5ea5c16897e", + ); + + final map = model.toMap(); + final result = Oauth2Organization.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + }); + }); +} diff --git a/test/src/models/oauth2_par_test.dart b/test/src/models/oauth2_par_test.dart new file mode 100644 index 00000000..8ccc1d58 --- /dev/null +++ b/test/src/models/oauth2_par_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2PAR', () { + test('model', () { + final model = Oauth2PAR( + request_uri: "urn:appwrite:oauth2:request:5e5ea5c16897e", + expires_in: 600, + ); + + final map = model.toMap(); + final result = Oauth2PAR.fromMap(map); + + expect(result.request_uri, "urn:appwrite:oauth2:request:5e5ea5c16897e"); + expect(result.expires_in, 600); + }); + }); +} diff --git a/test/src/models/oauth2_project_list_test.dart b/test/src/models/oauth2_project_list_test.dart new file mode 100644 index 00000000..1f6cf6a6 --- /dev/null +++ b/test/src/models/oauth2_project_list_test.dart @@ -0,0 +1,19 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2ProjectList', () { + test('model', () { + final model = Oauth2ProjectList( + total: 5, + projects: [], + ); + + final map = model.toMap(); + final result = Oauth2ProjectList.fromMap(map); + + expect(result.total, 5); + expect(result.projects, []); + }); + }); +} diff --git a/test/src/models/oauth2_project_test.dart b/test/src/models/oauth2_project_test.dart new file mode 100644 index 00000000..9771b53f --- /dev/null +++ b/test/src/models/oauth2_project_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Project', () { + test('model', () { + final model = Oauth2Project( + $id: "5e5ea5c16897e", + region: "fra", + endpoint: "https://fra.cloud.appwrite.io/v1", + ); + + final map = model.toMap(); + final result = Oauth2Project.fromMap(map); + + expect(result.$id, "5e5ea5c16897e"); + expect(result.region, "fra"); + expect(result.endpoint, "https://fra.cloud.appwrite.io/v1"); + }); + }); +} diff --git a/test/src/models/oauth2_reject_test.dart b/test/src/models/oauth2_reject_test.dart new file mode 100644 index 00000000..79aacf6a --- /dev/null +++ b/test/src/models/oauth2_reject_test.dart @@ -0,0 +1,21 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Reject', () { + test('model', () { + final model = Oauth2Reject( + redirectUrl: + "https://example.com/callback?error=access_denied&state=fghij", + ); + + final map = model.toMap(); + final result = Oauth2Reject.fromMap(map); + + expect( + result.redirectUrl, + "https://example.com/callback?error=access_denied&state=fghij", + ); + }); + }); +} diff --git a/test/src/models/oauth2_token_test.dart b/test/src/models/oauth2_token_test.dart new file mode 100644 index 00000000..5dafe749 --- /dev/null +++ b/test/src/models/oauth2_token_test.dart @@ -0,0 +1,25 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Oauth2Token', () { + test('model', () { + final model = Oauth2Token( + access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + scope: "openid email profile", + ); + + final map = model.toMap(); + final result = Oauth2Token.fromMap(map); + + expect(result.access_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."); + expect(result.token_type, "Bearer"); + expect(result.expires_in, 3600); + expect(result.refresh_token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."); + expect(result.scope, "openid email profile"); + }); + }); +} diff --git a/test/src/realtime_response_test.dart b/test/src/realtime_response_test.dart index 4435280a..029c35bf 100644 --- a/test/src/realtime_response_test.dart +++ b/test/src/realtime_response_test.dart @@ -48,7 +48,9 @@ void main() { final responseString = response1.toString(); expect( - responseString, equals('RealtimeResponse(type: $type, data: $data)')); + responseString, + equals('RealtimeResponse(type: $type, data: $data)'), + ); }); test('equality operator should compare two instances', () { diff --git a/test/src/realtime_subscription_test.dart b/test/src/realtime_subscription_test.dart index 1515f1a3..d19e6eac 100644 --- a/test/src/realtime_subscription_test.dart +++ b/test/src/realtime_subscription_test.dart @@ -8,15 +8,18 @@ void main() { final mockStream = StreamController.broadcast(); final mockCloseFunction = () async {}; final mockUnsubscribeFunction = () async {}; - Future mockUpdateFunction( - {List? channels, List? queries}) async {} + Future mockUpdateFunction({ + List? channels, + List? queries, + }) async {} final subscription = RealtimeSubscription( - controller: mockStream, - close: mockCloseFunction, - unsubscribe: mockUnsubscribeFunction, - update: mockUpdateFunction, - channels: ['documents'], - queries: const []); + controller: mockStream, + close: mockCloseFunction, + unsubscribe: mockUnsubscribeFunction, + update: mockUpdateFunction, + channels: ['documents'], + queries: const [], + ); test('should have the correct stream and close function', () { expect(subscription.controller, equals(mockStream)); diff --git a/test/src/upload_progress_test.dart b/test/src/upload_progress_test.dart index d21607ec..3dce66c9 100644 --- a/test/src/upload_progress_test.dart +++ b/test/src/upload_progress_test.dart @@ -14,7 +14,7 @@ void main() { "progress": progress, "sizeUploaded": sizeUploaded, "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded + "chunksUploaded": chunksUploaded, }; final uploadProgress = UploadProgress( $id: id, diff --git a/test/topic_test.dart b/test/topic_test.dart new file mode 100644 index 00000000..ba797dfa --- /dev/null +++ b/test/topic_test.dart @@ -0,0 +1,70 @@ +import 'package:appwrite/appwrite.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('path()', () { + test('joins levels', () { + expect(Topic.path(['user']).toString(), 'user'); + expect( + Topic.path(['user', 'notification']).toString(), + 'user/notification', + ); + }); + + test('appends levels', () { + expect( + Topic.path(['user']).path(['notification']).toString(), + 'user/notification', + ); + }); + }); + + group('any()', () { + test('appends a single-level wildcard', () { + expect( + Topic.path(['user']).any().path(['notification']).toString(), + 'user/+/notification', + ); + expect( + Topic.path(['chat']).any().any().path(['message']).toString(), + 'chat/+/+/message', + ); + }); + + test('starts a topic', () { + expect(Topic.any().path(['notification']).toString(), '+/notification'); + }); + }); + + group('all()', () { + test('ends a topic', () { + expect( + Topic.path(['org']).any().path(['logs']).all().toString(), + 'org/+/logs/#', + ); + }); + + test('matches every topic', () { + expect(Topic.all().toString(), '#'); + }); + }); + + group('errors', () { + final invalid = >{ + 'an empty path': [], + 'an empty level': ['user', ''], + 'a slash': ['user/123'], + 'a lone +': ['user', '+'], + 'an embedded +': ['user', 'a+b'], + 'a lone #': ['user', '#'], + 'an embedded #': ['user', 'a#b'], + }; + + invalid.forEach((name, levels) { + test('rejects $name', () { + expect(() => Topic.path(levels), throwsArgumentError); + expect(() => Topic.any().path(levels), throwsArgumentError); + }); + }); + }); +}