Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Let the watch change chapters, add bookmarks, set the sleep timer, seek and change speed and volume through the phone, show watch sessions with a watch icon and stop the watch from signing the phone out of BookOrbit

Barnabasc14b348c799a
diff --git a/android/app/src/fdroid/AndroidManifest.xml b/android/app/src/fdroid/AndroidManifest.xml
index b5f772e5..dde25239 100644
--- a/android/app/src/fdroid/AndroidManifest.xml
+++ b/android/app/src/fdroid/AndroidManifest.xml
@@ -27,5 +27,6 @@
<!-- Wear OS Data Layer (GMS) -->
<service android:name=".WearAuthListenerService" tools:node="remove"/>
<service android:name=".WearPlayerCommandListenerService" tools:node="remove"/>
+ <service android:name=".WearSessionListenerService" tools:node="remove"/>
</application>
</manifest>
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/BookOrbitSessionRenewer.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/BookOrbitSessionRenewer.kt
new file mode 100644
index 00000000..cf81c89e
--- /dev/null
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/BookOrbitSessionRenewer.kt
@@ -0,0 +1,138 @@
+package com.barnabas.absorb
+
+import android.content.SharedPreferences
+import android.util.Base64
+import android.util.Log
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+
+/**
+ * Renews the phone's BookOrbit session when the watch asks for a fresh token.
+ *
+ * The phone and the watch share one BookOrbit session, and BookOrbit ends the
+ * whole session when a refresh token it already swapped is sent again more
+ * than 30 seconds later. So the watch never spends that token itself: it asks
+ * the phone, and the phone renews it here from the stored pair, the same one
+ * every refresh in the app reads right before it goes out.
+ */
+object BookOrbitSessionRenewer {
+ private const val TAG = "WearAuthBridge"
+ private const val WEB_REFRESH_PREFIX = "web:"
+
+ /** Wider than the watch's own minute of headroom, so a watch that finds
+ * its token about to run out always gets a renewed one back. */
+ private const val RENEW_WITHIN_MS = 3 * 60_000L
+
+ private val lock = Any()
+ private val refreshCookie = Regex("refresh_token=([^;,\\s]+)")
+
+ /** Renews the stored BookOrbit pair when its access token runs out within
+ * a few minutes. Blocks on the network, so call it off the main thread. */
+ fun renewIfExpiring(prefs: SharedPreferences) {
+ synchronized(lock) {
+ if (prefs.getString("flutter.server_backend", null) != "bookorbit") return
+ val access = prefs.getString("flutter.token", null) ?: return
+ val refresh = prefs.getString("flutter.refresh_token", null) ?: return
+ val expiresAt = jwtExpiryMillis(access) ?: return
+ if (System.currentTimeMillis() + RENEW_WITHIN_MS < expiresAt) return
+ val server = prefs.getString("flutter.server_url", null)?.trimEnd('/') ?: return
+ val username = prefs.getString("flutter.username", null)
+
+ val renewed = send(server, refresh, customHeaders(prefs)) ?: return
+
+ // Something else in the app renewed it while this was out. Within
+ // BookOrbit's grace both got the same pair back; past it, theirs
+ // is the newer one. Either way, keep what is stored.
+ if (prefs.getString("flutter.refresh_token", null) != refresh ||
+ prefs.getString("flutter.server_url", null)?.trimEnd('/') != server ||
+ prefs.getString("flutter.username", null) != username
+ ) {
+ Log.i(TAG, "BookOrbit session was renewed elsewhere meanwhile; keeping the stored pair")
+ return
+ }
+ val saved = prefs.edit()
+ .putString("flutter.refresh_token", renewed.second)
+ .putString("flutter.token", renewed.first)
+ .putLong("flutter.token_saved_at", System.currentTimeMillis())
+ .putBoolean("flutter.wear_token_pair_pending", true)
+ .commit()
+ if (saved) Log.i(TAG, "Renewed the BookOrbit session for the watch")
+ else Log.w(TAG, "Renewed the BookOrbit session but could not store it")
+ }
+ }
+
+ /** The renewed access and refresh tokens, or null when BookOrbit could
+ * not be reached or turned the token down. */
+ private fun send(server: String, refresh: String, headers: Map<String, String>): Pair<String, String>? {
+ val webSession = refresh.startsWith(WEB_REFRESH_PREFIX)
+ val conn = try {
+ (URL("$server/api/v1/auth/refresh").openConnection() as HttpURLConnection).apply {
+ requestMethod = "POST"
+ connectTimeout = 10_000
+ readTimeout = 15_000
+ doOutput = true
+ setRequestProperty("Accept", "application/json")
+ setRequestProperty("Content-Type", "application/json")
+ setRequestProperty("User-Agent", "Absorb/${BuildConfig.VERSION_NAME}")
+ headers.forEach { (k, v) -> setRequestProperty(k, v) }
+ if (webSession) {
+ setRequestProperty("Cookie", "refresh_token=" + refresh.removePrefix(WEB_REFRESH_PREFIX))
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "BookOrbit renewal: cannot open connection", e)
+ return null
+ }
+ return try {
+ val body = if (webSession) "{}" else JSONObject().put("refreshToken", refresh).toString()
+ conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
+ val code = conn.responseCode
+ if (code !in 200..299) {
+ Log.w(TAG, "BookOrbit renewal turned down: HTTP $code")
+ return null
+ }
+ val json = JSONObject(conn.inputStream.bufferedReader().use { it.readText() })
+ val user = json.optJSONObject("user")
+ val access = user?.optString("accessToken")?.takeIf { it.isNotEmpty() }
+ ?: json.optString("accessToken").takeIf { it.isNotEmpty() }
+ ?: return null
+ val next = if (webSession) {
+ conn.headerFields["Set-Cookie"]
+ ?.firstNotNullOfOrNull { refreshCookie.find(it)?.groupValues?.get(1) }
+ ?.let { WEB_REFRESH_PREFIX + it }
+ } else {
+ user?.optString("refreshToken")?.takeIf { it.isNotEmpty() }
+ ?: json.optString("refreshToken").takeIf { it.isNotEmpty() }
+ }
+ access to (next ?: refresh)
+ } catch (e: Exception) {
+ Log.w(TAG, "BookOrbit renewal failed", e)
+ null
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ private fun customHeaders(prefs: SharedPreferences): Map<String, String> {
+ val raw = prefs.getString("flutter.custom_headers", null) ?: return emptyMap()
+ return try {
+ val obj = JSONObject(raw)
+ obj.keys().asSequence().associateWith { obj.optString(it) }
+ } catch (_: Exception) {
+ emptyMap()
+ }
+ }
+
+ /** Epoch millis stamped in a JWT's `exp`, or null when the token isn't one. */
+ private fun jwtExpiryMillis(token: String): Long? {
+ val parts = token.split('.')
+ if (parts.size != 3) return null
+ return try {
+ val payload = String(Base64.decode(parts[1], Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP))
+ JSONObject(payload).optLong("exp", 0L).takeIf { it > 0L }?.times(1000)
+ } catch (_: Exception) {
+ null
+ }
+ }
+}
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/PlatformIntegration.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/PlatformIntegration.kt
index f7af4c76..8b0e76eb 100644
--- a/android/app/src/gms/kotlin/com/barnabas/absorb/PlatformIntegration.kt
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/PlatformIntegration.kt
@@ -33,9 +33,19 @@ object PlatformIntegration {
// Bridge ABS playback state to the watch so it can render Now
// Playing without making its own API calls.
- MethodChannel(messenger, "com.barnabas.absorb/wear_player")
+ val wearPlayer = MethodChannel(messenger, "com.barnabas.absorb/wear_player")
+ WearPlayerBridge.channel = wearPlayer
+ wearPlayer
.setMethodCallHandler { call, result ->
when (call.method) {
+ "publishChapters" -> {
+ val itemId = call.argument<String>("itemId")
+ val chapters = call.argument<String>("chapters")
+ if (itemId != null && chapters != null) {
+ WearPlayerBridge.publishChapters(activity.applicationContext, itemId, chapters)
+ }
+ result.success(true)
+ }
"publish" -> {
WearPlayerBridge.publish(
context = activity.applicationContext,
@@ -50,6 +60,24 @@ object PlatformIntegration {
speed = (call.argument<Number>("speed") ?: 1.0).toFloat(),
skipBackSec = (call.argument<Number>("skipBackSec") ?: 10).toInt(),
skipForwardSec = (call.argument<Number>("skipForwardSec") ?: 30).toInt(),
+ chapterStartMs = (call.argument<Number>("chapterStartMs") ?: 0).toLong(),
+ chapterEndMs = (call.argument<Number>("chapterEndMs") ?: 0).toLong(),
+ autoRewindEnabled = call.argument<Boolean>("autoRewindEnabled") ?: true,
+ autoRewindMinSec = (call.argument<Number>("autoRewindMinSec") ?: 1.0).toDouble(),
+ autoRewindMaxSec = (call.argument<Number>("autoRewindMaxSec") ?: 30.0).toDouble(),
+ autoRewindDelaySec = (call.argument<Number>("autoRewindDelaySec") ?: 0.0).toDouble(),
+ autoRewindChapterBarrier = call.argument<Boolean>("autoRewindChapterBarrier") ?: false,
+ autoRewindSessionStart = call.argument<Boolean>("autoRewindSessionStart") ?: false,
+ skipChapterBarrier = call.argument<Boolean>("skipChapterBarrier") ?: true,
+ speedAdjustedTime = call.argument<Boolean>("speedAdjustedTime") ?: true,
+ chapterIndex = (call.argument<Number>("chapterIndex") ?: -1).toInt(),
+ chapterCount = (call.argument<Number>("chapterCount") ?: 0).toInt(),
+ sleepMode = call.argument<String>("sleepMode"),
+ sleepEndsAtMs = (call.argument<Number>("sleepEndsAtMs") ?: 0).toLong(),
+ sleepChaptersLeft = (call.argument<Number>("sleepChaptersLeft") ?: 0).toInt(),
+ sleepAddMinutes = (call.argument<Number>("sleepAddMinutes") ?: 5).toInt(),
+ speedPresets = call.argument<List<Number>>("speedPresets")?.map { it.toFloat() } ?: emptyList(),
+ themeColor = (call.argument<Number>("themeColor") ?: 0).toLong(),
)
result.success(true)
}
@@ -84,6 +112,7 @@ object PlatformIntegration {
isLegacyToken = call.argument<Boolean>("isLegacyToken") ?: false,
customHeaders = headers,
supportsTokenReturn = call.argument<Boolean>("supportsTokenReturn") ?: false,
+ backend = call.argument<String>("backend") ?: "abs",
)
result.success(true)
}
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthBridge.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthBridge.kt
index 303cdfd6..eb47c48f 100644
--- a/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthBridge.kt
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthBridge.kt
@@ -47,6 +47,7 @@ object WearAuthBridge {
isLegacyToken: Boolean,
customHeaders: Map<String, String> = emptyMap(),
supportsTokenReturn: Boolean = false,
+ backend: String = "abs",
) {
scope.launch {
try {
@@ -64,6 +65,7 @@ object WearAuthBridge {
put("customHeaders", headersJson)
put("source", "phone")
put("supportsTokenReturn", supportsTokenReturn)
+ put("backend", backend)
put("issuedAt", now)
}.toString()
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthListenerService.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthListenerService.kt
index fdd54fae..996bfe14 100644
--- a/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthListenerService.kt
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/WearAuthListenerService.kt
@@ -11,8 +11,9 @@ import org.json.JSONObject
*
* The watch sends two paths:
* - /absorb/auth/request — sent on watch cold start when no credentials
- * are cached. We respond by republishing the current session from
- * Flutter SharedPreferences.
+ * are cached, and on BookOrbit whenever the watch's token is about to run
+ * out. We respond by republishing the current session from Flutter
+ * SharedPreferences, renewing a BookOrbit one first when it needs it.
* - /absorb/auth/signout — sent when the user signs out from the watch.
* We wipe the published DataItem so the watch stays signed-out even
* after Play Services resyncs.
@@ -26,7 +27,12 @@ class WearAuthListenerService : WearableListenerService() {
override fun onMessageReceived(event: MessageEvent) {
when (event.path) {
- WearAuthBridge.AUTH_REQUEST_PATH -> republishFromStoredPrefs()
+ WearAuthBridge.AUTH_REQUEST_PATH -> {
+ BookOrbitSessionRenewer.renewIfExpiring(
+ applicationContext.getSharedPreferences(FLUTTER_PREFS_FILE, Context.MODE_PRIVATE),
+ )
+ republishFromStoredPrefs()
+ }
WearAuthBridge.AUTH_SIGN_OUT_PATH -> WearAuthBridge.clear(applicationContext)
WearAuthBridge.AUTH_ROTATED_PATH -> adoptRotatedTokens(event.data)
else -> super.onMessageReceived(event)
@@ -89,6 +95,9 @@ class WearAuthListenerService : WearableListenerService() {
val refreshToken = prefs.getString("flutter.refresh_token", null)
val username = prefs.getString("flutter.username", null) ?: ""
val userId = prefs.getString("flutter.user_id", null)
+ // Which kind of server the session is on; the watch needs it to
+ // pick its routes. Stored by ServerBackend.saveActive on the Dart side.
+ val backend = prefs.getString("flutter.server_backend", null) ?: "abs"
// AuthProvider treats absence of refresh_token as a legacy/API-key
// session; mirror that heuristic here so the watch knows not to
// try the refresh endpoint.
@@ -117,6 +126,7 @@ class WearAuthListenerService : WearableListenerService() {
isLegacyToken = isLegacy,
customHeaders = headers,
supportsTokenReturn = true,
+ backend = backend,
)
}
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerBridge.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerBridge.kt
index 775403b8..b8c4e8fc 100644
--- a/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerBridge.kt
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerBridge.kt
@@ -1,14 +1,18 @@
package com.barnabas.absorb
import android.content.Context
+import android.os.Handler
+import android.os.Looper
import android.util.Log
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.Wearable
+import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
+import org.json.JSONArray
import org.json.JSONObject
/**
@@ -25,11 +29,18 @@ object WearPlayerBridge {
private const val TAG = "WearPlayerBridge"
const val STATE_PATH = "/absorb/player/state/v1"
+ const val CHAPTERS_PATH = "/absorb/player/chapters/v1"
private const val KEY_PAYLOAD = "payload"
private const val KEY_ISSUED_AT = "issuedAt"
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val main = Handler(Looper.getMainLooper())
+
+ /** The Dart side's channel while the engine is up; the watch's extra
+ * actions (chapters, bookmark, sleep timer, seek) go through it. */
+ @Volatile
+ var channel: MethodChannel? = null
/** Push the current playback snapshot. Call from the same throttle
* loop that updates the home widget — anything finer-grained than
@@ -47,6 +58,24 @@ object WearPlayerBridge {
speed: Float,
skipBackSec: Int,
skipForwardSec: Int,
+ chapterStartMs: Long = 0L,
+ chapterEndMs: Long = 0L,
+ autoRewindEnabled: Boolean = true,
+ autoRewindMinSec: Double = 1.0,
+ autoRewindMaxSec: Double = 30.0,
+ autoRewindDelaySec: Double = 0.0,
+ autoRewindChapterBarrier: Boolean = false,
+ autoRewindSessionStart: Boolean = false,
+ skipChapterBarrier: Boolean = true,
+ speedAdjustedTime: Boolean = true,
+ chapterIndex: Int = -1,
+ chapterCount: Int = 0,
+ sleepMode: String? = null,
+ sleepEndsAtMs: Long = 0L,
+ sleepChaptersLeft: Int = 0,
+ sleepAddMinutes: Int = 5,
+ speedPresets: List<Float> = emptyList(),
+ themeColor: Long = 0L,
) {
scope.launch {
try {
@@ -63,6 +92,26 @@ object WearPlayerBridge {
put("speed", speed.toDouble())
put("skipBackSec", skipBackSec)
put("skipForwardSec", skipForwardSec)
+ put("chapterStartMs", chapterStartMs)
+ put("chapterEndMs", chapterEndMs)
+ // The playback settings the watch copies, so a book sounds
+ // the same from either device.
+ put("autoRewindEnabled", autoRewindEnabled)
+ put("autoRewindMinSec", autoRewindMinSec)
+ put("autoRewindMaxSec", autoRewindMaxSec)
+ put("autoRewindDelaySec", autoRewindDelaySec)
+ put("autoRewindChapterBarrier", autoRewindChapterBarrier)
+ put("autoRewindSessionStart", autoRewindSessionStart)
+ put("skipChapterBarrier", skipChapterBarrier)
+ put("speedAdjustedTime", speedAdjustedTime)
+ put("chapterIndex", chapterIndex)
+ put("chapterCount", chapterCount)
+ put("sleepMode", sleepMode ?: JSONObject.NULL)
+ put("sleepEndsAtMs", sleepEndsAtMs)
+ put("sleepChaptersLeft", sleepChaptersLeft)
+ put("sleepAddMinutes", sleepAddMinutes)
+ put("speedPresets", JSONArray().apply { for (p in speedPresets) put(p.toDouble()) })
+ put("themeColor", themeColor)
put("issuedAt", now)
}.toString()
@@ -80,4 +129,40 @@ object WearPlayerBridge {
}
}
}
+
+ /** The playing book's chapter list, once per book, for the watch's
+ * chapter page. [chaptersJson] is a JSON array of
+ * `{"title","start","end"}` with seconds. */
+ fun publishChapters(context: Context, itemId: String, chaptersJson: String) {
+ scope.launch {
+ try {
+ val payload = JSONObject().apply {
+ put("itemId", itemId)
+ put("chapters", JSONArray(chaptersJson))
+ }.toString()
+ val request = PutDataMapRequest.create(CHAPTERS_PATH).apply {
+ dataMap.putByteArray(KEY_PAYLOAD, payload.toByteArray(Charsets.UTF_8))
+ dataMap.putLong(KEY_ISSUED_AT, System.currentTimeMillis())
+ }.asPutDataRequest().setUrgent()
+ Wearable.getDataClient(context.applicationContext).putDataItem(request).await()
+ Log.i(TAG, "published chapters for $itemId")
+ } catch (e: Exception) {
+ Log.w(TAG, "Failed to publish chapters", e)
+ }
+ }
+ }
+
+ /** Hands a watch command to the Dart player. False when the Flutter
+ * engine is not up, so the caller can wake the app instead. */
+ fun command(name: String, args: Map<String, Any?> = emptyMap()): Boolean {
+ val ch = channel ?: return false
+ main.post {
+ try {
+ ch.invokeMethod("command", HashMap<String, Any?>(args).apply { put("name", name) })
+ } catch (e: Exception) {
+ Log.w(TAG, "command $name failed", e)
+ }
+ }
+ return true
+ }
}
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt
index acbd52fb..09a4b6bf 100644
--- a/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt
@@ -3,21 +3,26 @@ package com.barnabas.absorb
import android.content.ComponentName
import android.content.Context
import android.content.Intent
+import android.media.AudioManager
import android.net.Uri
import android.util.Log
import android.view.KeyEvent
import com.google.android.gms.wearable.MessageEvent
+import com.google.android.gms.wearable.Wearable
import com.google.android.gms.wearable.WearableListenerService
import org.json.JSONObject
/**
* Phone-side receiver for playback commands from the AbsorbWear watch.
*
- * Two flavours:
+ * Three flavours:
* - play-pause / skip-back / skip-forward: forwarded to the active
* MediaSession as a MEDIA_BUTTON broadcast. Same code path Bluetooth
* headphones and the NowPlayingWidget already use, so we get
* user-configured skip durations for free.
+ * - next-chapter / prev-chapter / bookmark / sleep / seek / speed: handed to the
+ * Dart player over the wear_player channel while the app is up; when it
+ * is not, the app is woken with the same request as a widget-style URI.
* - play-item: launches MainActivity with a URI the home_widget plugin
* can route. Flutter's HomeWidgetService picks it up and calls
* AudioPlayerService.playItem unconditionally (replacing any current
@@ -31,10 +36,44 @@ class WearPlayerCommandListenerService : WearableListenerService() {
"/absorb/player/cmd/skip-back" -> dispatchMediaButton(KeyEvent.KEYCODE_MEDIA_REWIND)
"/absorb/player/cmd/skip-forward" -> dispatchMediaButton(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD)
"/absorb/player/cmd/play-item" -> handlePlayItem(event.data)
+ "/absorb/player/cmd/volume-up" -> adjustVolume(AudioManager.ADJUST_RAISE, event.sourceNodeId)
+ "/absorb/player/cmd/volume-down" -> adjustVolume(AudioManager.ADJUST_LOWER, event.sourceNodeId)
+ "/absorb/player/cmd/volume-get" -> adjustVolume(AudioManager.ADJUST_SAME, event.sourceNodeId)
+ "/absorb/player/cmd/next-chapter" -> command("next_chapter")
+ "/absorb/player/cmd/prev-chapter" -> command("prev_chapter")
+ "/absorb/player/cmd/bookmark" -> command("bookmark")
+ "/absorb/player/cmd/stop" -> command("stop")
+ "/absorb/player/cmd/sleep" -> command("sleep", jsonArgs(event.data))
+ "/absorb/player/cmd/seek" -> command("seek", jsonArgs(event.data))
+ "/absorb/player/cmd/speed" -> command("speed", jsonArgs(event.data))
else -> super.onMessageReceived(event)
}
}
+ private fun jsonArgs(data: ByteArray): Map<String, Any?> {
+ if (data.isEmpty()) return emptyMap()
+ return try {
+ val obj = JSONObject(data.decodeToString())
+ obj.keys().asSequence().associateWith { obj.get(it) }
+ } catch (e: Exception) {
+ Log.w(TAG, "command payload not JSON", e)
+ emptyMap()
+ }
+ }
+
+ // The Dart player takes it straight away while the app is up; otherwise
+ // the app is started with the request, the way play-item is.
+ private fun command(name: String, args: Map<String, Any?> = emptyMap()) {
+ Log.i(TAG, "Watch -> $name $args")
+ if (WearPlayerBridge.command(name, args)) return
+ val builder = Uri.Builder()
+ .scheme("absorb")
+ .authority("widget")
+ .appendPath(name)
+ for ((k, v) in args) if (v != null) builder.appendQueryParameter(k, v.toString())
+ launch(builder.build())
+ }
+
private fun dispatchMediaButton(keyCode: Int) {
Log.i(TAG, "Watch -> MediaButton keyCode=$keyCode")
val intent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {
@@ -50,6 +89,24 @@ class WearPlayerCommandListenerService : WearableListenerService() {
applicationContext.sendBroadcast(intent)
}
+ // The watch's crown, turned on its phone-remote screen: one step of
+ // the media volume per message, with the system's own volume panel,
+ // and the new level sent back so the watch can draw it.
+ private fun adjustVolume(direction: Int, replyTo: String) {
+ val audio = applicationContext.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return
+ Log.i(TAG, "Watch -> volume direction=$direction")
+ if (direction != AudioManager.ADJUST_SAME) {
+ audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, AudioManager.FLAG_SHOW_UI)
+ }
+ val level = JSONObject()
+ .put("index", audio.getStreamVolume(AudioManager.STREAM_MUSIC))
+ .put("max", audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC))
+ .toString()
+ Wearable.getMessageClient(applicationContext)
+ .sendMessage(replyTo, "/absorb/player/volume", level.toByteArray(Charsets.UTF_8))
+ .addOnFailureListener { Log.w(TAG, "volume reply to $replyTo failed", it) }
+ }
+
private fun handlePlayItem(data: ByteArray) {
val payload = try {
JSONObject(data.decodeToString())
@@ -72,18 +129,20 @@ class WearPlayerCommandListenerService : WearableListenerService() {
.appendPath("play_item")
.appendQueryParameter("itemId", itemId)
if (episodeId != null) builder.appendQueryParameter("episodeId", episodeId)
- val uri = builder.build()
+ launch(builder.build())
+ }
+ private fun launch(uri: Uri) {
val intent = Intent(applicationContext, MainActivity::class.java).apply {
action = HOME_WIDGET_CLICK
this.data = uri
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
- Log.i(TAG, "Watch -> play-item uri=$uri")
+ Log.i(TAG, "Watch -> launch uri=$uri")
try {
applicationContext.startActivity(intent)
} catch (e: Exception) {
- Log.w(TAG, "Failed to launch MainActivity for play-item", e)
+ Log.w(TAG, "Failed to launch MainActivity for $uri", e)
}
}
diff --git a/android/app/src/gms/kotlin/com/barnabas/absorb/WearSessionListenerService.kt b/android/app/src/gms/kotlin/com/barnabas/absorb/WearSessionListenerService.kt
new file mode 100644
index 00000000..c8363c9e
--- /dev/null
+++ b/android/app/src/gms/kotlin/com/barnabas/absorb/WearSessionListenerService.kt
@@ -0,0 +1,63 @@
+package com.barnabas.absorb
+
+import android.content.Context
+import android.util.Log
+import com.google.android.gms.wearable.DataEvent
+import com.google.android.gms.wearable.DataEventBuffer
+import com.google.android.gms.wearable.DataMapItem
+import com.google.android.gms.wearable.WearableListenerService
+import org.json.JSONObject
+
+/**
+ * Takes the list of BookOrbit listening sessions the AbsorbWear watch has
+ * recorded and files them beside the ones this phone recorded, so the
+ * Stats screen can show them with the watch icon. BookOrbit keeps no
+ * device on a session, so both lists live in Flutter's shared
+ * preferences, keyed `bookId@startedAt` the way BookOrbitApiService keys
+ * its own; the Dart side reads this one as the watch's.
+ */
+class WearSessionListenerService : WearableListenerService() {
+
+ override fun onDataChanged(buffer: DataEventBuffer) {
+ for (event in buffer) {
+ if (event.type != DataEvent.TYPE_CHANGED || event.dataItem.uri.path != SESSIONS_PATH) continue
+ val bytes = DataMapItem.fromDataItem(event.dataItem).dataMap.getByteArray("payload") ?: continue
+ adopt(bytes)
+ }
+ }
+
+ private fun adopt(bytes: ByteArray) {
+ val payload = try {
+ JSONObject(bytes.toString(Charsets.UTF_8))
+ } catch (e: Exception) {
+ Log.w(TAG, "watch session list not JSON", e)
+ return
+ }
+ val device = payload.optString("device").ifBlank { "Wear OS watch" }
+ val sessions = payload.optJSONArray("sessions") ?: return
+ val prefs = applicationContext.getSharedPreferences(FLUTTER_PREFS_FILE, Context.MODE_PRIVATE)
+ val known = prefs.getString(WATCH_SESSIONS_KEY, null)
+ ?.let { raw -> try { JSONObject(raw) } catch (_: Exception) { null } }
+ ?: JSONObject()
+ var added = 0
+ for (i in 0 until sessions.length()) {
+ val s = sessions.optJSONObject(i) ?: continue
+ val bookId = s.optString("bookId")
+ val startedAt = s.optString("startedAt")
+ if (bookId.isEmpty() || startedAt.isEmpty()) continue
+ val key = "$bookId@$startedAt"
+ if (!known.has(key)) added++
+ known.put(key, device)
+ }
+ while (known.length() > 500) known.remove(known.keys().next())
+ prefs.edit().putString(WATCH_SESSIONS_KEY, known.toString()).apply()
+ Log.i(TAG, "Watch -> ${sessions.length()} BookOrbit sessions ($added new) from $device")
+ }
+
+ companion object {
+ private const val TAG = "WearPlayerBridge"
+ private const val SESSIONS_PATH = "/absorb/player/sessions/v1"
+ private const val FLUTTER_PREFS_FILE = "FlutterSharedPreferences"
+ private const val WATCH_SESSIONS_KEY = "flutter.bookorbit_watch_sessions"
+ }
+}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 171569ad..840d8a67 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -240,6 +240,20 @@
</intent-filter>
</service>
+ <!-- The watch names the BookOrbit listening sessions it recorded, so
+ the Stats screen can show them with the watch icon. -->
+ <service
+ android:name=".WearSessionListenerService"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
+ <data
+ android:scheme="wear"
+ android:host="*"
+ android:pathPrefix="/absorb/player/sessions" />
+ </intent-filter>
+ </service>
+
</application>
<queries>
diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dart
index b11dba9f..7f5c5849 100644
--- a/lib/screens/admin_users_screen.dart
+++ b/lib/screens/admin_users_screen.dart
@@ -697,6 +697,7 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {
final deviceInfo = s['deviceInfo'] as Map<String, dynamic>? ?? {};
final clientName = deviceInfo['clientName'] as String? ?? deviceInfo['deviceName'] as String? ?? '';
final isAbsorb = clientName.toLowerCase().contains('absorb');
+ final isWear = isAbsorb && clientName.toLowerCase().contains('wear');
return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),
@@ -716,7 +717,9 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {
borderRadius: BorderRadius.circular(8),
),
child: Center(
- child: isAbsorb
+ child: isWear
+ ? AbsorbWatchIcon(size: 18, color: Colors.tealAccent.withValues(alpha: 0.7))
+ : isAbsorb
? AbsorbWaveIcon(size: 16, color: Colors.tealAccent.withValues(alpha: 0.7))
: Icon(_clientIcon(clientName), size: 15, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
),
diff --git a/lib/services/wear_auth_service.dart b/lib/services/wear_auth_service.dart
index 440d2d53..91230787 100644
--- a/lib/services/wear_auth_service.dart
+++ b/lib/services/wear_auth_service.dart
@@ -32,11 +32,13 @@ class WearAuthService {
required bool isLegacyToken,
Map<String, String> customHeaders = const {},
bool supportsTokenReturn = false,
+ String backend = 'abs',
}) async {
if (!_supported) return;
try {
await _channel.invokeMethod<void>('publish', {
'serverUrl': serverUrl,
+ 'backend': backend,
'accessToken': accessToken,
'refreshToken': refreshToken,
'username': username,
diff --git a/lib/services/wear_player_service.dart b/lib/services/wear_player_service.dart
index a96e7341..e1223c4d 100644
--- a/lib/services/wear_player_service.dart
+++ b/lib/services/wear_player_service.dart
@@ -1,6 +1,9 @@
+import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
+import 'audio_player_service.dart';
+import 'sleep_timer_service.dart';
/// Pushes the active playback snapshot to the paired Wear OS companion
/// (AbsorbWear) via the Wearable Data Layer.
@@ -18,6 +21,51 @@ class WearPlayerService {
bool get _supported => !kIsWeb && Platform.isAndroid;
+ bool _listening = false;
+ String? _chaptersPublishedFor;
+
+ /// Start taking the watch's extra actions (chapter skips, bookmark, sleep
+ /// timer, seek). Safe to call more than once.
+ void listen() {
+ if (!_supported || _listening) return;
+ _listening = true;
+ _channel.setMethodCallHandler((call) async {
+ if (call.method != 'command') return null;
+ final args = Map<String, dynamic>.from(call.arguments as Map);
+ await WearCommands.handle(args['name'] as String? ?? '', args);
+ return true;
+ });
+ }
+
+ /// The playing book's chapter list, sent once per book so the watch can
+ /// show and jump between chapters while the phone plays.
+ Future<void> publishChapters(String? itemId, List<dynamic> chapters) async {
+ if (!_supported) return;
+ if (itemId == null) {
+ _chaptersPublishedFor = null;
+ return;
+ }
+ if (_chaptersPublishedFor == itemId) return;
+ _chaptersPublishedFor = itemId;
+ final list = <Map<String, dynamic>>[];
+ for (final c in chapters) {
+ if (c is! Map) continue;
+ list.add({
+ 'title': c['title']?.toString() ?? '',
+ 'start': (c['start'] as num?)?.toDouble() ?? 0.0,
+ 'end': (c['end'] as num?)?.toDouble() ?? 0.0,
+ });
+ }
+ try {
+ await _channel.invokeMethod<void>('publishChapters', {
+ 'itemId': itemId,
+ 'chapters': jsonEncode(list),
+ });
+ } catch (e) {
+ debugPrint('[WearPlayer] publishChapters failed: $e');
+ }
+ }
+
Future<void> publish({
required bool hasBook,
String? itemId,
@@ -30,6 +78,24 @@ class WearPlayerService {
required double speed,
required int skipBackSec,
required int skipForwardSec,
+ int chapterStartMs = 0,
+ int chapterEndMs = 0,
+ bool autoRewindEnabled = true,
+ double autoRewindMinSec = 1.0,
+ double autoRewindMaxSec = 30.0,
+ double autoRewindDelaySec = 0.0,
+ bool autoRewindChapterBarrier = false,
+ bool autoRewindSessionStart = false,
+ bool skipChapterBarrier = true,
+ bool speedAdjustedTime = true,
+ int chapterIndex = -1,
+ int chapterCount = 0,
+ String? sleepMode,
+ int sleepEndsAtMs = 0,
+ int sleepChaptersLeft = 0,
+ int sleepAddMinutes = 5,
+ List<double> speedPresets = const [],
+ int themeColor = 0,
}) async {
if (!_supported) return;
try {
@@ -45,9 +111,90 @@ class WearPlayerService {
'speed': speed,
'skipBackSec': skipBackSec,
'skipForwardSec': skipForwardSec,
+ 'chapterStartMs': chapterStartMs,
+ 'chapterEndMs': chapterEndMs,
+ 'autoRewindEnabled': autoRewindEnabled,
+ 'autoRewindMinSec': autoRewindMinSec,
+ 'autoRewindMaxSec': autoRewindMaxSec,
+ 'autoRewindDelaySec': autoRewindDelaySec,
+ 'autoRewindChapterBarrier': autoRewindChapterBarrier,
+ 'autoRewindSessionStart': autoRewindSessionStart,
+ 'skipChapterBarrier': skipChapterBarrier,
+ 'speedAdjustedTime': speedAdjustedTime,
+ 'chapterIndex': chapterIndex,
+ 'chapterCount': chapterCount,
+ 'sleepMode': sleepMode,
+ 'sleepEndsAtMs': sleepEndsAtMs,
+ 'sleepChaptersLeft': sleepChaptersLeft,
+ 'sleepAddMinutes': sleepAddMinutes,
+ 'speedPresets': speedPresets,
+ 'themeColor': themeColor,
});
} catch (e) {
debugPrint('[WearPlayer] publish failed: $e');
}
}
}
+
+/// The watch's extra player actions, the same whether they arrive over the
+/// wear_player channel (app up) or as a widget-style launch URI (app woken
+/// for them).
+class WearCommands {
+ WearCommands._();
+
+ static Future<void> handle(String name, Map<String, dynamic> args) async {
+ debugPrint('[WearPlayer] command $name $args');
+ final player = AudioPlayerService();
+ switch (name) {
+ case 'next_chapter':
+ if (player.hasBook) await player.skipToNextChapter();
+ break;
+ case 'prev_chapter':
+ if (player.hasBook) await player.skipToPreviousChapter();
+ break;
+ case 'bookmark':
+ if (player.hasBook) await AudioPlayerService.handler?.customAction('bookmark');
+ break;
+ case 'stop':
+ if (player.hasBook) await player.stop();
+ break;
+ case 'speed':
+ final speed = _double(args['speed']);
+ if (player.hasBook && speed != null && speed > 0) await player.setSpeed(speed);
+ break;
+ case 'seek':
+ final ms = _int(args['positionMs']);
+ if (player.hasBook && ms != null) {
+ await player.seekTo(Duration(milliseconds: ms), logDetail: 'watch');
+ }
+ break;
+ case 'sleep':
+ final sleep = SleepTimerService();
+ final minutes = _int(args['minutes']);
+ final chapters = _int(args['chapters']);
+ final add = _int(args['add']);
+ if (args['cancel'] == true || args['cancel'] == 'true') {
+ sleep.cancel();
+ } else if (minutes != null && minutes > 0) {
+ sleep.setTimeSleep(Duration(minutes: minutes));
+ } else if (chapters != null && chapters > 0) {
+ sleep.setChapterSleep(chapters);
+ } else if (add != null && add > 0) {
+ sleep.addTime(Duration(minutes: add));
+ }
+ break;
+ }
+ }
+
+ static int? _int(Object? v) {
+ if (v == null) return null;
+ if (v is num) return v.toInt();
+ return int.tryParse(v.toString());
+ }
+
+ static double? _double(Object? v) {
+ if (v == null) return null;
+ if (v is num) return v.toDouble();
+ return double.tryParse(v.toString());
+ }
+}
diff --git a/lib/widgets/absorb_wave_icon.dart b/lib/widgets/absorb_wave_icon.dart
index c0080b66..9189c31a 100644
--- a/lib/widgets/absorb_wave_icon.dart
+++ b/lib/widgets/absorb_wave_icon.dart
@@ -52,6 +52,84 @@ class _AbsorbWavePainter extends CustomPainter {
bool shouldRepaint(_AbsorbWavePainter old) => old.color != color;
}
+/// The wave on a watch face, with the band stubs above and below - for a
+/// session that came from the Wear OS app.
+class AbsorbWatchIcon extends StatelessWidget {
+ final double size;
+ final Color? color;
+
+ const AbsorbWatchIcon({super.key, this.size = 24, this.color});
+
+ @override
+ Widget build(BuildContext context) {
+ final c = color ?? Theme.of(context).colorScheme.primary;
+ return CustomPaint(
+ size: Size(size, size),
+ painter: _AbsorbWatchPainter(color: c),
+ );
+ }
+}
+
+class _AbsorbWatchPainter extends CustomPainter {
+ final Color color;
+
+ _AbsorbWatchPainter({required this.color});
+
+ static const _barHeights = [0.35, 0.6, 1.0, 0.6, 0.35];
+ static const _barCount = 5;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final s = size.width;
+ final center = Offset(s / 2, size.height / 2);
+ final strokeW = s * 0.07;
+
+ // The band: two rounded stubs the face sits between.
+ final bandPaint = Paint()..color = color;
+ final bandW = s * 0.34;
+ final bandH = s * 0.13;
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ Rect.fromCenter(center: Offset(center.dx, s * 0.10), width: bandW, height: bandH),
+ Radius.circular(bandH / 2),
+ ),
+ bandPaint,
+ );
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ Rect.fromCenter(center: Offset(center.dx, s * 0.90), width: bandW, height: bandH),
+ Radius.circular(bandH / 2),
+ ),
+ bandPaint,
+ );
+
+ // The round face.
+ final facePaint = Paint()
+ ..color = color
+ ..strokeWidth = strokeW
+ ..style = PaintingStyle.stroke;
+ canvas.drawCircle(center, s * 0.33, facePaint);
+
+ // The wave, small enough to sit inside the face.
+ final barPaint = Paint()
+ ..color = color
+ ..strokeWidth = strokeW * 0.8
+ ..strokeCap = StrokeCap.round;
+ final totalWidth = s * 0.34;
+ final startX = (s - totalWidth) / 2;
+ final spacing = totalWidth / (_barCount - 1);
+ final maxHalf = s * 0.19;
+ for (int i = 0; i < _barCount; i++) {
+ final x = startX + spacing * i;
+ final half = maxHalf * _barHeights[i];
+ canvas.drawLine(Offset(x, center.dy - half), Offset(x, center.dy + half), barPaint);
+ }
+ }
+
+ @override
+ bool shouldRepaint(_AbsorbWatchPainter old) => old.color != color;
+}
+
/// Wave icon with a circular rewind arrow around it - for "Absorb Again".
class AbsorbReplayIcon extends StatelessWidget {
final double size;
diff --git a/lib/widgets/listening_session_card.dart b/lib/widgets/listening_session_card.dart
index 2f95639e..ea79cfde 100644
--- a/lib/widgets/listening_session_card.dart
+++ b/lib/widgets/listening_session_card.dart
@@ -48,6 +48,7 @@ class ListeningSessionCard extends StatelessWidget {
deviceInfo['deviceName'] as String? ??
'';
final isAbsorb = clientName.toLowerCase().contains('absorb');
+ final isWear = isAbsorb && clientName.toLowerCase().contains('wear');
final isReading = session['mediaPlayer'] == ApiService.readingMediaPlayer;
return Padding(
@@ -81,6 +82,11 @@ class ListeningSessionCard extends StatelessWidget {
size: 18,
color: Colors.tealAccent.withValues(alpha: 0.9),
)
+ : isWear
+ ? AbsorbWatchIcon(
+ size: 20,
+ color: Colors.tealAccent.withValues(alpha: 0.9),
+ )
: isAbsorb
? AbsorbWaveIcon(
size: 18,