A cross platform Audiobookshelf client for Android and iOS
Dart
WearOS companion App sign in
Barnabase53099f1831b
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsindex 3eaf18f8..7833ef87 100644--- a/android/app/build.gradle.kts+++ b/android/app/build.gradle.kts@@ -85,4 +85,10 @@ flutter {dependencies {coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4")implementation("com.google.android.gms:play-services-cast-framework:21.5.0")++ // Wearable Data Layer — pushes ABS session credentials to the+ // paired Wear OS app so the watch can sign in without the user+ // typing anything on the watch keyboard.+ implementation("com.google.android.gms:play-services-wearable:19.0.0")+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0")}\ No newline at end of filediff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex dfc4ffd4..3559e0f6 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -150,6 +150,35 @@android:resource="@xml/stats_widget_info" /></receiver>+ <!-- Bridge to the AbsorbWear watch app: receives sync requests and+ sign-out events sent from the watch over the Wearable Data Layer. -->+ <service+ android:name=".WearAuthListenerService"+ android:exported="true">+ <intent-filter>+ <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />+ <data+ android:scheme="wear"+ android:host="*"+ android:pathPrefix="/absorb/auth" />+ </intent-filter>+ </service>++ <!-- Receives play-pause / skip-back / skip-forward commands sent+ from the AbsorbWear watch and forwards them to the audio+ session as MediaButton broadcasts. -->+ <service+ android:name=".WearPlayerCommandListenerService"+ android:exported="true">+ <intent-filter>+ <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />+ <data+ android:scheme="wear"+ android:host="*"+ android:pathPrefix="/absorb/player/cmd" />+ </intent-filter>+ </service>+</application><queries>diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.ktindex 3953e0f9..7022fd93 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt@@ -113,6 +113,69 @@ class MainActivity : AudioServiceActivity() {else -> result.notImplemented()}}++ // Bridge ABS playback state to the watch so it can render Now+ // Playing without making its own API calls.+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.barnabas.absorb/wear_player")+ .setMethodCallHandler { call, result ->+ when (call.method) {+ "publish" -> {+ WearPlayerBridge.publish(+ context = applicationContext,+ hasBook = call.argument<Boolean>("hasBook") ?: false,+ itemId = call.argument<String>("itemId"),+ title = call.argument<String>("title"),+ author = call.argument<String>("author"),+ chapter = call.argument<String>("chapter"),+ isPlaying = call.argument<Boolean>("isPlaying") ?: false,+ positionMs = (call.argument<Number>("positionMs") ?: 0).toLong(),+ durationMs = (call.argument<Number>("durationMs") ?: 0).toLong(),+ speed = (call.argument<Number>("speed") ?: 1.0).toFloat(),+ skipBackSec = (call.argument<Number>("skipBackSec") ?: 10).toInt(),+ skipForwardSec = (call.argument<Number>("skipForwardSec") ?: 30).toInt(),+ )+ result.success(true)+ }+ else -> result.notImplemented()+ }+ }++ // Bridge ABS auth state to the paired Wear OS app (AbsorbWear)+ // over the Google Play Services Wearable Data Layer.+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.barnabas.absorb/wear_auth")+ .setMethodCallHandler { call, result ->+ when (call.method) {+ "publish" -> {+ val serverUrl = call.argument<String>("serverUrl")+ val accessToken = call.argument<String>("accessToken")+ val username = call.argument<String>("username") ?: ""+ if (serverUrl == null || accessToken == null) {+ result.error("MISSING_ARGS", "serverUrl and accessToken are required", null)+ return@setMethodCallHandler+ }+ @Suppress("UNCHECKED_CAST")+ val headers = (call.argument<Map<String, Any?>>("customHeaders") ?: emptyMap())+ .mapNotNull { (k, v) -> if (v is String) k to v else null }+ .toMap()+ WearAuthBridge.publish(+ context = applicationContext,+ serverUrl = serverUrl,+ accessToken = accessToken,+ refreshToken = call.argument<String>("refreshToken"),+ username = username,+ userId = call.argument<String>("userId"),+ isLegacyToken = call.argument<Boolean>("isLegacyToken") ?: false,+ customHeaders = headers,+ )+ result.success(true)+ }+ "clear" -> {+ WearAuthBridge.clear(applicationContext)+ result.success(true)+ }+ else -> result.notImplemented()+ }+ }}private fun handleInit(result: MethodChannel.Result) {diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthBridge.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthBridge.ktnew file mode 100644index 00000000..44bc7140--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthBridge.kt@@ -0,0 +1,101 @@+package com.barnabas.absorb++import android.content.Context+import android.util.Log+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.tasks.await+import org.json.JSONObject++/**+ * Phone-side bridge that publishes the current Absorb session to the+ * Wearable Data Layer so the paired Wear OS app can sign in without the+ * user re-entering credentials on the watch keyboard.+ *+ * The companion Wear OS app reads the resulting `/absorb/auth/v1`+ * DataItem from a WearableListenerService. Keep the path constants and+ * field names in lock-step with that side (see AbsorbWear repo,+ * com.barnabas.absorb.wear.sync.WearPaths and auth.Credentials).+ */+object WearAuthBridge {+ private const val TAG = "WearAuthBridge"++ const val AUTH_PATH = "/absorb/auth/v1"+ const val AUTH_REQUEST_PATH = "/absorb/auth/request"+ const val AUTH_SIGN_OUT_PATH = "/absorb/auth/signout"++ private const val KEY_PAYLOAD = "payload"+ private const val KEY_ISSUED_AT = "issuedAt"++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ /** Push the active session to every connected watch. The DataItem is+ * persisted on both ends — a watch that comes online later still+ * receives the latest snapshot via Google Play Services sync. */+ fun publish(+ context: Context,+ serverUrl: String,+ accessToken: String,+ refreshToken: String?,+ username: String,+ userId: String?,+ isLegacyToken: Boolean,+ customHeaders: Map<String, String> = emptyMap(),+ ) {+ scope.launch {+ try {+ val now = System.currentTimeMillis()+ val headersJson = JSONObject().apply {+ customHeaders.forEach { (k, v) -> put(k, v) }+ }+ val payloadJson = JSONObject().apply {+ put("serverUrl", serverUrl)+ put("accessToken", accessToken)+ put("refreshToken", refreshToken ?: JSONObject.NULL)+ put("username", username)+ put("userId", userId ?: JSONObject.NULL)+ put("isLegacyToken", isLegacyToken)+ put("customHeaders", headersJson)+ put("issuedAt", now)+ }.toString()++ val request = PutDataMapRequest.create(AUTH_PATH).apply {+ // Both fields contribute to the DataItem's diff hash —+ // without ISSUED_AT, republishing the same token (e.g.+ // on app resume) wouldn't trigger onDataChanged on the+ // watch because Play Services treats it as unchanged.+ dataMap.putByteArray(KEY_PAYLOAD, payloadJson.toByteArray(Charsets.UTF_8))+ dataMap.putLong(KEY_ISSUED_AT, now)+ }.asPutDataRequest().setUrgent()++ Wearable.getDataClient(context.applicationContext).putDataItem(request).await()+ Log.i(TAG, "Published auth DataItem for user=$username")+ } catch (e: Exception) {+ Log.w(TAG, "Failed to publish auth DataItem", e)+ }+ }+ }++ /** Drop the persisted DataItem so any connected watch gets a TYPE_DELETED+ * event and signs itself out. Called on logout or account switch. */+ fun clear(context: Context) {+ scope.launch {+ try {+ val uri = android.net.Uri.Builder()+ .scheme("wear")+ .path(AUTH_PATH)+ .build()+ Wearable.getDataClient(context.applicationContext)+ .deleteDataItems(uri)+ .await()+ Log.i(TAG, "Cleared auth DataItem")+ } catch (e: Exception) {+ Log.w(TAG, "Failed to clear auth DataItem", e)+ }+ }+ }+}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthListenerService.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthListenerService.ktnew file mode 100644index 00000000..44a2c50c--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WearAuthListenerService.kt@@ -0,0 +1,84 @@+package com.barnabas.absorb++import android.content.Context+import android.util.Log+import com.google.android.gms.wearable.MessageEvent+import com.google.android.gms.wearable.WearableListenerService+import org.json.JSONObject++/**+ * Phone-side endpoint for watch -> phone Data Layer messages.+ *+ * 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.+ * - /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.+ *+ * Reads creds directly from the Flutter shared_preferences plugin's+ * backing XML (FlutterSharedPreferences) so we don't have to spin up the+ * Flutter engine just to answer a sync request when the phone app is+ * cold.+ */+class WearAuthListenerService : WearableListenerService() {++ override fun onMessageReceived(event: MessageEvent) {+ when (event.path) {+ WearAuthBridge.AUTH_REQUEST_PATH -> republishFromStoredPrefs()+ WearAuthBridge.AUTH_SIGN_OUT_PATH -> WearAuthBridge.clear(applicationContext)+ else -> super.onMessageReceived(event)+ }+ }++ private fun republishFromStoredPrefs() {+ val prefs = applicationContext.getSharedPreferences(+ FLUTTER_PREFS_FILE,+ Context.MODE_PRIVATE,+ )+ val serverUrl = prefs.getString("flutter.server_url", null)+ val token = prefs.getString("flutter.token", null)+ if (serverUrl == null || token == null) {+ Log.i(TAG, "Watch requested sync but no stored session on phone")+ return+ }+ val refreshToken = prefs.getString("flutter.refresh_token", null)+ val username = prefs.getString("flutter.username", null) ?: ""+ val userId = prefs.getString("flutter.user_id", null)+ // 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.+ val isLegacy = refreshToken == null++ // Flutter writes customHeaders as a JSON-encoded string under+ // `custom_headers` — decode and forward so Cloudflare Access /+ // proxy-auth users don't 403 when the watch makes ABS calls.+ val headers = mutableMapOf<String, String>()+ prefs.getString("flutter.custom_headers", null)?.let { raw ->+ try {+ val obj = JSONObject(raw)+ obj.keys().forEach { k -> obj.optString(k)?.let { headers[k] = it } }+ } catch (e: Exception) {+ Log.w(TAG, "Failed to decode custom_headers from prefs", e)+ }+ }++ WearAuthBridge.publish(+ context = applicationContext,+ serverUrl = serverUrl,+ accessToken = token,+ refreshToken = refreshToken,+ username = username,+ userId = userId,+ isLegacyToken = isLegacy,+ customHeaders = headers,+ )+ }++ companion object {+ private const val TAG = "WearAuthBridge"+ // Hardcoded by the flutter/shared_preferences plugin on Android.+ private const val FLUTTER_PREFS_FILE = "FlutterSharedPreferences"+ }+}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerBridge.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerBridge.ktnew file mode 100644index 00000000..775403b8--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerBridge.kt@@ -0,0 +1,83 @@+package com.barnabas.absorb++import android.content.Context+import android.util.Log+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.tasks.await+import org.json.JSONObject++/**+ * Pushes the current ABS playback snapshot to the paired Wear OS app+ * (AbsorbWear) so the watch can render "Now Playing" without making any+ * direct calls to the server.+ *+ * Keep the field set in sync with `com.barnabas.absorb.wear.player.PlayerState`+ * on the watch side. Bump the path version (`v1` → `v2`) when the shape+ * changes — DataItems are persistent and stale watches will still see the+ * last published payload until you republish.+ */+object WearPlayerBridge {+ private const val TAG = "WearPlayerBridge"++ const val STATE_PATH = "/absorb/player/state/v1"++ private const val KEY_PAYLOAD = "payload"+ private const val KEY_ISSUED_AT = "issuedAt"++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ /** Push the current playback snapshot. Call from the same throttle+ * loop that updates the home widget — anything finer-grained than+ * ~2s is wasted bandwidth. */+ fun publish(+ context: Context,+ hasBook: Boolean,+ itemId: String?,+ title: String?,+ author: String?,+ chapter: String?,+ isPlaying: Boolean,+ positionMs: Long,+ durationMs: Long,+ speed: Float,+ skipBackSec: Int,+ skipForwardSec: Int,+ ) {+ scope.launch {+ try {+ val now = System.currentTimeMillis()+ val payload = JSONObject().apply {+ put("hasBook", hasBook)+ put("itemId", itemId ?: JSONObject.NULL)+ put("title", title ?: JSONObject.NULL)+ put("author", author ?: JSONObject.NULL)+ put("chapter", chapter ?: JSONObject.NULL)+ put("isPlaying", isPlaying)+ put("positionMs", positionMs)+ put("durationMs", durationMs)+ put("speed", speed.toDouble())+ put("skipBackSec", skipBackSec)+ put("skipForwardSec", skipForwardSec)+ put("issuedAt", now)+ }.toString()++ val request = PutDataMapRequest.create(STATE_PATH).apply {+ // Both fields contribute to the diff hash — the timestamp+ // alone keeps republishes of identical metadata flowing+ // (so position-tick updates still propagate).+ dataMap.putByteArray(KEY_PAYLOAD, payload.toByteArray(Charsets.UTF_8))+ dataMap.putLong(KEY_ISSUED_AT, now)+ }.asPutDataRequest().setUrgent()++ Wearable.getDataClient(context.applicationContext).putDataItem(request).await()+ } catch (e: Exception) {+ Log.w(TAG, "Failed to publish player state", e)+ }+ }+ }+}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.ktnew file mode 100644index 00000000..acbd52fb--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WearPlayerCommandListenerService.kt@@ -0,0 +1,95 @@+package com.barnabas.absorb++import android.content.ComponentName+import android.content.Context+import android.content.Intent+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.WearableListenerService+import org.json.JSONObject++/**+ * Phone-side receiver for playback commands from the AbsorbWear watch.+ *+ * Two 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.+ * - 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+ * session).+ */+class WearPlayerCommandListenerService : WearableListenerService() {++ override fun onMessageReceived(event: MessageEvent) {+ when (event.path) {+ "/absorb/player/cmd/play-pause" -> dispatchMediaButton(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)+ "/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)+ else -> super.onMessageReceived(event)+ }+ }++ private fun dispatchMediaButton(keyCode: Int) {+ Log.i(TAG, "Watch -> MediaButton keyCode=$keyCode")+ val intent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {+ component = ComponentName(+ applicationContext,+ "com.ryanheise.audioservice.MediaButtonReceiver",+ )+ putExtra(+ Intent.EXTRA_KEY_EVENT,+ KeyEvent(KeyEvent.ACTION_DOWN, keyCode),+ )+ }+ applicationContext.sendBroadcast(intent)+ }++ private fun handlePlayItem(data: ByteArray) {+ val payload = try {+ JSONObject(data.decodeToString())+ } catch (e: Exception) {+ Log.w(TAG, "play-item payload not JSON", e); return+ }+ val itemId = payload.optString("itemId").ifBlank { null }+ if (itemId == null) {+ Log.w(TAG, "play-item missing itemId"); return+ }+ val episodeId = payload.optString("episodeId").ifBlank { null }++ // Build a URI the home_widget plugin already knows how to route+ // — it captures intents whose action is HOME_WIDGET_CLICK and+ // posts the data URI onto HomeWidget.widgetClicked. The Dart+ // side adds a /play_item case that parses these query params.+ val builder = Uri.Builder()+ .scheme("absorb")+ .authority("widget")+ .appendPath("play_item")+ .appendQueryParameter("itemId", itemId)+ if (episodeId != null) builder.appendQueryParameter("episodeId", episodeId)+ val uri = builder.build()++ 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")+ try {+ applicationContext.startActivity(intent)+ } catch (e: Exception) {+ Log.w(TAG, "Failed to launch MainActivity for play-item", e)+ }+ }++ companion object {+ private const val TAG = "WearPlayerBridge"+ // Intent action the home_widget plugin filters for.+ private const val HOME_WIDGET_CLICK = "es.antonborri.home_widget.action.LAUNCH"+ }+}diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 6727aae7..7c5051c2 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -11,6 +11,7 @@ import '../services/session_cache.dart';import '../services/socket_service.dart';import '../services/user_account_service.dart';import '../services/home_widget_service.dart';+import '../services/wear_auth_service.dart';import '../l10n/app_localizations.dart';import '../main.dart' show scaffoldMessengerKey, rootNavigatorKey;@@ -190,9 +191,29 @@ class AuthProvider extends ChangeNotifier {}// Push new token to socketSocketService().updateToken(_accessToken!);+ // Keep the paired Wear OS app's cached token in sync.+ _pushSessionToWear();notifyListeners();}+ /// Push the current session to the paired Wear OS app (if any). Safe+ /// to call unconditionally — the service is a no-op on non-Android+ /// platforms and when no watch is connected.+ void _pushSessionToWear() {+ final url = _serverUrl;+ final token = _accessToken;+ if (url == null || token == null) return;+ WearAuthService.instance.publish(+ serverUrl: url,+ accessToken: token,+ refreshToken: _refreshToken,+ username: _username ?? '',+ userId: _userId,+ isLegacyToken: _isLegacyToken,+ customHeaders: _customHeaders,+ );+ }+void _onAuthExpired() {debugPrint('[Auth] Token refresh failed, forcing re-login');// Show a message to the user@@ -334,6 +355,7 @@ class AuthProvider extends ChangeNotifier {}debugPrint('[Auth] tryRestoreSession done, isAuthenticated=$isAuthenticated (${sw.elapsedMilliseconds}ms)');+ if (isAuthenticated) _pushSessionToWear();_isLoading = false;notifyListeners();}@@ -456,6 +478,7 @@ class AuthProvider extends ChangeNotifier {await HomeWidgetService().clearStats();HomeWidgetService().refreshStats(force: true);+ _pushSessionToWear();_isLoading = false;notifyListeners();return true;@@ -542,6 +565,7 @@ class AuthProvider extends ChangeNotifier {await HomeWidgetService().clearStats();HomeWidgetService().refreshStats(force: true);+ _pushSessionToWear();_isLoading = false;notifyListeners();return true;@@ -629,6 +653,7 @@ class AuthProvider extends ChangeNotifier {await HomeWidgetService().clearStats();HomeWidgetService().refreshStats(force: true);+ _pushSessionToWear();_isLoading = false;notifyListeners();return true;@@ -795,6 +820,9 @@ class AuthProvider extends ChangeNotifier {await prefs.remove('default_library_id');} catch (_) {}+ // Sign the paired watch out too.+ WearAuthService.instance.clear();+notifyListeners();}@@ -922,6 +950,7 @@ class AuthProvider extends ChangeNotifier {}}_fetchServerVersion(activeServerUrl!);+ _pushSessionToWear();notifyListeners();return true;}diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 13bed7fd..5d56ce1f 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -12,6 +12,7 @@ import 'package:shared_preferences/shared_preferences.dart';import 'audio_player_service.dart';import 'api_service.dart';import 'download_service.dart';+import 'wear_player_service.dart';const String _androidWidgetName = 'NowPlayingWidget';const String _androidWidgetCompactName = 'NowPlayingWidgetCompact';@@ -188,6 +189,17 @@ class HomeWidgetService {case '/skip_forward':_handleSkipForward();break;+ case '/play_item':+ // Triggered by WearPlayerCommandListenerService when the watch+ // taps an item in Continue Listening. Unconditional — replaces+ // any current session (the watch already knows what it picked).+ final itemId = uri.queryParameters['itemId'];+ final rawEpisode = uri.queryParameters['episodeId'];+ final episodeId = (rawEpisode == null || rawEpisode.isEmpty) ? null : rawEpisode;+ if (itemId != null && itemId.isNotEmpty) {+ _handlePlayItem(itemId, episodeId);+ }+ break;}}}@@ -214,6 +226,92 @@ class HomeWidgetService {player.skipForward();}+ /// Start playback of a specific item. Used by the watch's Continue+ /// Listening tap → WearPlayerCommandListenerService → /play_item URI.+ /// Always plays (no toggle path) — the watch already chose which book+ /// it wants and the user expects an immediate switch.+ Future<void> _handlePlayItem(String itemId, String? episodeId) async {+ debugPrint('[HomeWidget] _handlePlayItem itemId=$itemId episodeId=$episodeId');+ final player = AudioPlayerService();++ final prefs = await SharedPreferences.getInstance();+ final serverUrl = prefs.getString('server_url');+ final token = prefs.getString('token');+ if (serverUrl == null || token == null) {+ debugPrint('[HomeWidget] play_item: no session in prefs');+ return;+ }+ final refreshToken = prefs.getString('refresh_token');++ Map<String, String>? customHeaders;+ final headersJson = prefs.getString('custom_headers');+ if (headersJson != null) {+ try {+ customHeaders =+ Map<String, String>.from(jsonDecode(headersJson) as Map);+ } catch (_) {}+ }++ final api = ApiService(+ baseUrl: serverUrl,+ token: token,+ refreshToken: refreshToken,+ isLegacyToken: refreshToken == null,+ customHeaders: customHeaders ?? const {},+ );++ try {+ final fullItem = await api.getLibraryItem(itemId);+ if (fullItem == null) {+ debugPrint('[HomeWidget] play_item: getLibraryItem returned null');+ return;+ }+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String? ?? '';+ final author = metadata['authorName'] as String? ?? '';+ final coverUrl = api.getCoverUrl(itemId);+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble()+ : 0.0;+ final chapters = (media['chapters'] as List<dynamic>?) ?? [];++ if (episodeId != null) {+ final episodes = (media['episodes'] as List<dynamic>?) ?? [];+ final episode = episodes.cast<Map<String, dynamic>>().firstWhere(+ (e) => e['id'] == episodeId,+ orElse: () => <String, dynamic>{},+ );+ final epTitle = episode['title'] as String? ?? title;+ final epDuration =+ (episode['duration'] as num?)?.toDouble() ?? duration;+ await player.playItem(+ api: api,+ itemId: itemId,+ title: epTitle,+ author: title,+ coverUrl: coverUrl,+ totalDuration: epDuration,+ chapters: const [],+ episodeId: episodeId,+ episodeTitle: epTitle,+ );+ } else {+ await player.playItem(+ api: api,+ itemId: itemId,+ title: title,+ author: author,+ coverUrl: coverUrl,+ totalDuration: duration,+ chapters: chapters,+ );+ }+ } catch (e) {+ debugPrint('[HomeWidget] play_item failed: $e');+ }+ }+Future<void> _handlePlayPause() async {final player = AudioPlayerService();debugPrint(@@ -417,6 +515,33 @@ class HomeWidgetService {}await _updateAllWidgets();+ _pushToWear(player, hasBook, skipBack, skipForward);+ }++ /// Mirror the same snapshot we just wrote to the home widget to the+ /// paired Wear OS companion. No-op off Android / when no watch is+ /// connected; cost is negligible (one MethodChannel call).+ void _pushToWear(+ AudioPlayerService player,+ bool hasBook,+ int skipBack,+ int skipForward,+ ) {+ if (!Platform.isAndroid) return;+ final chapterTitle = player.currentChapter?['title'] as String?;+ WearPlayerService.instance.publish(+ hasBook: hasBook,+ itemId: hasBook ? player.currentItemId : null,+ title: hasBook ? player.currentTitle : null,+ author: hasBook ? player.currentAuthor : null,+ chapter: hasBook ? chapterTitle : null,+ isPlaying: player.isPlaying,+ positionMs: player.position.inMilliseconds,+ durationMs: (player.totalDuration * 1000).round(),+ speed: player.speed.toDouble(),+ skipBackSec: skipBack,+ skipForwardSec: skipForward,+ );}/// Phase 1.1: write everything the iOS native player core needs to resumediff --git a/lib/services/wear_auth_service.dart b/lib/services/wear_auth_service.dartnew file mode 100644index 00000000..56943d50--- /dev/null+++ b/lib/services/wear_auth_service.dart@@ -0,0 +1,61 @@+import 'dart:io' show Platform;+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';++/// Thin bridge to the Android-side WearAuthBridge that publishes the+/// current ABS session to the paired Wear OS app (AbsorbWear) via the+/// Google Play Services Wearable Data Layer.+///+/// No-op on every platform except Android — iOS doesn't talk to Wear OS,+/// and desktop/web have nowhere to push to.+class WearAuthService {+ WearAuthService._();+ static final WearAuthService instance = WearAuthService._();++ static const MethodChannel _channel =+ MethodChannel('com.barnabas.absorb/wear_auth');++ bool get _supported => !kIsWeb && Platform.isAndroid;++ /// Push the current session to the paired watch. Safe to call on any+ /// login/refresh/account-switch; the Data Layer dedupes by hash.+ ///+ /// [customHeaders] are forwarded so the watch can replay Cloudflare+ /// Access / proxy auth headers on its own ABS API calls.+ Future<void> publish({+ required String serverUrl,+ required String accessToken,+ String? refreshToken,+ required String username,+ String? userId,+ required bool isLegacyToken,+ Map<String, String> customHeaders = const {},+ }) async {+ if (!_supported) return;+ try {+ await _channel.invokeMethod<void>('publish', {+ 'serverUrl': serverUrl,+ 'accessToken': accessToken,+ 'refreshToken': refreshToken,+ 'username': username,+ 'userId': userId,+ 'isLegacyToken': isLegacyToken,+ 'customHeaders': customHeaders,+ });+ } catch (e) {+ // Pure-best-effort: the phone app must work even if Play Services+ // is missing (e.g. on degoogled ROMs).+ debugPrint('[WearAuth] publish failed: $e');+ }+ }++ /// Clear the published session so the paired watch signs out too.+ Future<void> clear() async {+ if (!_supported) return;+ try {+ await _channel.invokeMethod<void>('clear');+ } catch (e) {+ debugPrint('[WearAuth] clear failed: $e');+ }+ }+}diff --git a/lib/services/wear_player_service.dart b/lib/services/wear_player_service.dartnew file mode 100644index 00000000..a96e7341--- /dev/null+++ b/lib/services/wear_player_service.dart@@ -0,0 +1,53 @@+import 'dart:io' show Platform;+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';++/// Pushes the active playback snapshot to the paired Wear OS companion+/// (AbsorbWear) via the Wearable Data Layer.+///+/// Like [WearAuthService] this is best-effort and a no-op off Android.+/// We piggyback on the existing HomeWidgetService update cadence (~2s),+/// so the bandwidth profile is identical to what the home widget+/// already costs.+class WearPlayerService {+ WearPlayerService._();+ static final WearPlayerService instance = WearPlayerService._();++ static const MethodChannel _channel =+ MethodChannel('com.barnabas.absorb/wear_player');++ bool get _supported => !kIsWeb && Platform.isAndroid;++ Future<void> publish({+ required bool hasBook,+ String? itemId,+ String? title,+ String? author,+ String? chapter,+ required bool isPlaying,+ required int positionMs,+ required int durationMs,+ required double speed,+ required int skipBackSec,+ required int skipForwardSec,+ }) async {+ if (!_supported) return;+ try {+ await _channel.invokeMethod<void>('publish', {+ 'hasBook': hasBook,+ 'itemId': itemId,+ 'title': title,+ 'author': author,+ 'chapter': chapter,+ 'isPlaying': isPlaying,+ 'positionMs': positionMs,+ 'durationMs': durationMs,+ 'speed': speed,+ 'skipBackSec': skipBackSec,+ 'skipForwardSec': skipForwardSec,+ });+ } catch (e) {+ debugPrint('[WearPlayer] publish failed: $e');+ }+ }+}