From 0a109924d9f1698c98c70bd2dde30649cd3387a6 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 16 Nov 2026 10:32:21 +0000 Subject: [PATCH] chore: update Android SDK to 31.3.0 --- CHANGELOG.md | 14 + README.md | 41 ++- docs/examples/java/account/create-device.md | 29 ++ .../java/account/create-ldap-session.md | 32 ++ docs/examples/java/account/delete-device.md | 30 ++ docs/examples/java/account/get-device.md | 30 ++ .../java/account/update-device-session.md | 31 ++ docs/examples/kotlin/account/create-device.md | 13 + .../kotlin/account/create-ldap-session.md | 17 ++ docs/examples/kotlin/account/delete-device.md | 15 + docs/examples/kotlin/account/get-device.md | 15 + .../kotlin/account/update-device-session.md | 16 + library/src/main/AndroidManifest.xml | 6 +- library/src/main/java/io/appwrite/Client.kt | 6 +- library/src/main/java/io/appwrite/Tracking.kt | 285 ++++++++++++++++++ .../java/io/appwrite/enums/ImageFormat.kt | 4 +- .../java/io/appwrite/enums/OAuthProvider.kt | 4 + .../main/java/io/appwrite/models/Device.kt | 77 +++++ .../main/java/io/appwrite/models/Session.kt | 8 + .../main/java/io/appwrite/services/Account.kt | 184 ++++++++++- .../main/java/io/appwrite/services/Avatars.kt | 6 +- .../main/java/io/appwrite/services/Push.kt | 75 ++++- .../io/appwrite/services/PushBackground.kt | 66 +++- .../java/io/appwrite/services/PushWakeups.kt | 23 +- .../main/java/io/appwrite/services/Storage.kt | 5 +- .../src/test/java/io/appwrite/TrackingTest.kt | 269 +++++++++++++++++ .../services/PushNotificationOpenedTest.kt | 25 ++ 27 files changed, 1283 insertions(+), 43 deletions(-) create mode 100644 docs/examples/java/account/create-device.md create mode 100644 docs/examples/java/account/create-ldap-session.md create mode 100644 docs/examples/java/account/delete-device.md create mode 100644 docs/examples/java/account/get-device.md create mode 100644 docs/examples/java/account/update-device-session.md create mode 100644 docs/examples/kotlin/account/create-device.md create mode 100644 docs/examples/kotlin/account/create-ldap-session.md create mode 100644 docs/examples/kotlin/account/delete-device.md create mode 100644 docs/examples/kotlin/account/get-device.md create mode 100644 docs/examples/kotlin/account/update-device-session.md create mode 100644 library/src/main/java/io/appwrite/Tracking.kt create mode 100644 library/src/main/java/io/appwrite/models/Device.kt create mode 100644 library/src/test/java/io/appwrite/TrackingTest.kt create mode 100644 library/src/test/java/io/appwrite/services/PushNotificationOpenedTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 51a083c..5daf323 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Change Log +## 31.3.0 + +* Added: `Tracking` sends app, screen and push analytics through `Analytics`; `start()` sends `first_open` once per install and `app_updated` after a version change +* Added: `Push.setTracking` sends `push_received` and `push_opened` with the message's `messageId` +* Added: `PushNotificationOpened.messageId` +* Added: `Account.createDevice`, `getDevice`, `deleteDevice` and `updateDeviceSession`, and the `Device` model +* Added: `Account.createLDAPSession` +* Added: `Session.userName` +* Added: `ImageFormat.AUTO` on `Storage.getFilePreview` and the avatar endpoints, serving avif or webp when the `Accept` header supports it +* Added: `OAuthProvider.NAVER` and `OAuthProvider.VIPPSSANDBOX` +* Updated: the SDK no longer declares `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_REMOTE_MESSAGING`; apps that call `Push.setForeground(true)` declare them +* Fixed: background push keeps waking up on phones that hold back expedited jobs +* Updated: requests send `X-Appwrite-Response-Format: 2.7.2` + ## 31.2.0 * Added: `Client.setEnvironment` to act in a project environment; realtime connections carry it diff --git a/README.md b/README.md index 6f010e4..3de35aa 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![Maven Central](https://img.shields.io/maven-central/v/io.appwrite/sdk-for-android.svg?color=green&style=flat-square) ![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-2.7.0-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-2.7.2-blue.svg?style=flat-square) [![X Account](https://img.shields.io/badge/follow-%40appwrite-000000?logo=x&style=flat-square)](https://x.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) @@ -20,7 +20,7 @@ Kotlin DSL (`build.gradle.kts`): ```kotlin dependencies { - implementation("io.appwrite:sdk-for-android:31.2.0") + implementation("io.appwrite:sdk-for-android:31.3.0") } ``` @@ -28,7 +28,7 @@ Groovy (`build.gradle`): ```groovy dependencies { - implementation 'io.appwrite:sdk-for-android:31.2.0' + implementation 'io.appwrite:sdk-for-android:31.3.0' } ``` @@ -275,12 +275,26 @@ If `backgroundRestricted` is true, the user restricted the app's background usag If the user force-stops the app (Settings > Force stop, and on some devices swiping it away from recents), Android cancels its alarms and jobs: nothing is delivered until the app is opened again, and the broker then replays what was sent meanwhile. -For immediate delivery even after a kill and during Doze, call `push.setForeground(true)` from the foreground: it adds a foreground service with a quiet ongoing notification. If you never enable it, you can remove the service from your merged manifest, so the Play Console does not ask you to declare it: +For immediate delivery even after a kill and during Doze, call `push.setForeground(true)` from the foreground: it adds a foreground service with a quiet ongoing notification. Foreground mode is opt-in, because Google Play asks apps that declare a `remoteMessaging` foreground service to justify it in the Play Console. To use it: -```xml - - -``` +1. Add both permissions to `app/src/main/AndroidManifest.xml`, inside `` and outside ``: + + ```xml + + + + + + ... + + + ``` + +2. In the Play Console, complete the foreground service declaration for remote messaging, under App content > Foreground service permissions. + +3. Call `push.setForeground(true)` while the app is on screen. Without the permissions it reports an error to `onError` and delivery stays on the scheduled runs. + +The SDK already declares its `PushService`, so you don't add a ``. To turn foreground mode off again, call `push.setForeground(false)`. ### Opening a tapped notification @@ -296,6 +310,17 @@ val stop = push.onNotificationOpened { opened -> openSale(opened.data["saleId"]) A tap made while nothing listens is kept for `getInitialNotification()`. The tap intent still carries `Push.EXTRA_TOPIC` and `Push.EXTRA_PAYLOAD` for apps that read their activity's intent. +### Push analytics + +Attach a `Tracking` to send `push_received` for each message a background subscription gets with a notification to show while the app is running, and `push_opened` for each tap reported by `getInitialNotification` or `onNotificationOpened`. Both carry the message's `messageId`, also exposed as `opened.messageId`. + +```kotlin +val tracking = Tracking(Analytics(client), "").also { it.start() } +val push = Push(client, context).setTracking(tracking) +``` + +`tracking.start()` also sends `first_open` once per install and `app_updated` on the first start after the app's version name changes. A reinstall or "clear data" counts as a new install. Call it from `Application.onCreate`. With another push provider, call `tracking.pushReceived(messageId = ..., campaign = ...)` and `tracking.pushOpened(...)` from its handlers. `push_received` is best effort: while the app is killed, its code often does not run when a notification arrives. + ## Learn more - [Android quick start](https://appwrite.io/docs/quick-starts/android) and [Java quick start](https://appwrite.io/docs/quick-starts/android-java) diff --git a/docs/examples/java/account/create-device.md b/docs/examples/java/account/create-device.md new file mode 100644 index 0000000..524f2da --- /dev/null +++ b/docs/examples/java/account/create-device.md @@ -0,0 +1,29 @@ +```java +import android.util.Log; + +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.exceptions.AppwriteException; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +try { + account.createDevice( + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) + ); +} catch (AppwriteException e) { + e.printStackTrace(); +} +``` diff --git a/docs/examples/java/account/create-ldap-session.md b/docs/examples/java/account/create-ldap-session.md new file mode 100644 index 0000000..3f14423 --- /dev/null +++ b/docs/examples/java/account/create-ldap-session.md @@ -0,0 +1,32 @@ +```java +import android.util.Log; + +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.exceptions.AppwriteException; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +try { + account.createLDAPSession( + "", // username + "password", // password + 60L, // duration (optional) + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) + ); +} catch (AppwriteException e) { + e.printStackTrace(); +} +``` diff --git a/docs/examples/java/account/delete-device.md b/docs/examples/java/account/delete-device.md new file mode 100644 index 0000000..589c2a8 --- /dev/null +++ b/docs/examples/java/account/delete-device.md @@ -0,0 +1,30 @@ +```java +import android.util.Log; + +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.exceptions.AppwriteException; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +try { + account.deleteDevice( + "", // deviceId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) + ); +} catch (AppwriteException e) { + e.printStackTrace(); +} +``` diff --git a/docs/examples/java/account/get-device.md b/docs/examples/java/account/get-device.md new file mode 100644 index 0000000..6137d80 --- /dev/null +++ b/docs/examples/java/account/get-device.md @@ -0,0 +1,30 @@ +```java +import android.util.Log; + +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.exceptions.AppwriteException; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +try { + account.getDevice( + "", // deviceId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) + ); +} catch (AppwriteException e) { + e.printStackTrace(); +} +``` diff --git a/docs/examples/java/account/update-device-session.md b/docs/examples/java/account/update-device-session.md new file mode 100644 index 0000000..410c591 --- /dev/null +++ b/docs/examples/java/account/update-device-session.md @@ -0,0 +1,31 @@ +```java +import android.util.Log; + +import io.appwrite.Client; +import io.appwrite.coroutines.CoroutineCallback; +import io.appwrite.exceptions.AppwriteException; +import io.appwrite.services.Account; + +Client client = new Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject(""); // Your project ID + +Account account = new Account(client); + +try { + account.updateDeviceSession( + "", // deviceId + "", // sessionId + new CoroutineCallback<>((result, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } + + Log.d("Appwrite", result.toString()); + }) + ); +} catch (AppwriteException e) { + e.printStackTrace(); +} +``` diff --git a/docs/examples/kotlin/account/create-device.md b/docs/examples/kotlin/account/create-device.md new file mode 100644 index 0000000..a5cac33 --- /dev/null +++ b/docs/examples/kotlin/account/create-device.md @@ -0,0 +1,13 @@ +```kotlin +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createDevice() +``` diff --git a/docs/examples/kotlin/account/create-ldap-session.md b/docs/examples/kotlin/account/create-ldap-session.md new file mode 100644 index 0000000..a406470 --- /dev/null +++ b/docs/examples/kotlin/account/create-ldap-session.md @@ -0,0 +1,17 @@ +```kotlin +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.createLDAPSession( + username = "", + password = "password", + duration = 60, // (optional) +) +``` diff --git a/docs/examples/kotlin/account/delete-device.md b/docs/examples/kotlin/account/delete-device.md new file mode 100644 index 0000000..51601a1 --- /dev/null +++ b/docs/examples/kotlin/account/delete-device.md @@ -0,0 +1,15 @@ +```kotlin +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.deleteDevice( + deviceId = "", +) +``` diff --git a/docs/examples/kotlin/account/get-device.md b/docs/examples/kotlin/account/get-device.md new file mode 100644 index 0000000..d81cd81 --- /dev/null +++ b/docs/examples/kotlin/account/get-device.md @@ -0,0 +1,15 @@ +```kotlin +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.getDevice( + deviceId = "", +) +``` diff --git a/docs/examples/kotlin/account/update-device-session.md b/docs/examples/kotlin/account/update-device-session.md new file mode 100644 index 0000000..c66af0e --- /dev/null +++ b/docs/examples/kotlin/account/update-device-session.md @@ -0,0 +1,16 @@ +```kotlin +import io.appwrite.Client +import io.appwrite.coroutines.CoroutineCallback +import io.appwrite.services.Account + +val client = Client(context) + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +val account = Account(client) + +val result = account.updateDeviceSession( + deviceId = "", + sessionId = "", +) +``` diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml index d2b7d50..72d725e 100644 --- a/library/src/main/AndroidManifest.xml +++ b/library/src/main/AndroidManifest.xml @@ -10,10 +10,8 @@ - - - + + internal val appContext: Context = context.applicationContext ?: context + internal val cookieJar = ListenableCookieJar(CookieManager( SharedPreferencesCookieStore(context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE)), CookiePolicy.ACCEPT_ALL @@ -124,8 +126,8 @@ class Client @JvmOverloads constructor( "x-sdk-name" to "Android", "x-sdk-platform" to "client", "x-sdk-language" to "android", - "x-sdk-version" to "31.2.0", - "x-appwrite-response-format" to "2.7.0" + "x-sdk-version" to "31.3.0", + "x-appwrite-response-format" to "2.7.2" ) config = mutableMapOf() diff --git a/library/src/main/java/io/appwrite/Tracking.kt b/library/src/main/java/io/appwrite/Tracking.kt new file mode 100644 index 0000000..075f62c --- /dev/null +++ b/library/src/main/java/io/appwrite/Tracking.kt @@ -0,0 +1,285 @@ +package io.appwrite + +import android.app.Activity +import android.app.ActivityManager +import android.app.Application +import android.content.Context +import android.os.Bundle +import android.os.SystemClock +import androidx.annotation.MainThread +import io.appwrite.services.Analytics +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import org.json.JSONObject +import java.net.URI +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Auto-tracking helpers for the generated [Analytics] service: install, update and app-lifecycle + * events, push helpers, and manual [screenView] / [event] calls, all sent through + * `Analytics.createEvent`. + * + * Auto-emitted event names follow `snake_case` + lowercase (`screen_view`, `app_backgrounded`, + * `app_foregrounded`, etc.). Prop keys use camelCase to match the endpoint's parameter naming. + * + * Engagement time is reported as a **delta** attached to each `app_backgrounded` event, covering + * only the foreground time accrued since the app last came to the foreground, the same way the + * Web and Flutter helpers report it. + * + * Call [start] from `Application.onCreate` or before the first activity starts, so the lifecycle + * callbacks see every activity: + * + * ```kotlin + * val tracking = Tracking(Analytics(client), "") + * tracking.start() + * ``` + * + * @param url Base URL events are reported under; screen names resolve against it. The endpoint + * only accepts absolute URLs. + */ +class Tracking @JvmOverloads constructor( + private val analytics: Analytics, + /** Analytics property every event is recorded against. */ + val propertyId: String, + val url: String = "app://android", +) { + private val context: Context = analytics.client.appContext + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private var lifecycleAttached = false + private var startedActivities = 0 + private var foregroundSince: Long? = null + + // Sub-second engagement left over from the previous flush, so many short foreground + // stretches do not each lose a fraction of a second to truncation. + private var engagementCarry = 0L + + private val lifecycle = object : Application.ActivityLifecycleCallbacks { + override fun onActivityStarted(activity: Activity) { + startedActivities++ + // Another activity starting while the app is on screen keeps the interval open. + if (foregroundSince != null) { + return + } + foregroundSince = SystemClock.elapsedRealtime() + event("app_foregrounded", interactive = false) + } + + override fun onActivityStopped(activity: Activity) { + startedActivities = (startedActivities - 1).coerceAtLeast(0) + // A rotation stops and restarts the activity without the app leaving the screen. + if (startedActivities > 0 || activity.isChangingConfigurations) { + return + } + val since = foregroundSince ?: return + foregroundSince = null + val elapsed = engagementCarry + SystemClock.elapsedRealtime() - since + val seconds = elapsed / 1000 + engagementCarry = elapsed % 1000 + event("app_backgrounded", engagementTime = seconds.takeIf { it > 0 }, interactive = false) + } + + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit + + override fun onActivityResumed(activity: Activity) = Unit + + override fun onActivityPaused(activity: Activity) = Unit + + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit + + override fun onActivityDestroyed(activity: Activity) = Unit + } + + /** + * Start the default auto-tracking set: app-lifecycle events, as [enableAutoLifecycleEvents], + * plus `first_open` and `app_updated`. + * + * `first_open` is sent once per install, `app_updated` (with `previousVersion` and `version`) + * on the first start after the app's version name changes. Both rely on a marker in the SDK's + * shared preferences, so a reinstall or "clear data" counts as a new install. An existing + * install upgrading to this SDK is not counted when the client has saved cookies; without them + * its first start after the upgrade counts once. + * + * The check runs once per process. An event whose request fails is kept and sent again on the + * next start; a crash after it was sent but before it was cleared sends it once more. + */ + @MainThread + fun start() { + enableAutoLifecycleEvents() + if (!installChecked.compareAndSet(false, true)) { + return + } + scope.launch { + try { + val prefs = context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE) + var pending = prefs.getString(INSTALL_PENDING, null) + // Before anything else: the app's first request can save cookies meanwhile. + val ranBefore = pending == null && context.getSharedPreferences(Client.COOKIE_PREFS, Context.MODE_PRIVATE).all.isNotEmpty() + val saved = prefs.getString(INSTALL_MARKER, null) + val version = context.packageManager.getPackageInfo(context.packageName, 0).versionName.orEmpty() + if (pending == null) { + if (saved == version) { + return@launch + } + pending = when { + saved != null -> JSONObject() + .put("name", "app_updated") + .put("props", JSONObject().put("previousVersion", saved).put("version", version)) + !ranBefore -> JSONObject().put("name", "first_open") + else -> null + }?.toString() + } else if (saved != version) { + // A failed update retried on a newer version reports one previousVersion→current event. + val retried = JSONObject(pending) + val update = retried.optJSONObject("props")?.takeIf { retried.getString("name") == "app_updated" } + // Rolled back to the version it updated from: no net change, so nothing to report. + pending = if (update?.optString("previousVersion") == version) null else retried.also { update?.put("version", version) }.toString() + } + // Pending event and marker in one atomic write, before sending, so no start sends it + // twice and a retried event does not leave the marker on an older version. + if (saved != version) { + prefs.edit().putString(INSTALL_PENDING, pending).putString(INSTALL_MARKER, version).commit() + } + val event = JSONObject(pending ?: return@launch) + val props = event.optJSONObject("props")?.let { json -> json.keys().asSequence().associateWith { json.getString(it) } } + if (send(event.getString("name"), props = props, interactive = false)) { + prefs.edit().remove(INSTALL_PENDING).commit() + } + } catch (e: Exception) { + // Analytics never surface errors to the host app. + } + } + } + + /** + * Start emitting `app_backgrounded` and `app_foregrounded` events when the app leaves or + * returns to the screen. Idempotent: repeat calls no-op. + */ + @MainThread + fun enableAutoLifecycleEvents() { + val app = context as? Application ?: return + if (lifecycleAttached) { + return + } + lifecycleAttached = true + // A process started in the background (e.g. by push delivery) is not on screen yet, so + // its first activity sends app_foregrounded. + val onScreen = ActivityManager.RunningAppProcessInfo() + .also { ActivityManager.getMyMemoryState(it) } + .importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND + foregroundSince = if (onScreen) SystemClock.elapsedRealtime() else null + engagementCarry = 0 + app.registerActivityLifecycleCallbacks(lifecycle) + } + + /** Stop emitting lifecycle events. Safe to call when auto-lifecycle was never enabled. */ + @MainThread + fun disableAutoLifecycleEvents() { + if (!lifecycleAttached) { + return + } + lifecycleAttached = false + startedActivities = 0 + foregroundSince = null + engagementCarry = 0 + (context as Application).unregisterActivityLifecycleCallbacks(lifecycle) + } + + /** + * Emit an ad-hoc analytics event. [url] may be absolute or a path resolved against + * [Tracking.url]. Request failures are swallowed so analytics never surface errors to the + * host app. + */ + @JvmOverloads + fun event( + name: String, + url: String? = null, + props: Map? = null, + engagementTime: Long? = null, + interactive: Boolean? = null, + ) { + scope.launch { send(name, url, props, engagementTime, interactive) } + } + + // Whether the endpoint accepted the event; failures, including a malformed [url], are swallowed. + private suspend fun send( + name: String, + url: String? = null, + props: Map? = null, + engagementTime: Long? = null, + interactive: Boolean? = null, + ): Boolean = try { + val base = URI(this.url) + // java.net.URI drops the "/" RFC 3986 puts between a path-less base and a relative path. + val target = url?.let { (if (base.rawPath.isNullOrEmpty()) base.resolve("/") else base).resolve(URI(null, null, it, null)).toString() } + analytics.createEvent( + propertyId = propertyId, + name = name, + url = target ?: this.url, + // The endpoint buckets this as viewport width in dp, like the Web helper's `innerWidth`. + screenWidth = context.resources.configuration.screenWidthDp.takeIf { it > 0 }?.toLong(), + engagementTime = engagementTime, + // The endpoint takes props as a flat alternating key/value list. + props = props?.filterValues { it != null }?.flatMap { listOf(it.key, "${it.value}") }, + interactive = interactive, + ) + true + } catch (e: Exception) { + false + } + + /** + * Mobile-idiomatic screen-view shortcut. Renders as a `screen_view` analytics event with + * `screen`, optional `screenClass` and any caller-supplied properties. [name] is also the + * event URL's path. + */ + @JvmOverloads + fun screenView( + name: String, + className: String? = null, + props: Map? = null, + ) { + val merged = mutableMapOf("screen" to name) + if (className != null) { + merged["screenClass"] = className + } + if (props != null) { + merged.putAll(props) + } + event("screen_view", url = name, props = merged) + } + + /** + * Send `push_received` for a push notification the device got. Call it from your push + * handler; best effort, since while the app is killed its code often does not run when a + * notification arrives. [messageId] is the Appwrite Messaging message id. + */ + @JvmOverloads + fun pushReceived(messageId: String? = null, campaign: String? = null) { + event("push_received", props = pushProps(messageId, campaign), interactive = false) + } + + /** + * Send `push_opened` when the user taps a push notification. [messageId] is the + * Appwrite Messaging message id. + */ + @JvmOverloads + fun pushOpened(messageId: String? = null, campaign: String? = null) { + event("push_opened", props = pushProps(messageId, campaign), interactive = true) + } + + private fun pushProps(messageId: String?, campaign: String?): Map = buildMap { + messageId?.let { put("messageId", it) } + campaign?.let { put("campaign", it) } + } + + internal companion object { + private const val INSTALL_MARKER = "trackingInstallVersion" + private const val INSTALL_PENDING = "trackingInstallPending" + + // Shared by every instance, so concurrent or repeated start() calls never race on the marker. + internal val installChecked = AtomicBoolean(false) + } +} diff --git a/library/src/main/java/io/appwrite/enums/ImageFormat.kt b/library/src/main/java/io/appwrite/enums/ImageFormat.kt index 77ea60d..d64dc3b 100644 --- a/library/src/main/java/io/appwrite/enums/ImageFormat.kt +++ b/library/src/main/java/io/appwrite/enums/ImageFormat.kt @@ -16,7 +16,9 @@ enum class ImageFormat(val value: String) { @SerializedName("avif") AVIF("avif"), @SerializedName("gif") - GIF("gif"); + GIF("gif"), + @SerializedName("auto") + AUTO("auto"); override fun toString() = value } diff --git a/library/src/main/java/io/appwrite/enums/OAuthProvider.kt b/library/src/main/java/io/appwrite/enums/OAuthProvider.kt index 14ca80e..11ddd0a 100644 --- a/library/src/main/java/io/appwrite/enums/OAuthProvider.kt +++ b/library/src/main/java/io/appwrite/enums/OAuthProvider.kt @@ -57,6 +57,8 @@ enum class OAuthProvider(val value: String) { LINKEDIN("linkedin"), @SerializedName("microsoft") MICROSOFT("microsoft"), + @SerializedName("naver") + NAVER("naver"), @SerializedName("notion") NOTION("notion"), @SerializedName("oidc") @@ -89,6 +91,8 @@ enum class OAuthProvider(val value: String) { TWITCH("twitch"), @SerializedName("vipps") VIPPS("vipps"), + @SerializedName("vippsSandbox") + VIPPSSANDBOX("vippsSandbox"), @SerializedName("webflow") WEBFLOW("webflow"), @SerializedName("wordpress") diff --git a/library/src/main/java/io/appwrite/models/Device.kt b/library/src/main/java/io/appwrite/models/Device.kt new file mode 100644 index 0000000..43cbcc4 --- /dev/null +++ b/library/src/main/java/io/appwrite/models/Device.kt @@ -0,0 +1,77 @@ +package io.appwrite.models + +import com.google.gson.annotations.SerializedName +import io.appwrite.extensions.jsonCast + +/** + * Device + */ +data class Device( + /** + * Device ID. + */ + @SerializedName("\$id") + val id: String, + + /** + * Device creation date in ISO 8601 format. + */ + @SerializedName("\$createdAt") + val createdAt: String, + + /** + * Device update date in ISO 8601 format. + */ + @SerializedName("\$updatedAt") + val updatedAt: String, + + /** + * Device expiration date in ISO 8601 format. + */ + @SerializedName("expire") + val expire: String, + + /** + * ID of the session that is currently active on the device. Empty when no session is active, for example right after the active session was deleted. + */ + @SerializedName("activeSessionId") + val activeSessionId: String, + + /** + * List of sessions the device holds. Switch between them to change the active account. + */ + @SerializedName("sessions") + val sessions: List, + + /** + * Secret used to authenticate the device. Carried by the device cookie; only included in the response if the request was made with an API key. + */ + @SerializedName("secret") + val secret: String, + +) { + fun toMap(): Map = mapOf( + "\$id" to id as Any, + "\$createdAt" to createdAt as Any, + "\$updatedAt" to updatedAt as Any, + "expire" to expire as Any, + "activeSessionId" to activeSessionId as Any, + "sessions" to sessions.map { it.toMap() } as Any, + "secret" to secret as Any, + ) + + companion object { + @Suppress("UNCHECKED_CAST") + fun from( + map: Map, + ) = Device( + id = (if (map.containsKey("\$id")) map["\$id"] else "") as String, + createdAt = (if (map.containsKey("\$createdAt")) map["\$createdAt"] else "") as String, + updatedAt = (if (map.containsKey("\$updatedAt")) map["\$updatedAt"] else "") as String, + expire = (if (map.containsKey("expire")) map["expire"] else "") as String, + activeSessionId = (if (map.containsKey("activeSessionId")) map["activeSessionId"] else "") as String, + sessions = ((if (map.containsKey("sessions")) map["sessions"] else listOf()) as List>).map { Session.from(map = it) }, + secret = (if (map.containsKey("secret")) map["secret"] else "") as String, + ) + } +} diff --git a/library/src/main/java/io/appwrite/models/Session.kt b/library/src/main/java/io/appwrite/models/Session.kt index 884d581..3ed6a92 100644 --- a/library/src/main/java/io/appwrite/models/Session.kt +++ b/library/src/main/java/io/appwrite/models/Session.kt @@ -31,6 +31,12 @@ data class Session( @SerializedName("userId") val userId: String, + /** + * Name of the user the session belongs to. Lets a client label the account, for example in an account switcher. + */ + @SerializedName("userName") + val userName: String, + /** * Session expiration date in ISO 8601 format. */ @@ -187,6 +193,7 @@ data class Session( "\$createdAt" to createdAt as Any, "\$updatedAt" to updatedAt as Any, "userId" to userId as Any, + "userName" to userName as Any, "expire" to expire as Any, "provider" to provider as Any, "providerUid" to providerUid as Any, @@ -223,6 +230,7 @@ data class Session( createdAt = (if (map.containsKey("\$createdAt")) map["\$createdAt"] else "") as String, updatedAt = (if (map.containsKey("\$updatedAt")) map["\$updatedAt"] else "") as String, userId = (if (map.containsKey("userId")) map["userId"] else "") as String, + userName = (if (map.containsKey("userName")) map["userName"] else "") as String, expire = (if (map.containsKey("expire")) map["expire"] else "") as String, provider = (if (map.containsKey("provider")) map["provider"] else "") as String, providerUid = (if (map.containsKey("providerUid")) map["providerUid"] else "") as String, diff --git a/library/src/main/java/io/appwrite/services/Account.kt b/library/src/main/java/io/appwrite/services/Account.kt index 99dfc84..bae8f95 100644 --- a/library/src/main/java/io/appwrite/services/Account.kt +++ b/library/src/main/java/io/appwrite/services/Account.kt @@ -347,6 +347,146 @@ class Account(client: Client) : Service(client) { ) } + /** + * Create an account switching device. A device is a container, scoped to one browser or app install, that holds multiple sessions and tracks which one is active. Once a device exists, session creation endpoints attach the new session to it automatically, so a single browser can stay signed in to several accounts and switch between them. A device holds at most one session per user: signing in again as a user it already holds replaces that user's session. The device lives as long as its newest session. + * + * The device secret is returned in a cookie. Run this on app start: if the browser already has a valid device, the existing one is returned with the same status code instead of an error, so it is always safe to call. + * + * Every session that joins the device rotates the device secret and re-issues the cookie, so an earlier copy of the secret stops working. A client that keeps the secret itself, rather than relying on the cookie, must replace it from each session response. + * + * @return [io.appwrite.models.Device] + */ + @Throws(AppwriteException::class) + suspend fun createDevice(): io.appwrite.models.Device { + val apiPath = "/account/devices" + val apiParams = mutableMapOf() + val apiHeaders = mutableMapOf( + "X-Appwrite-Project" to client.config["project"].orEmpty(), + "content-type" to "application/json", + "accept" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Device = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Device.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Device::class.java, + converter, + ) + } + + /** + * Get the account switching device for the current browser, including every session it holds, the name of the user each session belongs to, and the ID of the active session. Use the string 'current' to reference the current browser's device. + * + * @param deviceId Device ID. Use the string 'current' to reference the device of the current browser. + * @return [io.appwrite.models.Device] + */ + @Throws(AppwriteException::class) + suspend fun getDevice( + deviceId: String, + ): io.appwrite.models.Device { + if (deviceId.isEmpty()) { + throw AppwriteException("Missing required parameter: \"deviceId\"") + } + val apiPath = ("/account/devices/{deviceId}" + .replace("{deviceId}", Client.encodePath(deviceId)) + ) + val apiParams = mutableMapOf() + val apiHeaders = mutableMapOf( + "X-Appwrite-Project" to client.config["project"].orEmpty(), + "accept" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Device = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Device.from(map = it as Map) + } + return client.call( + "GET", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Device::class.java, + converter, + ) + } + + /** + * Delete the account switching device for the current browser. Every session the device holds is signed out, each firing its own session delete event, the device is removed, and both the device and session cookies are cleared. Use the string 'current' to reference the current browser's device. + * + * @param deviceId Device ID. Use the string 'current' to reference the device of the current browser. + * @return [Any] + */ + @Throws(AppwriteException::class) + suspend fun deleteDevice( + deviceId: String, + ): Any { + if (deviceId.isEmpty()) { + throw AppwriteException("Missing required parameter: \"deviceId\"") + } + val apiPath = ("/account/devices/{deviceId}" + .replace("{deviceId}", Client.encodePath(deviceId)) + ) + val apiParams = mutableMapOf() + val apiHeaders = mutableMapOf( + "X-Appwrite-Project" to client.config["project"].orEmpty(), + "content-type" to "application/json", + "accept" to "application/json", + ) + return client.call( + "DELETE", + apiPath, + apiHeaders, + apiParams, + responseType = Any::class.java, + ) + } + + /** + * Switch the active account on an account switching device to one of the sessions it holds. The chosen session becomes active and its secret is written to the browser's session cookie, so subsequent requests authenticate as that account. Use the string 'current' to reference the current browser's device. + * + * Switching rotates the chosen session's secret. Any other holder of that session, such as a copy kept elsewhere, stops working, so a session should not be shared across devices. + * + * @param deviceId Device ID. Use the string 'current' to reference the device of the current browser. + * @param sessionId ID of the session, held by the device, to make active. + * @return [io.appwrite.models.Session] + */ + @Throws(AppwriteException::class) + suspend fun updateDeviceSession( + deviceId: String, + sessionId: String, + ): io.appwrite.models.Session { + if (deviceId.isEmpty()) { + throw AppwriteException("Missing required parameter: \"deviceId\"") + } + val apiPath = ("/account/devices/{deviceId}/session" + .replace("{deviceId}", Client.encodePath(deviceId)) + ) + val apiParams = mutableMapOf( + "sessionId" to sessionId, + ) + val apiHeaders = mutableMapOf( + "X-Appwrite-Project" to client.config["project"].orEmpty(), + "content-type" to "application/json", + "accept" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "PATCH", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + /** * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. * This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. @@ -2038,6 +2178,46 @@ class Account(client: Client) : Service(client) { ) } + /** + * Allow the user to login into their account by providing the username and password they use in the project's LDAP directory. The directory verifies the password; on the first sign-in an account is created from the directory entry, and on later sign-ins the name, email and phone follow the directory. This endpoint requires LDAP to be configured and enabled for the project. A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * @param username Directory username, matched against the username attribute of the project's LDAP configuration. + * @param password Directory password. + * @param duration Session length in seconds. Minimum is 60 seconds, and it cannot exceed the project maximum session length. Defaults to the project maximum session length. + * @return [io.appwrite.models.Session] + */ + @JvmOverloads + @Throws(AppwriteException::class) + suspend fun createLDAPSession( + username: String, + password: String, + duration: Long? = null, + ): io.appwrite.models.Session { + val apiPath = "/account/sessions/ldap" + val apiParams = mutableMapOf( + "username" to username, + "password" to password, + "duration" to duration, + ) + val apiHeaders = mutableMapOf( + "X-Appwrite-Project" to client.config["project"].orEmpty(), + "content-type" to "application/json", + "accept" to "application/json", + ) + val converter: (Any) -> io.appwrite.models.Session = { + @Suppress("UNCHECKED_CAST") + io.appwrite.models.Session.from(map = it as Map) + } + return client.call( + "POST", + apiPath, + apiHeaders, + apiParams, + responseType = io.appwrite.models.Session::class.java, + converter, + ) + } + /** * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * @@ -2086,7 +2266,7 @@ class Account(client: Client) : Service(client) { * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * * - * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, appwrite, auth0, authentik, autodesk, bitbucket, bitly, box, cloudflare, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, fusionauth, github, gitlab, google, huggingface, kakao, keycloak, kick, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, resend, salesforce, slack, spotify, stripe, tiktok, tradeshift, tradeshiftBox, twitch, vipps, webflow, wordpress, x, yahoo, yammer, yandex, zoho, zoom. + * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, appwrite, auth0, authentik, autodesk, bitbucket, bitly, box, cloudflare, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, fusionauth, github, gitlab, google, huggingface, kakao, keycloak, kick, linkedin, microsoft, naver, notion, oidc, okta, paypal, paypalSandbox, podio, resend, salesforce, slack, spotify, stripe, tiktok, tradeshift, tradeshiftBox, twitch, vipps, vippsSandbox, webflow, wordpress, x, yahoo, yammer, yandex, zoho, zoom. * @param success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @param failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @param scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. @@ -2598,7 +2778,7 @@ class Account(client: Client) : Service(client) { * * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, appwrite, auth0, authentik, autodesk, bitbucket, bitly, box, cloudflare, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, fusionauth, github, gitlab, google, huggingface, kakao, keycloak, kick, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, resend, salesforce, slack, spotify, stripe, tiktok, tradeshift, tradeshiftBox, twitch, vipps, webflow, wordpress, x, yahoo, yammer, yandex, zoho, zoom. + * @param provider OAuth2 Provider. Currently, supported providers are: amazon, apple, appwrite, auth0, authentik, autodesk, bitbucket, bitly, box, cloudflare, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, fusionauth, github, gitlab, google, huggingface, kakao, keycloak, kick, linkedin, microsoft, naver, notion, oidc, okta, paypal, paypalSandbox, podio, resend, salesforce, slack, spotify, stripe, tiktok, tradeshift, tradeshiftBox, twitch, vipps, vippsSandbox, webflow, wordpress, x, yahoo, yammer, yandex, zoho, zoom. * @param success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @param failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @param scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. diff --git a/library/src/main/java/io/appwrite/services/Avatars.kt b/library/src/main/java/io/appwrite/services/Avatars.kt index 8624ff3..5fe1909 100644 --- a/library/src/main/java/io/appwrite/services/Avatars.kt +++ b/library/src/main/java/io/appwrite/services/Avatars.kt @@ -423,6 +423,8 @@ class Avatars(client: Client) : Service(client) { * * When width and height are specified, the image is resized accordingly. If both dimensions are 0, the API provides an image at original size. If dimensions are not specified, the default viewport size is 1280x720px. * + * Set `output` to `auto` to receive avif or webp when the `Accept` header of your request supports it, falling back to png. + * * @param url Website URL which you want to capture. * @param headers HTTP headers to send with the browser request. Only Accept and Accept-Language are allowed. Defaults to empty. * @param viewportWidth Browser viewport width. Pass an integer between 1 to 1920. Defaults to 1280. @@ -442,7 +444,7 @@ class Avatars(client: Client) : Service(client) { * @param width Output image width. Pass 0 to use original width, or an integer between 1 to 2000. Defaults to 0 (original width). * @param height Output image height. Pass 0 to use original height, or an integer between 1 to 2000. Defaults to 0 (original height). * @param quality Screenshot quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. - * @param output Output format type (jpeg, jpg, png, gif and webp). + * @param output Output format type (jpeg, jpg, png, gif, webp, heic and avif). Pass auto to serve avif or webp when the Accept header of your request supports it, falling back to png. * @return [ByteArray] */ @JvmOverloads @@ -494,7 +496,7 @@ class Avatars(client: Client) : Service(client) { ) val apiHeaders = mutableMapOf( "X-Appwrite-Project" to client.config["project"].orEmpty(), - "accept" to "image/png", + "accept" to "image/*", ) return client.call( "GET", diff --git a/library/src/main/java/io/appwrite/services/Push.kt b/library/src/main/java/io/appwrite/services/Push.kt index 21409d7..49f66d2 100644 --- a/library/src/main/java/io/appwrite/services/Push.kt +++ b/library/src/main/java/io/appwrite/services/Push.kt @@ -8,6 +8,7 @@ import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle +import android.os.SystemClock import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat @@ -16,6 +17,7 @@ import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient import io.appwrite.Client import io.appwrite.Service import io.appwrite.Topic +import io.appwrite.Tracking import io.appwrite.exceptions.AppwriteException import org.json.JSONArray import org.json.JSONException @@ -30,20 +32,22 @@ import java.util.concurrent.atomic.AtomicBoolean private const val LOG_TAG = "AppwritePush" /** A background notification the user tapped. */ -data class PushNotificationOpened( +data class PushNotificationOpened @JvmOverloads constructor( /** The topic the message was published to. */ val topic: String, /** The `data` sent with the message (e.g. `createPush`), parsed; empty when it had none. */ val data: Map, + /** The Appwrite Messaging message id, when the message was sent through Messaging. */ + val messageId: String? = null, ) { internal companion object { fun of(tap: PushTap): PushNotificationOpened { - val data = try { - JSONObject(tap.payload).optJSONObject("data")?.toMap() + val json = try { + JSONObject(tap.payload) } catch (e: JSONException) { null } - return PushNotificationOpened(tap.topic, data ?: emptyMap()) + return PushNotificationOpened(tap.topic, json?.optJSONObject("data")?.toMap() ?: emptyMap(), (json?.opt("messageId") as? String)?.takeIf { it.isNotEmpty() }) } private fun JSONObject.toMap(): Map = keys().asSequence().associateWith { jsonValue(get(it)) } @@ -260,8 +264,9 @@ class Push( * Run background delivery in a foreground service (with a quiet ongoing * notification), for immediate delivery even after the process is killed and during Doze, * instead of only the scheduled runs. Saved, so it applies after restarts too; call it from - * the foreground (Android 12+ refuses to start the service from the background). Apps that - * never enable it can remove the service from their merged manifest. It only affects + * the foreground (Android 12+ refuses to start the service from the background). It needs the + * `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_REMOTE_MESSAGING` permissions declared in the + * app's manifest, and reports to [onError] without them. It only affects * `background = true` subscriptions; `background = false` ones still deliver only while the * app process is alive. */ @@ -278,7 +283,7 @@ class Push( * push.getInitialNotification()?.let { openSale(it.data["saleId"]) } * ``` */ - fun getInitialNotification(): PushNotificationOpened? = PushTaps.take()?.let { PushNotificationOpened.of(it) } + fun getInitialNotification(): PushNotificationOpened? = PushTaps.take()?.let { opened(it) } /** * Call [callback] on the main thread each time the user taps a background notification while @@ -291,7 +296,42 @@ class Push( * ``` */ fun onNotificationOpened(callback: (PushNotificationOpened) -> Unit): () -> Unit = - PushTaps.listen { callback(PushNotificationOpened.of(it)) } + PushTaps.listen { callback(opened(it)) } + + @Volatile + private var tracking: Tracking? = null + + /** + * Send push analytics through [tracking]: `push_received` for each message a background + * subscription gets with a notification to show while the app is running, and `push_opened` + * for each tap reported by [getInitialNotification] or [onNotificationOpened], both with the + * message's `messageId`. + */ + fun setTracking(tracking: Tracking): Push { + this.tracking = tracking + return this + } + + private fun opened(tap: PushTap): PushNotificationOpened { + val opened = PushNotificationOpened.of(tap) + val tracking = tracking + if (tracking != null && TrackedPush.first("opened\n${tap.topic}\n${opened.messageId ?: JSONObject(opened.data)}")) { + tracking.pushOpened(opened.messageId) + } + return opened + } + + // Checked on delivery, since PushSubscription.update can toggle background later. + private fun received(id: String, message: PushMessage) { + val tracking = tracking ?: return + if (subscriptions[id]?.background != true || !PushBackground.notificationContent(message).visible) { + return + } + val messageId = runCatching { JSONObject(message.data).opt("messageId") as? String }.getOrNull()?.takeIf { it.isNotEmpty() } + if (TrackedPush.first("received\n${message.topic}\n${messageId ?: message.data}")) { + tracking.pushReceived(messageId) + } + } /** * Subscribe to the signed-in user's own topic, `users/` — "messages for me" @@ -415,7 +455,11 @@ class Push( for (topic in topics) { val id = UUID.randomUUID().toString() ids.add(id) - subscriptions[id] = Sub(topic, callback, background, title, retry, notifyInForeground) + val tracked: (PushMessage) -> Unit = { message -> + received(id, message) + callback(message) + } + subscriptions[id] = Sub(topic, tracked, background, title, retry, notifyInForeground) } // If any SUBSCRIBE fails, roll this call's registrations back and return to a @@ -918,6 +962,19 @@ internal fun resolvePushUserId(client: Client): String { // Asks once per process for POST_NOTIFICATIONS (Android 13+) when background delivery starts, from // the app's visible activity, or from the next one to resume when none is. An activity Push is // created with counts as visible, since it resumed before the lifecycle callbacks were registered. +// Recently tracked push events, process-wide: a tap reaches every onNotificationOpened listener and +// a message every overlapping subscription, so each counts once. +private object TrackedPush { + private val tracked = mutableMapOf() + + @Synchronized + fun first(key: String): Boolean { + val now = SystemClock.elapsedRealtime() + tracked.values.removeAll { now - it > 10_000 } + return tracked.putIfAbsent(key, now) == null + } +} + private object NotificationPermissionPrompt { private const val REQUEST_CODE = 9412 diff --git a/library/src/main/java/io/appwrite/services/PushBackground.kt b/library/src/main/java/io/appwrite/services/PushBackground.kt index 266114c..6ad0c69 100644 --- a/library/src/main/java/io/appwrite/services/PushBackground.kt +++ b/library/src/main/java/io/appwrite/services/PushBackground.kt @@ -180,6 +180,10 @@ internal object PushBackground { @Volatile var serviceRunning = false + // Whether the expedited job an alarm handed its run to has started; it runs in this process. + @Volatile + var expeditedJobRunning = 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 @@ -299,13 +303,31 @@ internal object PushBackground { val app = context.applicationContext PushStore.setForeground(app, enabled) serviceStartReported = false + if (enabled && !foregroundDeclared(app)) { + report( + AppwriteException( + "Foreground mode needs the FOREGROUND_SERVICE and FOREGROUND_SERVICE_REMOTE_MESSAGING permissions declared in the app's manifest", + ), + ) + } ensureService(app) } + /** Whether the app declares what foreground mode needs: [PushService] and its permissions. */ + fun foregroundDeclared(context: Context): Boolean { + val app = context.applicationContext + val service = runCatching { + app.packageManager.getServiceInfo(ComponentName(app, PushService::class.java), 0) + }.isSuccess + return service && + declares(app, Manifest.permission.FOREGROUND_SERVICE) && + (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE || declares(app, Manifest.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING)) + } + /** 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) { + return PushStore.foreground(app) && foregroundDeclared(app) && synchronized(lock) { load(app) isActive() } @@ -480,24 +502,47 @@ internal object PushBackground { * Android 12+: hand a run to an expedited job, which starts at once with network access and * keeps the process runnable until it finishes. A broadcast receiver woken in a cached process * runs at background priority and can be frozen before it connects. Returns false when the - * job cannot be scheduled (older Android, or the expedited quota is used up), so the caller - * runs the tick itself. + * job cannot be scheduled (older Android, or the expedited quota is used up) or the last one + * never started, so the caller runs the tick itself. Returns true without a new job while the + * last one is still running. */ fun runExpedited(context: Context): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { return false } + val jobs = context.getSystemService(JobScheduler::class.java) ?: return false + // The last hand-off is still pending. A running one keeps its run; one that never started + // is held back by the system, so run in the receiver. + if (jobs.getPendingJob(EXPEDITED_JOB_ID) != null) { + if (expeditedJobRunning) { + return true + } + jobs.cancel(EXPEDITED_JOB_ID) + return false + } return try { val job = JobInfo.Builder(EXPEDITED_JOB_ID, ComponentName(context, PushJobService::class.java)) .setExpedited(true) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .build() - context.getSystemService(JobScheduler::class.java)?.schedule(job) == JobScheduler.RESULT_SUCCESS + jobs.schedule(job) == JobScheduler.RESULT_SUCCESS } catch (e: Exception) { false } } + /** Arm the next alarm of the chain without touching the jobs (the alarm handed its run to one). */ + fun armNextAlarm(context: Context) { + val app = context.applicationContext + val active = synchronized(lock) { + load(app) + isActive() + } + if (active) { + schedule(app, INTERVAL_MS, alarmOnly = true) + } + } + /** 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, alarmOnly = true) @@ -1216,7 +1261,7 @@ internal object PushBackground { exactAlarms = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || app.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true, ignoringBatteryOptimizations = app.getSystemService(PowerManager::class.java)?.isIgnoringBatteryOptimizations(app.packageName) == true, - foregroundService = PushStore.foreground(app), + foregroundService = PushStore.foreground(app) && foregroundDeclared(app), backgroundRestricted = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && app.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted == true, ) @@ -1250,14 +1295,15 @@ internal object PushBackground { ) } + private fun declares(context: Context, permission: String): Boolean = runCatching { + @Suppress("DEPRECATION") + context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions + }.getOrNull()?.contains(permission) == true + // Open a settings screen for this package when the app declares [permission]. private fun openSettings(context: Context, action: String, permission: String): Boolean { val app = context.applicationContext - val declared = runCatching { - @Suppress("DEPRECATION") - app.packageManager.getPackageInfo(app.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions - }.getOrNull()?.contains(permission) == true - if (!declared) { + if (!declares(app, permission)) { return false } return try { diff --git a/library/src/main/java/io/appwrite/services/PushWakeups.kt b/library/src/main/java/io/appwrite/services/PushWakeups.kt index c6d5616..079d135 100644 --- a/library/src/main/java/io/appwrite/services/PushWakeups.kt +++ b/library/src/main/java/io/appwrite/services/PushWakeups.kt @@ -15,13 +15,27 @@ class PushJobService : JobService() { // A chained job arms the next under the other chained id; the watchdog and an expedited // run (handed over by the alarm) only run once. Each stays up while missed messages arrive. val chained = params.jobId.takeIf { it == PushBackground.JOB_ID || it == PushBackground.NEXT_JOB_ID } - PushBackground.tick(this, chained, PushBackground.JOB_DRAIN_MS) { jobFinished(params, false) } + val expedited = params.jobId == PushBackground.EXPEDITED_JOB_ID + if (expedited) { + PushBackground.expeditedJobRunning = true + } + PushBackground.tick(this, chained, PushBackground.JOB_DRAIN_MS) { + if (expedited) { + PushBackground.expeditedJobRunning = false + } + jobFinished(params, false) + } return true } // The run re-arms the next one itself, and the watchdog repeats on its own, so a stopped run // needs no retry. - override fun onStopJob(params: JobParameters): Boolean = false + override fun onStopJob(params: JobParameters): Boolean { + if (params.jobId == PushBackground.EXPEDITED_JOB_ID) { + PushBackground.expeditedJobRunning = false + } + return false + } } /** @@ -34,8 +48,11 @@ class PushAlarmReceiver : BroadcastReceiver() { return } // On Android 12+ the run goes to an expedited job, which keeps the process runnable while it - // connects and the broker replays; it runs here when the system refuses one. + // connects and the broker replays; it runs here when the system refuses one. The next alarm + // is armed first: an accepted job is not a started one (some phones hold jobs back for + // thermal or vendor limits), and the chain must not depend on it. if (PushBackground.runExpedited(context)) { + PushBackground.armNextAlarm(context) return } val pending = goAsync() diff --git a/library/src/main/java/io/appwrite/services/Storage.kt b/library/src/main/java/io/appwrite/services/Storage.kt index d2313ea..6e1f81d 100644 --- a/library/src/main/java/io/appwrite/services/Storage.kt +++ b/library/src/main/java/io/appwrite/services/Storage.kt @@ -294,7 +294,8 @@ class Storage(client: Client) : Service(client) { } /** - * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Preview is supported only for image files smaller than 10MB. + * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Set `output` to `auto` to receive avif or webp when the client's `Accept` header supports it, falling back to the original image format. Preview is supported only for image files smaller than 10MB. + * * * @param bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). * @param fileId File ID @@ -308,7 +309,7 @@ class Storage(client: Client) : Service(client) { * @param opacity Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. * @param rotation Preview image rotation in degrees. Pass an integer between -360 and 360. * @param background Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. - * @param output Output format type (jpeg, jpg, png, gif and webp). + * @param output Output format type (jpeg, jpg, png, gif, webp, heic and avif). Pass auto to serve avif or webp when the client's Accept header supports it, falling back to the original format. * @param token File token for accessing this file. * @return [ByteArray] */ diff --git a/library/src/test/java/io/appwrite/TrackingTest.kt b/library/src/test/java/io/appwrite/TrackingTest.kt new file mode 100644 index 0000000..f8c0462 --- /dev/null +++ b/library/src/test/java/io/appwrite/TrackingTest.kt @@ -0,0 +1,269 @@ +package io.appwrite + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.appwrite.services.Analytics +import io.appwrite.services.Push +import io.appwrite.services.PushBackground +import io.appwrite.services.PushMessage +import io.appwrite.services.PushTap +import io.appwrite.services.PushTaps +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Protocol +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import okio.Buffer +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.util.Collections + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4::class) +class TrackingTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private val events: MutableList = Collections.synchronizedList(mutableListOf()) + private val trackers = mutableListOf() + private lateinit var client: Client + private lateinit var analytics: Analytics + + // Requests to fail before the endpoint accepts events again. + @Volatile + private var failures = 0 + + @Volatile + private var requests = 0 + + @Before + fun setUp() { + Tracking.installChecked.set(false) + client = Client(context).setProject("project").setJWT("jwt") + client.endpointPush = "mqtt://127.0.0.1:1" + client.http = client.http.newBuilder() + .addInterceptor { chain -> + val failed = synchronized(this) { + requests++ + (failures > 0).also { if (it) failures-- } + } + val body = Buffer().also { chain.request().body!!.writeTo(it) }.readUtf8() + if (!failed) { + events.add(JSONObject(body)) + } + Response.Builder() + .request(chain.request()) + .protocol(Protocol.HTTP_1_1) + .code(if (failed) 500 else 200) + .message(if (failed) "Error" else "OK") + .body((if (failed) "{\"message\":\"failed\",\"code\":500}" else "{}").toResponseBody("application/json".toMediaType())) + .build() + } + .build() + analytics = Analytics(client) + } + + @After + fun tearDown() { + trackers.forEach { it.disableAutoLifecycleEvents() } + } + + private fun marker(): String? = context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).getString("trackingInstallVersion", null) + + private fun pending(): String? = context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).getString("trackingInstallPending", null) + + private fun waitFor(condition: () -> Boolean) { + val deadline = System.currentTimeMillis() + 5000 + while (!condition() && System.currentTimeMillis() < deadline) { + Thread.sleep(10) + } + } + + // A start in a new process: start() does not wait for the install check, so wait for its + // marker and for its send to settle; the marker is written before the send. + private fun start(version: String) { + Tracking.installChecked.set(false) + val before = requests + shadowOf(context.packageManager).getInternalMutablePackageInfo(context.packageName).versionName = version + val tracking = Tracking(analytics, "property") + trackers.add(tracking) + tracking.start() + waitFor { marker() == version && (pending() == null || requests > before) } + Thread.sleep(200) + } + + private fun payload(messageId: String, notification: Boolean = true): String = JSONObject() + .put("messageId", messageId) + .put(if (notification) "notification" else "data", JSONObject().put("title", "Sale")) + .toString() + + @Test + fun firstOpenIsSentOncePerInstall() { + start("1.0.0") + start("1.0.0") + + assertEquals(1, events.size) + assertEquals("first_open", events.single().getString("name")) + assertEquals(false, events.single().getBoolean("interactive")) + } + + @Test + fun concurrentStartsSendOneFirstOpen() { + shadowOf(context.packageManager).getInternalMutablePackageInfo(context.packageName).versionName = "1.0.0" + val first = Tracking(analytics, "property") + val second = Tracking(analytics, "property") + trackers.addAll(listOf(first, second)) + first.start() + second.start() + second.start() + waitFor { marker() == "1.0.0" } + Thread.sleep(300) + + assertEquals(listOf("first_open"), events.map { it.getString("name") }) + } + + @Test + fun aFailedInstallEventIsSentOnTheNextStart() { + failures = 1 + start("1.0.0") + + assertEquals(0, events.size) + assertNotNull(pending()) + + start("1.0.0") + + assertEquals(listOf("first_open"), events.map { it.getString("name") }) + assertNull(pending()) + } + + @Test + fun aPendingEventIsSentOnceAndMovesAStaleMarker() { + context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).edit() + .putString("trackingInstallVersion", "1.0.0") + .putString("trackingInstallPending", "{\"name\":\"first_open\"}") + .commit() + + start("1.1.0") + start("1.1.0") + + assertEquals(listOf("first_open"), events.map { it.getString("name") }) + assertNull(pending()) + } + + @Test + fun aPendingUpdateRetriedOnANewerVersionReportsTheCurrentVersion() { + context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).edit() + .putString("trackingInstallVersion", "1.1.0") + .putString("trackingInstallPending", "{\"name\":\"app_updated\",\"props\":{\"previousVersion\":\"1.0.0\",\"version\":\"1.1.0\"}}") + .commit() + + start("1.2.0") + start("1.2.0") + + assertEquals(listOf("app_updated"), events.map { it.getString("name") }) + assertEquals("[\"previousVersion\",\"1.0.0\",\"version\",\"1.2.0\"]", events.single().getJSONArray("props").toString()) + assertEquals("1.2.0", marker()) + assertNull(pending()) + } + + @Test + fun aRollbackWhileAnUpdateIsPendingSendsNothing() { + context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).edit() + .putString("trackingInstallVersion", "1.1.0") + .putString("trackingInstallPending", "{\"name\":\"app_updated\",\"props\":{\"previousVersion\":\"1.0.0\",\"version\":\"1.1.0\"}}") + .commit() + + start("1.0.0") + start("1.0.0") + + assertEquals(0, events.size) + assertEquals("1.0.0", marker()) + assertNull(pending()) + } + + @Test + fun anInstallThatRanTheSdkBeforeGetsNoFirstOpen() { + context.getSharedPreferences(Client.COOKIE_PREFS, Context.MODE_PRIVATE).edit().putString("cookie", "saved").commit() + + start("1.0.0") + + assertEquals(0, events.size) + assertEquals("1.0.0", marker()) + } + + @Test + fun appUpdatedIsSentOnTheFirstStartOfANewVersion() { + context.getSharedPreferences(Client.GLOBAL_PREFS, Context.MODE_PRIVATE).edit().putString("trackingInstallVersion", "1.0.0").commit() + + start("1.1.0") + start("1.1.0") + + assertEquals(1, events.size) + assertEquals("app_updated", events.single().getString("name")) + assertEquals("[\"previousVersion\",\"1.0.0\",\"version\",\"1.1.0\"]", events.single().getJSONArray("props").toString()) + assertEquals(false, events.single().getBoolean("interactive")) + } + + @Test + fun pushHelpersSendMessageIdAndCampaign() { + val tracking = Tracking(analytics, "property") + tracking.pushReceived(messageId = "message") + tracking.pushOpened(messageId = "message", campaign = "sale") + waitFor { events.size >= 2 } + + val byName = events.associateBy { it.getString("name") } + assertEquals("[\"messageId\",\"message\"]", byName.getValue("push_received").getJSONArray("props").toString()) + assertEquals(false, byName.getValue("push_received").getBoolean("interactive")) + assertEquals("[\"messageId\",\"message\",\"campaign\",\"sale\"]", byName.getValue("push_opened").getJSONArray("props").toString()) + assertEquals(true, byName.getValue("push_opened").getBoolean("interactive")) + } + + @Test + fun pushSendsOneReceivedPerMessageAcrossOverlappingSubscriptions() { + val push = Push(client, context).setTracking(Tracking(analytics, "property")) + push.subscribe(listOf("users/user", "users/#"), background = true) {} + PushBackground.deliverMessage(context, PushMessage("users/user", payload("received").toByteArray(), 1)) { {} } + PushBackground.deliverMessage(context, PushMessage("users/user", payload("silent", notification = false).toByteArray(), 1)) { {} } + waitFor { events.isNotEmpty() } + Thread.sleep(300) + push.close() + + assertEquals(1, events.size) + assertEquals("push_received", events.single().getString("name")) + assertEquals("[\"messageId\",\"received\"]", events.single().getJSONArray("props").toString()) + assertEquals(false, events.single().getBoolean("interactive")) + } + + @Test + fun pushSendsOneOpenedPerTapAcrossListeners() { + val push = Push(client, context).setTracking(Tracking(analytics, "property")) + val stops = listOf(push.onNotificationOpened {}, push.onNotificationOpened {}) + PushTaps.record(PushTap("users/user", payload("listened"))) + stops.forEach { it() } + PushTaps.record(PushTap("users/user", payload("launched"))) + push.getInitialNotification() + waitFor { events.size >= 2 } + Thread.sleep(300) + push.close() + + assertEquals(listOf("push_opened", "push_opened"), events.map { it.getString("name") }) + assertEquals(setOf("[\"messageId\",\"listened\"]", "[\"messageId\",\"launched\"]"), events.map { it.getJSONArray("props").toString() }.toSet()) + assertEquals(true, events.first().getBoolean("interactive")) + } + + @Test + fun screenNamesResolveAgainstTheBaseUrl() { + val tracking = Tracking(analytics, "property") + tracking.screenView("Home Screen", props = mapOf("tab" to null)) + waitFor { events.isNotEmpty() } + + assertEquals("app://android/Home%20Screen", events.single().getString("url")) + assertEquals("[\"screen\",\"Home Screen\"]", events.single().getJSONArray("props").toString()) + } +} diff --git a/library/src/test/java/io/appwrite/services/PushNotificationOpenedTest.kt b/library/src/test/java/io/appwrite/services/PushNotificationOpenedTest.kt new file mode 100644 index 0000000..eddfb2c --- /dev/null +++ b/library/src/test/java/io/appwrite/services/PushNotificationOpenedTest.kt @@ -0,0 +1,25 @@ +package io.appwrite.services + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4::class) +class PushNotificationOpenedTest { + @Test + fun messageIdIsReadFromTheEnvelope() { + val payload = """{"messageId":"message","notification":{"title":"Sale"},"data":{"saleId":"42"}}""" + + val opened = PushNotificationOpened.of(PushTap("users/user", payload)) + + assertEquals("message", opened.messageId) + assertEquals(mapOf("saleId" to "42"), opened.data) + assertNull(PushNotificationOpened.of(PushTap("users/user", "raw")).messageId) + assertNull(PushNotificationOpened.of(PushTap("users/user", "{\"messageId\":\"\"}")).messageId) + assertNull(PushNotificationOpened("users/user", emptyMap()).messageId) + } +}