Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Initial commit — fresh start

Nathan Poulsonfa9c138e76be
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..3070cb86
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,48 @@
+# Miscellaneous
+*.class
+*.log
+*.pyc
+*.swp
+.DS_Store
+.atom/
+.build/
+.buildlog/
+.history
+.svn/
+.swiftpm/
+migrate_working_dir/
+
+# IntelliJ related
+*.iml
+*.ipr
+*.iws
+.idea/
+
+# The .vscode folder contains launch configuration and tasks you configure in
+# VS Code which you may wish to be included in version control, so this line
+# is commented out by default.
+#.vscode/
+
+# Flutter/Dart/Pub related
+**/doc/api/
+**/ios/Flutter/.last_build_id
+.dart_tool/
+.flutter-plugins-dependencies
+.pub-cache/
+.pub/
+/build/
+/coverage/
+
+# Symbolication related
+app.*.symbols
+
+# Obfuscation related
+app.*.map.json
+
+# Android Studio will place build artifacts here
+/android/app/debug
+/android/app/profile
+/android/app/release
+
+android/key.properties
+*.jks
diff --git a/.metadata b/.metadata
new file mode 100644
index 00000000..792284aa
--- /dev/null
+++ b/.metadata
@@ -0,0 +1,30 @@
+# This file tracks properties of this Flutter project.
+# Used by Flutter tool to assess capabilities and perform upgrades etc.
+#
+# This file should be version controlled and should not be manually edited.
+
+version:
+ revision: "19074d12f7eaf6a8180cd4036a430c1d76de904e"
+ channel: "stable"
+
+project_type: app
+
+# Tracks metadata for the flutter migrate command
+migration:
+ platforms:
+ - platform: root
+ create_revision: 19074d12f7eaf6a8180cd4036a430c1d76de904e
+ base_revision: 19074d12f7eaf6a8180cd4036a430c1d76de904e
+ - platform: android
+ create_revision: 19074d12f7eaf6a8180cd4036a430c1d76de904e
+ base_revision: 19074d12f7eaf6a8180cd4036a430c1d76de904e
+
+ # User provided section
+
+ # List of Local paths (relative to this file) that should be
+ # ignored by the migrate tool.
+ #
+ # Files that are not part of the templates will be ignored by default.
+ unmanaged_files:
+ - 'lib/main.dart'
+ - 'ios/Runner.xcodeproj/project.pbxproj'
diff --git a/PRIVACY_POLICY.md b/PRIVACY_POLICY.md
new file mode 100644
index 00000000..85205a45
--- /dev/null
+++ b/PRIVACY_POLICY.md
@@ -0,0 +1,51 @@
+# Privacy Policy
+
+**Absorb** — Audiobookshelf Client
+
+Last updated: February 23, 2026
+
+## Overview
+
+Absorb is a mobile client for Audiobookshelf servers. It connects directly to your self-hosted server and does not route any data through third-party services.
+
+## Data Collection
+
+Absorb does not collect, store, or transmit any personal data to the developer or any third party. All data stays between your device and your Audiobookshelf server.
+
+## What the App Stores Locally
+
+The following information is stored on your device only:
+
+- Server URL and authentication token for connecting to your server
+- Playback preferences (speed, sleep timer, equalizer settings)
+- Downloaded audiobook files for offline listening
+- Cached cover images and metadata
+
+This data never leaves your device except when communicating directly with your Audiobookshelf server.
+
+## Network Communication
+
+Absorb communicates only with:
+
+- Your self-hosted Audiobookshelf server (for library data, playback sync, and streaming)
+- Audnexus (optional, for fetching audiobook ratings and metadata)
+
+No analytics, crash reporting, or tracking services are used.
+
+## Third-Party Services
+
+Absorb does not integrate with any advertising networks, analytics platforms, or data brokers.
+
+## Children's Privacy
+
+Absorb does not knowingly collect any information from children under 13.
+
+## Changes to This Policy
+
+Any updates to this privacy policy will be reflected on this page with an updated date.
+
+## Contact
+
+If you have questions about this privacy policy, you can reach the developer through the GitHub repository:
+
+https://github.com/npoulson/absorb
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..5bc39d16
--- /dev/null
+++ b/README.md
@@ -0,0 +1,32 @@
+# Absorb
+
+A modern audiobookshelf client for Android with a card-based player experience.
+
+## Screenshots
+
+## Screenshots
+| Absorbing | Library | Details | Stats |
+|:-:|:-:|:-:|:-:|
+| <img src="screenshots/absorbing.png" width="200"> | <img src="screenshots/library.png" width="200"> | <img src="screenshots/details.png" width="200"> | <img src="screenshots/stats.png" width="200"> |
+## Features
+
+- **Card-based player** — full-screen "Absorbing" cards replace the traditional player screen
+- **Audiobookshelf integration** — connects to your self-hosted audiobookshelf server
+- **Offline playback** — download books for listening without a connection
+- **Sleep timer** with visual fill bar countdown
+- **Playback speed** control with fine-grained slider
+- **Bookmarks** — save and jump to moments in any book
+- **Chapter navigation** with dual progress bars (book + chapter)
+- **Audible ratings** — see star ratings from Audible on your books
+- **Auto-continue series** — seamlessly move to the next book
+- **Material You** theming with dynamic color support
+- **Listening stats** — track your listening history
+
+## Install
+
+Download the latest APK from [Releases](../../releases) or add the repo to [Obtainium](https://github.com/ImranR98/Obtainium).
+
+## Requirements
+
+- An [audiobookshelf](https://www.audiobookshelf.org/) server (self-hosted)
+- Android 7.0+
diff --git a/analysis_options.yaml b/analysis_options.yaml
new file mode 100644
index 00000000..4f710a78
--- /dev/null
+++ b/analysis_options.yaml
@@ -0,0 +1,7 @@
+include: package:flutter_lints/flutter.yaml
+
+linter:
+ rules:
+ prefer_const_constructors: true
+ prefer_const_declarations: true
+ avoid_print: true
diff --git a/android/.gitignore b/android/.gitignore
new file mode 100644
index 00000000..be3943c9
--- /dev/null
+++ b/android/.gitignore
@@ -0,0 +1,14 @@
+gradle-wrapper.jar
+/.gradle
+/captures/
+/gradlew
+/gradlew.bat
+/local.properties
+GeneratedPluginRegistrant.java
+.cxx/
+
+# Remember to never publicly share your keystore.
+# See https://flutter.dev/to/reference-keystore
+key.properties
+**/*.keystore
+**/*.jks
diff --git a/android/.kotlin/sessions/kotlin-compiler-6906615826790267457.salive b/android/.kotlin/sessions/kotlin-compiler-6906615826790267457.salive
new file mode 100644
index 00000000..e69de29b
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 00000000..9b2d69f4
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,77 @@
+import java.util.Properties
+import java.io.FileInputStream
+
+plugins {
+ id("com.android.application")
+ id("kotlin-android")
+ id("dev.flutter.flutter-gradle-plugin")
+}
+
+val keystoreProperties = Properties()
+val keystorePropertiesFile = rootProject.file("key.properties")
+if (keystorePropertiesFile.exists()) {
+ keystoreProperties.load(FileInputStream(keystorePropertiesFile))
+}
+
+android {
+ namespace = "com.barnabas.absorb"
+ compileSdk = flutter.compileSdkVersion
+ ndkVersion = flutter.ndkVersion
+
+ compileOptions {
+ isCoreLibraryDesugaringEnabled = true
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = JavaVersion.VERSION_17.toString()
+ }
+
+ signingConfigs {
+ create("release") {
+ keyAlias = keystoreProperties["keyAlias"] as String?
+ keyPassword = keystoreProperties["keyPassword"] as String?
+ storeFile = (keystoreProperties["storeFile"] as String?)?.let { file(it) }
+ storePassword = keystoreProperties["storePassword"] as String?
+ }
+ }
+
+ defaultConfig {
+ applicationId = "com.barnabas.absorb"
+ minSdk = flutter.minSdkVersion
+ targetSdk = flutter.targetSdkVersion
+ versionCode = flutter.versionCode
+ versionName = flutter.versionName
+ }
+
+ buildTypes {
+ debug {
+ signingConfig = signingConfigs.getByName("release")
+ }
+ release {
+ signingConfig = signingConfigs.getByName("release")
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro"
+ )
+ }
+}
+
+ applicationVariants.all {
+ outputs.all {
+ (this as com.android.build.gradle.internal.api.BaseVariantOutputImpl)
+ .outputFileName = "absorb-${versionName}.apk"
+ }
+ }
+}
+
+flutter {
+ source = "../.."
+}
+
+dependencies {
+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4")
+}
\ No newline at end of file
diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro
new file mode 100644
index 00000000..0129127f
--- /dev/null
+++ b/android/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Flutter
+-keep class io.flutter.** { *; }
+-keep class io.flutter.plugins.** { *; }
+
+# just_audio
+-keep class com.google.android.exoplayer2.** { *; }
+-keep class androidx.media3.** { *; }
+
+# audio_service
+-keep class com.ryanheise.audioservice.** { *; }
+
+# Google Play Core (not used but referenced by Flutter engine)
+-dontwarn com.google.android.play.core.**
+
+# Keep all annotations
+-keepattributes *Annotation*
+
+# Prevent stripping of native methods
+-keepclasseswithmembernames class * {
+ native <methods>;
+}
\ No newline at end of file
diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml
new file mode 100644
index 00000000..399f6981
--- /dev/null
+++ b/android/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,7 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <!-- The INTERNET permission is required for development. Specifically,
+ the Flutter tool needs it to communicate with the running application
+ to allow setting breakpoints, to provide hot reload, etc.
+ -->
+ <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..3220082a
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,92 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
+
+ <!-- REQUIRED PERMISSIONS -->
+ <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.WAKE_LOCK"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
+
+ <!-- Block permissions pulled in by dependencies -->
+ <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" tools:node="remove"/>
+ <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove"/>
+
+ <application android:label="Absorb" android:name="${applicationName}" android:icon="@mipmap/ic_launcher" android:usesCleartextTraffic="true">
+
+ <activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTop" android:taskAffinity="" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize">
+ <meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme"/>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN"/>
+ <category android:name="android.intent.category.LAUNCHER"/>
+ </intent-filter>
+ <!-- Required by audio_service: tap notification to return to app -->
+ <intent-filter>
+ <action android:name="com.ryanheise.audioservice.NOTIFICATION_CLICK"/>
+ <category android:name="android.intent.category.DEFAULT"/>
+ </intent-filter>
+
+ <!-- oidc -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="audiobookshelf" android:host="oauth" />
+ </intent-filter>
+
+ </activity>
+
+ <!-- audio_service: background playback and media notification -->
+ <service android:name="com.ryanheise.audioservice.AudioService" android:foregroundServiceType="mediaPlayback" android:exported="true" tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.media.browse.MediaBrowserService"/>
+ </intent-filter>
+ </service>
+
+ <!-- Media button support (headphones, car stereo, etc.) -->
+ <receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver" android:exported="true" tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.intent.action.MEDIA_BUTTON"/>
+ </intent-filter>
+ </receiver>
+
+ <meta-data android:name="flutterEmbedding" android:value="2"/>
+
+ <meta-data android:name="com.ryanheise.audioservice.NOTIFICATION_ICON" android:resource="@drawable/ic_notification"/>
+
+ <meta-data
+ android:name="com.google.android.gms.car.application"
+ android:resource="@xml/automotive_app_desc" />
+
+ <meta-data
+ android:name="com.google.android.gms.car.notification.SmallIcon"
+ android:resource="@drawable/ic_notification" />
+
+ <!-- Chromecast Metadata -->
+ <meta-data
+ android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
+ android:value="com.felnanuke.google_cast.GoogleCastOptionsProvider" />
+
+ <!-- Send covers to AA while offline -->
+ <provider
+ android:name=".CoverContentProvider"
+ android:authorities="com.barnabas.absorb.covers"
+ android:exported="true"
+ android:grantUriPermissions="true" />
+
+ <!--Forground notification for better download-->
+ <service
+ android:name="com.dexterous.flutterlocalnotifications.ForegroundService"
+ android:exported="false"
+ android:foregroundServiceType="dataSync" />
+
+ </application>
+
+ <queries>
+ <intent>
+ <action android:name="android.intent.action.PROCESS_TEXT"/>
+ <data android:mimeType="text/plain"/>
+ </intent>
+ </queries>
+</manifest>
\ No newline at end of file
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
new file mode 100644
index 00000000..30578939
--- /dev/null
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
@@ -0,0 +1,141 @@
+package com.barnabas.absorb
+
+import android.content.ContentProvider
+import android.content.ContentValues
+import android.database.Cursor
+import android.database.MatrixCursor
+import android.net.Uri
+import android.os.ParcelFileDescriptor
+import android.provider.OpenableColumns
+import java.io.File
+
+/**
+ * ContentProvider that serves locally-cached cover images to Android Auto.
+ *
+ * Android Auto cannot load file:// URIs directly — it requires content:// URIs.
+ * This provider maps:
+ * content://com.barnabas.absorb.covers/cover/<itemId>
+ * to the cover.jpg file in the item's download directory.
+ *
+ * Place this file at:
+ * android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
+ *
+ * Register in AndroidManifest.xml inside the <application> tag:
+ *
+ * <provider
+ * android:name=".CoverContentProvider"
+ * android:authorities="com.barnabas.absorb.covers"
+ * android:exported="true"
+ * android:grantUriPermissions="true" />
+ */
+class CoverContentProvider : ContentProvider() {
+
+ companion object {
+ const val AUTHORITY = "com.barnabas.absorb.covers"
+
+ fun buildCoverUri(itemId: String): Uri {
+ return Uri.parse("content://$AUTHORITY/cover/$itemId")
+ }
+ }
+
+ override fun onCreate(): Boolean = true
+
+ override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
+ val itemId = extractItemId(uri) ?: return null
+ val context = context ?: return null
+ val coverFile = findCoverFile(context, itemId) ?: return null
+ return ParcelFileDescriptor.open(coverFile, ParcelFileDescriptor.MODE_READ_ONLY)
+ }
+
+ /**
+ * Return MIME type for the URI. Android Auto's image loader checks this
+ * to determine if it can handle the content:// URI as an image.
+ */
+ override fun getType(uri: Uri): String = "image/jpeg"
+
+ /**
+ * Return supported stream MIME types. Android Auto may call this to verify
+ * the provider can serve image data before attempting to load it.
+ */
+ override fun getStreamTypes(uri: Uri, mimeTypeFilter: String): Array<String>? {
+ // Match any image filter (e.g. "image/*", "*/*", "image/jpeg")
+ if (mimeTypeFilter == "*/*" ||
+ mimeTypeFilter == "image/*" ||
+ mimeTypeFilter == "image/jpeg") {
+ return arrayOf("image/jpeg")
+ }
+ return null
+ }
+
+ /**
+ * Implement query to return file metadata. Some Android Auto implementations
+ * query the provider for display name and size before loading the image.
+ */
+ override fun query(
+ uri: Uri,
+ projection: Array<out String>?,
+ selection: String?,
+ selectionArgs: Array<out String>?,
+ sortOrder: String?
+ ): Cursor? {
+ val itemId = extractItemId(uri) ?: return null
+ val context = context ?: return null
+ val coverFile = findCoverFile(context, itemId) ?: return null
+
+ val cols = projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)
+ val cursor = MatrixCursor(cols.map { it }.toTypedArray())
+ val row = cols.map { col ->
+ when (col) {
+ OpenableColumns.DISPLAY_NAME -> "cover.jpg"
+ OpenableColumns.SIZE -> coverFile.length()
+ else -> null
+ }
+ }.toTypedArray()
+ cursor.addRow(row)
+ return cursor
+ }
+
+ // ── Helpers ──
+
+ private fun extractItemId(uri: Uri): String? {
+ val segments = uri.pathSegments
+ // Expected: /cover/<itemId>
+ if (segments.size != 2 || segments[0] != "cover") return null
+ val itemId = segments[1]
+ // Sanitize — only allow alphanumeric, hyphens, underscores
+ if (!itemId.matches(Regex("^[a-zA-Z0-9_\\-]+$"))) return null
+ return itemId
+ }
+
+ private fun findCoverFile(context: android.content.Context, itemId: String): File? {
+ // Check custom download path first (stored in SharedPreferences)
+ val prefs = context.getSharedPreferences("FlutterSharedPreferences", android.content.Context.MODE_PRIVATE)
+ val customPath = prefs.getString("flutter.custom_download_path", null)
+
+ if (customPath != null && customPath.isNotEmpty()) {
+ val file = File("$customPath/$itemId/cover.jpg")
+ if (file.exists() && file.canRead()) return file
+ }
+
+ // Default: app documents directory
+ val docsDir = context.filesDir?.parentFile?.let { File(it, "app_flutter/downloads") }
+ if (docsDir != null) {
+ val file = File("$docsDir/$itemId/cover.jpg")
+ if (file.exists() && file.canRead()) return file
+ }
+
+ // Also try getExternalFilesDir path
+ val extDir = context.getExternalFilesDir(null)
+ if (extDir != null) {
+ val file = File("${extDir.parent}/app_flutter/downloads/$itemId/cover.jpg")
+ if (file.exists() && file.canRead()) return file
+ }
+
+ return null
+ }
+
+ // Not used — read-only provider
+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null
+ override fun update(uri: Uri, values: ContentValues?, s: String?, sa: Array<out String>?): Int = 0
+ override fun delete(uri: Uri, s: String?, sa: Array<out String>?): Int = 0
+}
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
new file mode 100644
index 00000000..a9c702d5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -0,0 +1,187 @@
+package com.barnabas.absorb
+
+import android.media.audiofx.BassBoost
+import android.media.audiofx.Equalizer
+import android.media.audiofx.LoudnessEnhancer
+import android.media.audiofx.Virtualizer
+import android.util.Log
+import com.ryanheise.audioservice.AudioServiceActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
+
+class MainActivity : AudioServiceActivity() {
+ private val TAG = "AbsorbEQ"
+ private val CHANNEL = "com.absorb.equalizer"
+
+ private var equalizer: Equalizer? = null
+ private var bassBoost: BassBoost? = null
+ private var virtualizer: Virtualizer? = null
+ private var loudnessEnhancer: LoudnessEnhancer? = null
+ private var currentSessionId: Int = 0
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
+ .setMethodCallHandler { call, result ->
+ when (call.method) {
+ "init" -> handleInit(result)
+ "attachSession" -> {
+ val sessionId = call.argument<Int>("sessionId") ?: 0
+ handleAttachSession(sessionId, result)
+ }
+ "setEnabled" -> {
+ val enabled = call.argument<Boolean>("enabled") ?: false
+ handleSetEnabled(enabled, result)
+ }
+ "setBand" -> {
+ val band = call.argument<Int>("band") ?: 0
+ val level = call.argument<Int>("level") ?: 0
+ handleSetBand(band, level, result)
+ }
+ "setBassBoost" -> {
+ val strength = call.argument<Int>("strength") ?: 0
+ handleSetBassBoost(strength, result)
+ }
+ "setVirtualizer" -> {
+ val strength = call.argument<Int>("strength") ?: 0
+ handleSetVirtualizer(strength, result)
+ }
+ "setLoudness" -> {
+ val gain = call.argument<Int>("gain") ?: 0
+ handleSetLoudness(gain, result)
+ }
+ else -> result.notImplemented()
+ }
+ }
+ Log.d(TAG, "EQ method channel registered")
+ }
+
+ private fun handleInit(result: MethodChannel.Result) {
+ try {
+ val tempEq = Equalizer(0, 0)
+ val numBands = tempEq.numberOfBands.toInt()
+ val frequencies = mutableListOf<Int>()
+ for (i in 0 until numBands) {
+ frequencies.add(tempEq.getCenterFreq(i.toShort()) / 1000)
+ }
+ val bandRange = tempEq.bandLevelRange
+ val minLevel = bandRange[0] / 100.0
+ val maxLevel = bandRange[1] / 100.0
+ tempEq.release()
+
+ Log.d(TAG, "init: $numBands bands, frequencies=$frequencies, range=[$minLevel, $maxLevel]dB")
+ result.success(mapOf(
+ "bands" to numBands,
+ "frequencies" to frequencies,
+ "minLevel" to minLevel,
+ "maxLevel" to maxLevel
+ ))
+ } catch (e: Exception) {
+ Log.e(TAG, "init failed: ${e.message}")
+ result.error("EQ_INIT_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleAttachSession(sessionId: Int, result: MethodChannel.Result) {
+ try {
+ Log.d(TAG, "attachSession: $sessionId (previous: $currentSessionId)")
+ if (sessionId != currentSessionId) {
+ releaseEffects()
+ }
+ currentSessionId = sessionId
+
+ if (sessionId == 0) {
+ result.success(true)
+ return
+ }
+
+ equalizer = Equalizer(0, sessionId).apply { enabled = true }
+ bassBoost = try {
+ BassBoost(0, sessionId).apply { enabled = true }
+ } catch (e: Exception) {
+ Log.w(TAG, "BassBoost not supported: ${e.message}"); null
+ }
+ virtualizer = try {
+ Virtualizer(0, sessionId).apply { enabled = true }
+ } catch (e: Exception) {
+ Log.w(TAG, "Virtualizer not supported: ${e.message}"); null
+ }
+ loudnessEnhancer = try {
+ LoudnessEnhancer(sessionId).apply { enabled = true }
+ } catch (e: Exception) {
+ Log.w(TAG, "LoudnessEnhancer not supported: ${e.message}"); null
+ }
+
+ Log.d(TAG, "Effects attached to session $sessionId")
+ result.success(true)
+ } catch (e: Exception) {
+ Log.e(TAG, "attachSession failed: ${e.message}")
+ result.error("EQ_ATTACH_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleSetEnabled(enabled: Boolean, result: MethodChannel.Result) {
+ try {
+ equalizer?.enabled = enabled
+ bassBoost?.enabled = enabled
+ virtualizer?.enabled = enabled
+ loudnessEnhancer?.enabled = enabled
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("EQ_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleSetBand(band: Int, level: Int, result: MethodChannel.Result) {
+ try {
+ equalizer?.setBandLevel(band.toShort(), level.toShort())
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("EQ_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleSetBassBoost(strength: Int, result: MethodChannel.Result) {
+ try {
+ bassBoost?.setStrength(strength.toShort().coerceIn(0, 1000))
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("EQ_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleSetVirtualizer(strength: Int, result: MethodChannel.Result) {
+ try {
+ virtualizer?.setStrength(strength.toShort().coerceIn(0, 1000))
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("EQ_ERROR", e.message, null)
+ }
+ }
+
+ private fun handleSetLoudness(gain: Int, result: MethodChannel.Result) {
+ try {
+ loudnessEnhancer?.setTargetGain(gain)
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("EQ_ERROR", e.message, null)
+ }
+ }
+
+ private fun releaseEffects() {
+ try { equalizer?.release() } catch (_: Exception) {}
+ try { bassBoost?.release() } catch (_: Exception) {}
+ try { virtualizer?.release() } catch (_: Exception) {}
+ try { loudnessEnhancer?.release() } catch (_: Exception) {}
+ equalizer = null
+ bassBoost = null
+ virtualizer = null
+ loudnessEnhancer = null
+ }
+
+ override fun onDestroy() {
+ releaseEffects()
+ super.onDestroy()
+ }
+}
diff --git a/android/app/src/main/res/drawable-hdpi/android12splash.png b/android/app/src/main/res/drawable-hdpi/android12splash.png
new file mode 100644
index 00000000..47391e24
Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png
new file mode 100644
index 00000000..8cf02212
Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/drawable-hdpi/splash.png b/android/app/src/main/res/drawable-hdpi/splash.png
new file mode 100644
index 00000000..47391e24
Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/splash.png differ
diff --git a/android/app/src/main/res/drawable-mdpi/android12splash.png b/android/app/src/main/res/drawable-mdpi/android12splash.png
new file mode 100644
index 00000000..43821f2e
Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png
new file mode 100644
index 00000000..e7ba547f
Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/drawable-mdpi/splash.png b/android/app/src/main/res/drawable-mdpi/splash.png
new file mode 100644
index 00000000..43821f2e
Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/splash.png differ
diff --git a/android/app/src/main/res/drawable-night-hdpi/android12splash.png b/android/app/src/main/res/drawable-night-hdpi/android12splash.png
new file mode 100644
index 00000000..47391e24
Binary files /dev/null and b/android/app/src/main/res/drawable-night-hdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-night-mdpi/android12splash.png b/android/app/src/main/res/drawable-night-mdpi/android12splash.png
new file mode 100644
index 00000000..43821f2e
Binary files /dev/null and b/android/app/src/main/res/drawable-night-mdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-night-xhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xhdpi/android12splash.png
new file mode 100644
index 00000000..0f7122e1
Binary files /dev/null and b/android/app/src/main/res/drawable-night-xhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png
new file mode 100644
index 00000000..30a67a98
Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png
new file mode 100644
index 00000000..bce2d345
Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-v21/background.png b/android/app/src/main/res/drawable-v21/background.png
new file mode 100644
index 00000000..e815fd62
Binary files /dev/null and b/android/app/src/main/res/drawable-v21/background.png differ
diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml
new file mode 100644
index 00000000..3cc4948a
--- /dev/null
+++ b/android/app/src/main/res/drawable-v21/launch_background.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+ <item>
+ <bitmap android:gravity="fill" android:src="@drawable/background"/>
+ </item>
+ <item>
+ <bitmap android:gravity="center" android:src="@drawable/splash"/>
+ </item>
+</layer-list>
diff --git a/android/app/src/main/res/drawable-xhdpi/android12splash.png b/android/app/src/main/res/drawable-xhdpi/android12splash.png
new file mode 100644
index 00000000..0f7122e1
Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png
new file mode 100644
index 00000000..7fc59181
Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/drawable-xhdpi/splash.png b/android/app/src/main/res/drawable-xhdpi/splash.png
new file mode 100644
index 00000000..0f7122e1
Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/splash.png differ
diff --git a/android/app/src/main/res/drawable-xxhdpi/android12splash.png b/android/app/src/main/res/drawable-xxhdpi/android12splash.png
new file mode 100644
index 00000000..30a67a98
Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png
new file mode 100644
index 00000000..a6e4e14b
Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/drawable-xxhdpi/splash.png b/android/app/src/main/res/drawable-xxhdpi/splash.png
new file mode 100644
index 00000000..30a67a98
Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/splash.png differ
diff --git a/android/app/src/main/res/drawable-xxxhdpi/android12splash.png b/android/app/src/main/res/drawable-xxxhdpi/android12splash.png
new file mode 100644
index 00000000..bce2d345
Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/android12splash.png differ
diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 00000000..4e57c5bb
Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/drawable-xxxhdpi/splash.png b/android/app/src/main/res/drawable-xxxhdpi/splash.png
new file mode 100644
index 00000000..bce2d345
Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/splash.png differ
diff --git a/android/app/src/main/res/drawable/audio_service_skip_to_next.xml b/android/app/src/main/res/drawable/audio_service_skip_to_next.xml
new file mode 100644
index 00000000..d570a5a1
--- /dev/null
+++ b/android/app/src/main/res/drawable/audio_service_skip_to_next.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M18,13c0,3.31 -2.69,6 -6,6s-6,-2.69 -6,-6 2.69,-6 6,-6v4l5,-5 -5,-5v4c-4.42,0 -8,3.58 -8,8s3.58,8 8,8 8,-3.58 8,-8h-2z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/audio_service_skip_to_previous.xml b/android/app/src/main/res/drawable/audio_service_skip_to_previous.xml
new file mode 100644
index 00000000..477731ff
--- /dev/null
+++ b/android/app/src/main/res/drawable/audio_service_skip_to_previous.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,5V1L7,6l5,5V7c3.31,0 6,2.69 6,6s-2.69,6 -6,6 -6,-2.69 -6,-6H4c0,4.42 3.58,8 8,8s8,-3.58 8,-8 -3.58,-8 -8,-8z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/background.png b/android/app/src/main/res/drawable/background.png
new file mode 100644
index 00000000..e815fd62
Binary files /dev/null and b/android/app/src/main/res/drawable/background.png differ
diff --git a/android/app/src/main/res/drawable/ic_chapter_next.xml b/android/app/src/main/res/drawable/ic_chapter_next.xml
new file mode 100644
index 00000000..61bbdd35
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_chapter_next.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M16,6h2v12h-2V6z"/>
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M6,13c0,3.31 2.69,6 6,6 1.53,0 2.92,-0.58 3.98,-1.52l-1.42,-1.42C13.74,16.66 12.91,17 12,17c-2.21,0 -4,-1.79 -4,-4s1.79,-4 4,-4v3l5,-5 -5,-5v3c-3.31,0 -6,2.69 -6,6z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_chapter_previous.xml b/android/app/src/main/res/drawable/ic_chapter_previous.xml
new file mode 100644
index 00000000..8478f7ab
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_chapter_previous.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M6,6h2v12H6V6z"/>
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M18,13c0,3.31 -2.69,6 -6,6 -1.53,0 -2.92,-0.58 -3.98,-1.52l1.42,-1.42C10.26,16.66 11.09,17 12,17c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4v3L7,7l5,-5v3c3.31,0 6,2.69 6,6z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_forward.xml b/android/app/src/main/res/drawable/ic_forward.xml
new file mode 100644
index 00000000..d570a5a1
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_forward.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M18,13c0,3.31 -2.69,6 -6,6s-6,-2.69 -6,-6 2.69,-6 6,-6v4l5,-5 -5,-5v4c-4.42,0 -8,3.58 -8,8s3.58,8 8,8 8,-3.58 8,-8h-2z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_notification.png b/android/app/src/main/res/drawable/ic_notification.png
new file mode 100644
index 00000000..5ffb0665
Binary files /dev/null and b/android/app/src/main/res/drawable/ic_notification.png differ
diff --git a/android/app/src/main/res/drawable/ic_replay.xml b/android/app/src/main/res/drawable/ic_replay.xml
new file mode 100644
index 00000000..477731ff
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_replay.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,5V1L7,6l5,5V7c3.31,0 6,2.69 6,6s-2.69,6 -6,6 -6,-2.69 -6,-6H4c0,4.42 3.58,8 8,8s8,-3.58 8,-8 -3.58,-8 -8,-8z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_skip_next.xml b/android/app/src/main/res/drawable/ic_skip_next.xml
new file mode 100644
index 00000000..4fff2475
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_skip_next.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_skip_previous.xml b/android/app/src/main/res/drawable/ic_skip_previous.xml
new file mode 100644
index 00000000..77df8ad7
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_skip_previous.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M6,6h2v12H6V6zM9.5,12l8.5,6V6L9.5,12z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml
new file mode 100644
index 00000000..3cc4948a
--- /dev/null
+++ b/android/app/src/main/res/drawable/launch_background.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+ <item>
+ <bitmap android:gravity="fill" android:src="@drawable/background"/>
+ </item>
+ <item>
+ <bitmap android:gravity="center" android:src="@drawable/splash"/>
+ </item>
+</layer-list>
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 00000000..c79c58a3
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background"/>
+ <foreground>
+ <inset
+ android:drawable="@drawable/ic_launcher_foreground"
+ android:inset="16%" />
+ </foreground>
+</adaptive-icon>
diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 00000000..d2d82f79
Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 00000000..1907770d
Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 00000000..844769b5
Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 00000000..60e36ebb
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 00000000..b07585ca
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/values-night-v31/styles.xml b/android/app/src/main/res/values-night-v31/styles.xml
new file mode 100644
index 00000000..2ddcec19
--- /dev/null
+++ b/android/app/src/main/res/values-night-v31/styles.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
+ <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
+ <item name="android:forceDarkAllowed">false</item>
+ <item name="android:windowFullscreen">false</item>
+ <item name="android:windowDrawsSystemBarBackgrounds">false</item>
+ <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
+ <item name="android:windowSplashScreenBackground">#000000</item>
+ <item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
+ </style>
+ <!-- Theme applied to the Android Window as soon as the process has started.
+ This theme determines the color of the Android Window while your
+ Flutter UI initializes, as well as behind your Flutter UI while its
+ running.
+
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
+ <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
+ <item name="android:windowBackground">?android:colorBackground</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml
new file mode 100644
index 00000000..dbc9ea9f
--- /dev/null
+++ b/android/app/src/main/res/values-night/styles.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
+ <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
+ <!-- Show a splash screen on the activity. Automatically removed when
+ the Flutter engine draws its first frame -->
+ <item name="android:windowBackground">@drawable/launch_background</item>
+ <item name="android:forceDarkAllowed">false</item>
+ <item name="android:windowFullscreen">false</item>
+ <item name="android:windowDrawsSystemBarBackgrounds">false</item>
+ <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
+ </style>
+ <!-- Theme applied to the Android Window as soon as the process has started.
+ This theme determines the color of the Android Window while your
+ Flutter UI initializes, as well as behind your Flutter UI while its
+ running.
+
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
+ <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
+ <item name="android:windowBackground">?android:colorBackground</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/values-v31/styles.xml b/android/app/src/main/res/values-v31/styles.xml
new file mode 100644
index 00000000..1ea6bfd6
--- /dev/null
+++ b/android/app/src/main/res/values-v31/styles.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <item name="android:forceDarkAllowed">false</item>
+ <item name="android:windowFullscreen">false</item>
+ <item name="android:windowDrawsSystemBarBackgrounds">false</item>
+ <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
+ <item name="android:windowSplashScreenBackground">#000000</item>
+ <item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
+ </style>
+ <!-- Theme applied to the Android Window as soon as the process has started.
+ This theme determines the color of the Android Window while your
+ Flutter UI initializes, as well as behind your Flutter UI while its
+ running.
+
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <item name="android:windowBackground">?android:colorBackground</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml
new file mode 100644
index 00000000..beab31f7
--- /dev/null
+++ b/android/app/src/main/res/values/colors.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_background">#000000</color>
+</resources>
\ No newline at end of file
diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml
new file mode 100644
index 00000000..0d1fa8fc
--- /dev/null
+++ b/android/app/src/main/res/values/styles.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <!-- Show a splash screen on the activity. Automatically removed when
+ the Flutter engine draws its first frame -->
+ <item name="android:windowBackground">@drawable/launch_background</item>
+ <item name="android:forceDarkAllowed">false</item>
+ <item name="android:windowFullscreen">false</item>
+ <item name="android:windowDrawsSystemBarBackgrounds">false</item>
+ <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
+ </style>
+ <!-- Theme applied to the Android Window as soon as the process has started.
+ This theme determines the color of the Android Window while your
+ Flutter UI initializes, as well as behind your Flutter UI while its
+ running.
+
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <item name="android:windowBackground">?android:colorBackground</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/xml/automotive_app_desc.xml b/android/app/src/main/res/xml/automotive_app_desc.xml
new file mode 100644
index 00000000..0f739ff8
--- /dev/null
+++ b/android/app/src/main/res/xml/automotive_app_desc.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<automotiveApp>
+ <uses name="media" />
+</automotiveApp>
\ No newline at end of file
diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml
new file mode 100644
index 00000000..399f6981
--- /dev/null
+++ b/android/app/src/profile/AndroidManifest.xml
@@ -0,0 +1,7 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <!-- The INTERNET permission is required for development. Specifically,
+ the Flutter tool needs it to communicate with the running application
+ to allow setting breakpoints, to provide hot reload, etc.
+ -->
+ <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
new file mode 100644
index 00000000..dbee657b
--- /dev/null
+++ b/android/build.gradle.kts
@@ -0,0 +1,24 @@
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+val newBuildDir: Directory =
+ rootProject.layout.buildDirectory
+ .dir("../../build")
+ .get()
+rootProject.layout.buildDirectory.value(newBuildDir)
+
+subprojects {
+ val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
+ project.layout.buildDirectory.value(newSubprojectBuildDir)
+}
+subprojects {
+ project.evaluationDependsOn(":app")
+}
+
+tasks.register<Delete>("clean") {
+ delete(rootProject.layout.buildDirectory)
+}
diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html
new file mode 100644
index 00000000..9873eab4
--- /dev/null
+++ b/android/build/reports/problems/problems-report.html
@@ -0,0 +1,663 @@
+<!DOCTYPE html>
+
+<html lang="en">
+<head>
+ <!-- Required meta tags -->
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+
+ <style type="text/css">
+ /*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */
+html {
+ line-height: 1.15;
+ -ms-text-size-adjust: 100%;
+ -webkit-text-size-adjust: 100%
+}
+
+body {
+ margin: 0
+}
+
+article, aside, footer, header, nav, section {
+ display: block
+}
+
+h1 {
+ font-size: 2em;
+ margin: .67em 0
+}
+
+figcaption, figure, main {
+ display: block
+}
+
+figure {
+ margin: 1em 40px
+}
+
+hr {
+ box-sizing: content-box;
+ height: 0;
+ overflow: visible
+}
+
+pre {
+ font-family: monospace, monospace;
+ font-size: 1em
+}
+
+a {
+ background-color: transparent;
+ -webkit-text-decoration-skip: objects
+}
+
+abbr[title] {
+ border-bottom: none;
+ text-decoration: underline;
+ text-decoration: underline dotted
+}
+
+b, strong {
+ font-weight: inherit
+}
+
+b, strong {
+ font-weight: bolder
+}
+
+code, kbd, samp {
+ font-family: monospace, monospace;
+ font-size: 1em
+}
+
+dfn {
+ font-style: italic
+}
+
+mark {
+ background-color: #ff0;
+ color: #000
+}
+
+small {
+ font-size: 80%
+}
+
+sub, sup {
+ font-size: 75%;
+ line-height: 0;
+ position: relative;
+ vertical-align: baseline
+}
+
+sub {
+ bottom: -.25em
+}
+
+sup {
+ top: -.5em
+}
+
+audio, video {
+ display: inline-block
+}
+
+audio:not([controls]) {
+ display: none;
+ height: 0
+}
+
+img {
+ border-style: none
+}
+
+svg:not(:root) {
+ overflow: hidden
+}
+
+button, input, optgroup, select, textarea {
+ font-family: sans-serif;
+ font-size: 100%;
+ line-height: 1.15;
+ margin: 0
+}
+
+button, input {
+ overflow: visible
+}
+
+button, select {
+ text-transform: none
+}
+
+[type=reset], [type=submit], button, html [type=button] {
+ -webkit-appearance: button
+}
+
+[type=button]::-moz-focus-inner, [type=reset]::-moz-focus-inner, [type=submit]::-moz-focus-inner, button::-moz-focus-inner {
+ border-style: none;
+ padding: 0
+}
+
+[type=button]:-moz-focusring, [type=reset]:-moz-focusring, [type=submit]:-moz-focusring, button:-moz-focusring {
+ outline: 1px dotted ButtonText
+}
+
+fieldset {
+ padding: .35em .75em .625em
+}
+
+legend {
+ box-sizing: border-box;
+ color: inherit;
+ display: table;
+ max-width: 100%;
+ padding: 0;
+ white-space: normal
+}
+
+progress {
+ display: inline-block;
+ vertical-align: baseline
+}
+
+textarea {
+ overflow: auto
+}
+
+[type=checkbox], [type=radio] {
+ box-sizing: border-box;
+ padding: 0
+}
+
+[type=number]::-webkit-inner-spin-button, [type=number]::-webkit-outer-spin-button {
+ height: auto
+}
+
+[type=search] {
+ -webkit-appearance: textfield;
+ outline-offset: -2px
+}
+
+[type=search]::-webkit-search-cancel-button, [type=search]::-webkit-search-decoration {
+ -webkit-appearance: none
+}
+
+::-webkit-file-upload-button {
+ -webkit-appearance: button;
+ font: inherit
+}
+
+details, menu {
+ display: block
+}
+
+summary {
+ display: list-item
+}
+
+canvas {
+ display: inline-block
+}
+
+template {
+ display: none
+}
+
+[hidden] {
+ display: none
+}
+
+/* configuration cache styles */
+
+.report-wrapper {
+ margin: 0;
+ padding: 0 24px;
+}
+
+.gradle-logo {
+ width: 32px;
+ height: 24px;
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAYAAACbU/80AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAGAAAAAA915G0AAAD5klEQVRIDbVWC0xTZxT+emmhVUEeA1/ROh/tFAFFGK7oJisIKsNVoOwBbJPowEWHzikRxeiMRpwwjDWRBHQLIzOmiRhe22BT40TitiyaMBQFfMEeLMIEaSmk+/+rvd7be4no6Elu7n++c/5zzv845/wyOyG4iGyDgzCdNOPLM9W41n4bnmNUiHo5DNsz0hGsmcV6lbkyAOOWXJjrz4qWp1C4o3z/LqzWL4VcJB1FIHmZHn/f78a6pDcxbeIEfNvQiPwTZbDZBpC24zOEaGfDpTsgtZby6u+QlrubFWUY3nh6AH39/ahr/Bn1jZfxW3ML2js60dtvgbtcQVblj8CZM7A0PBSrol6Ft+c4KZ8iTB1nwN0//8IEP9/hA2i924Gir0/iq8oa/NvbJzLiDKiUSqTE6pGVbEBY4BxnsYAPSnwXTa3tLCZ5BF3dPdAkGNHzoFcwcaRMnC4CeZkZiAgKFE252nITC1Pew9Dj5GNEGgS4Rbb5eZ1Te7UXG6FLX4cV6zeh5kIDaDpSunL9Boyf5nLOpwT4Sx+BxWrFK8QAnTAapPRQwofcj86uLoG59cbVEOzA0NAQNh38Atn5RSjY8rFAmc/I3dyQvOx1PsSNVy7Roa3ajHDePbBYLSLn1MaGd5KFAXy07xAOl59C6elK+I73hIHcbGd6wXs8qkyH8FZcjLOI5X/9/TrOnLsAldJDUu4As1NToFFPe3IEpm/M2HigwCFnU6t4Zw6Ck1JhGRhgcXq5juXloKyqFnlHirmz5CaNcEAv59kSE9wVikcB3O78A/MSU0Fznk/H9+yAetJEnPr+B8RFLsLcGS8ia28+qQuX+WrPNNZOV+Nc6VH4+3iz89g0pEaLzRUiQ3LGDWsM8Qidq2WL0PGKKlgf74ZIeQTAfFJ6a44WIsDXh9OW/dPdY58aawC9KK6kpOgolO7JxViVSuBGXnvxksudZ5F0O5yzGYxMJnBOGaau4fnPU2RNAtCFBKFoa7akczaAptY2iWmjB33+yQa4kZwfjpi2ex3Dyf43vuAljWQ/4Btmei1WPj+q45hF4U+1J4fEizCEvNf0EWHoIW244sfzoN1RipaT2kDfdjfv3MNpojdISjmfIheE8Fnp8WR9vJ2Zr+O+bYUmO+kJ9KnIUtf9bnvY2x9wcqrrvnCJvfL8Tw4V9v9LU7PdKzJaoNdy645AR4ph1JMncZHRKrVvYyYY5kmP8iO1v2T3dk6HDtYmrgJtOnwKnaPFrg8z+BBX7QSgEyOPJfX9Qd9DFs40GgTOHbrBs2ch4bXFuEG2mmFkeD9hpUMk+NMXEe0TNtsg/Ly94DVurEAuxfwHC1WiVbe0U7MAAAAASUVORK5CYII=");
+ background-size: contain;
+}
+
+.header {
+ display: flex;
+ flex-wrap: wrap;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ padding: 24px 24px 0 24px;
+ background-color: white;
+ z-index: 1;
+}
+
+.learn-more {
+ margin-left: auto;
+ align-self: center;
+ font-size: 0.875rem;
+ font-weight: normal;
+}
+
+.title {
+ display: flex;
+ align-items: center;
+ padding: 18px 0 24px 0;
+ flex: 1 0 100%;
+}
+
+.content {
+ font-size: 0.875rem;
+ padding: 240px 0 48px;
+ overflow-x: auto;
+ white-space: nowrap;
+}
+
+.content ol:first-of-type {
+ margin: 0;
+}
+
+.tree-btn {
+ cursor: pointer;
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-top: -0.2em;
+}
+
+.tree-btn.collapsed {
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512"><path d="M166.9 264.5l-117.8 116c-4.7 4.7-12.3 4.7-17 0l-7.1-7.1c-4.7-4.7-4.7-12.3 0-17L127.3 256 25.1 155.6c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0l117.8 116c4.6 4.7 4.6 12.3-.1 17z" fill="%23999999" stroke="%23999999"/></svg>');
+}
+
+.tree-btn.expanded {
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 512"><path d="M119.5 326.9L3.5 209.1c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0L128 287.3l100.4-102.2c4.7-4.7 12.3-4.7 17 0l7.1 7.1c4.7 4.7 4.7 12.3 0 17L136.5 327c-4.7 4.6-12.3 4.6-17-.1z" fill="%23999999" stroke="%23999999"/></svg>');
+}
+
+ul .tree-btn {
+ margin-right: 3px;
+}
+
+.leaf-icon {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 512"><path d="M32 256 H224" stroke="%23999999" stroke-width="48" stroke-linecap="round"/></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-top: -0.2em;
+}
+
+.invisible-text {
+ user-select: all; /* Allow the text to be selectable */
+ color: transparent; /* Hide the text */
+ text-indent: -9999px; /* Move the text out of view */
+ position: relative;
+ white-space: pre; /* Preserve meaningful whitespace in the invisible text for copying */
+}
+
+.text-for-copy {
+ display: inline-block;
+}
+
+.enum-icon {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><circle cx="512" cy="512" r="200" /></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.5ex;
+ margin-inline-end: 0.5ex;
+ margin-top: -0.2em;
+}
+
+.error-icon {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M193.94 256L296.5 153.44l21.15-21.15c3.12-3.12 3.12-8.19 0-11.31l-22.63-22.63c-3.12-3.12-8.19-3.12-11.31 0L160 222.06 36.29 98.34c-3.12-3.12-8.19-3.12-11.31 0L2.34 120.97c-3.12 3.12-3.12 8.19 0 11.31L126.06 256 2.34 379.71c-3.12 3.12-3.12 8.19 0 11.31l22.63 22.63c3.12 3.12 8.19 3.12 11.31 0L160 289.94 262.56 392.5l21.15 21.15c3.12 3.12 8.19 3.12 11.31 0l22.63-22.63c3.12-3.12 3.12-8.19 0-11.31L193.94 256z" fill="%23FC461E" stroke="%23FC461E"/></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.5ex;
+ margin-inline-end: 0.5ex;
+ margin-top: -0.2em;
+}
+
+.advice-icon {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-image: url('data:image/svg+xml;utf8,<svg width="800px" height="800px" viewBox="-4.93 0 122.88 122.88" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="enable-background:new 0 0 113.01 122.88" xml:space="preserve"><g><path d="M44.13,102.06c-1.14,0.03-2.14-0.81-2.3-1.96c-0.17-1.2,0.64-2.31,1.82-2.54c-1.3-7.37-4.85-11.43-8.6-15.72 c-2.92-3.34-5.95-6.81-8.34-11.92c-2.35-5.03-3.64-10.23-3.6-15.63c0.05-5.4,1.42-10.96,4.4-16.71c0.02-0.04,0.04-0.07,0.06-0.11 l0,0c3.91-6.62,9.38-11.04,15.47-13.52c5.11-2.09,10.66-2.8,16.1-2.3c5.42,0.5,10.73,2.2,15.37,4.94 c5.9,3.49,10.75,8.67,13.42,15.21c1.44,3.54,2.42,7.49,2.54,11.82c0.12,4.31-0.62,8.96-2.61,13.88 c-2.66,6.59-6.18,10.68-9.47,14.51c-3.03,3.53-5.85,6.81-7.42,11.84c0.89,0.21,1.59,0.94,1.73,1.9c0.17,1.24-0.7,2.39-1.94,2.56 l-0.77,0.11c-0.14,1.09-0.23,2.26-0.27,3.51l0.25-0.04c1.24-0.17,2.39,0.7,2.56,1.94c0.17,1.24-0.7,2.39-1.94,2.56l-0.78,0.11 c0.01,0.15,0.02,0.3,0.03,0.45l0,0c0.07,0.88,0.08,1.73,0.03,2.54l0.13-0.02c1.25-0.15,2.38,0.74,2.54,1.98 c0.15,1.25-0.74,2.38-1.98,2.54l-1.68,0.21c-1.2,3.11-3.34,5.48-5.87,6.94c-1.74,1.01-3.67,1.59-5.61,1.71 c-1.97,0.12-3.96-0.25-5.78-1.13c-2.08-1.02-3.94-2.71-5.29-5.14c-0.65-0.33-1.13-0.97-1.23-1.75c-0.04-0.31-0.01-0.61,0.07-0.89 c-0.39-1.16-0.68-2.43-0.87-3.83l-0.07,0.01c-1.24,0.17-2.39-0.7-2.56-1.94c-0.17-1.24,0.7-2.39,1.94-2.56l0.54-0.08 C44.19,104.32,44.18,103.16,44.13,102.06L44.13,102.06z M2.18,58.86C1.01,58.89,0.04,57.98,0,56.81c-0.04-1.17,0.88-2.14,2.05-2.18 l8.7-0.3c1.17-0.04,2.14,0.88,2.18,2.05c0.04,1.17-0.88,2.14-2.05,2.18L2.18,58.86L2.18,58.86z M110.68,50.25 c1.16-0.12,2.2,0.73,2.32,1.89c0.12,1.16-0.73,2.2-1.89,2.32l-8.66,0.91c-1.16,0.12-2.2-0.73-2.32-1.89 c-0.12-1.16,0.73-2.2,1.89-2.32L110.68,50.25L110.68,50.25z M94.91,14.78c0.65-0.97,1.96-1.23,2.93-0.58 c0.97,0.65,1.23,1.96,0.58,2.93l-4.84,7.24c-0.65,0.97-1.96,1.23-2.93,0.58c-0.97-0.65-1.23-1.96-0.58-2.93L94.91,14.78 L94.91,14.78z M57.63,2.06c0.03-1.17,1-2.09,2.16-2.06c1.17,0.03,2.09,1,2.06,2.16l-0.22,8.7c-0.03,1.17-1,2.09-2.16,2.06 c-1.17-0.03-2.09-1-2.06-2.16L57.63,2.06L57.63,2.06z M13.88,15.53c-0.86-0.8-0.9-2.14-0.11-2.99c0.8-0.86,2.14-0.9,2.99-0.11 l6.37,5.94c0.86,0.8,0.9,2.14,0.11,2.99c-0.8,0.86-2.14,0.9-2.99,0.11L13.88,15.53L13.88,15.53z M47.88,96.95l18.49-2.63 c1.59-6.7,5.05-10.73,8.8-15.08c3.08-3.58,6.36-7.4,8.76-13.34c1.76-4.35,2.41-8.43,2.31-12.19c-0.1-3.75-0.96-7.21-2.24-10.34 c-2.3-5.63-6.51-10.11-11.65-13.15c-4.11-2.43-8.8-3.94-13.59-4.37c-4.77-0.44-9.64,0.19-14.13,2.02 c-5.26,2.15-9.99,5.97-13.39,11.72c-2.64,5.12-3.86,10.02-3.9,14.73c-0.04,4.74,1.11,9.33,3.2,13.8c2.13,4.56,4.97,7.8,7.69,10.92 C42.47,83.9,46.48,88.49,47.88,96.95L47.88,96.95z M65.62,99.02l-17.27,2.45c0.05,1.1,0.07,2.25,0.05,3.47l17.05-2.42 C65.47,101.29,65.52,100.12,65.62,99.02L65.62,99.02z M48.49,109.52c0.12,0.92,0.3,1.76,0.53,2.54l16.55-2.04 c0.11-0.86,0.13-1.77,0.05-2.74l0,0l0-0.02l-0.01-0.17L48.49,109.52L48.49,109.52z M51.37,116.36c0.64,0.67,1.35,1.19,2.1,1.55 c1.15,0.56,2.42,0.79,3.67,0.72c1.29-0.08,2.57-0.47,3.74-1.15c1.1-0.64,2.09-1.53,2.88-2.65L51.37,116.36L51.37,116.36z"/></g></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.5ex;
+ margin-inline-end: 0.5ex;
+ margin-top: -0.2em;
+}
+
+.warning-icon {
+ display: inline-block;
+ width: 13px;
+ height: 13px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M270.2 160h35.5c3.4 0 6.1 2.8 6 6.2l-7.5 196c-.1 3.2-2.8 5.8-6 5.8h-20.5c-3.2 0-5.9-2.5-6-5.8l-7.5-196c-.1-3.4 2.6-6.2 6-6.2zM288 388c-15.5 0-28 12.5-28 28s12.5 28 28 28 28-12.5 28-28-12.5-28-28-28zm281.5 52L329.6 24c-18.4-32-64.7-32-83.2 0L6.5 440c-18.4 31.9 4.6 72 41.6 72H528c36.8 0 60-40 41.5-72zM528 480H48c-12.3 0-20-13.3-13.9-24l240-416c6.1-10.6 21.6-10.7 27.7 0l240 416c6.2 10.6-1.5 24-13.8 24z" fill="%23DEAD22" stroke="%23DEAD22"/></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.3ex;
+ margin-inline-end: 1.1ex;
+ margin-top: -0.1em;
+}
+
+.documentation-button {
+ cursor: pointer;
+ display: inline-block;
+ width: 13px;
+ height: 13px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 340c-15.464 0-28 12.536-28 28s12.536 28 28 28 28-12.536 28-28-12.536-28-28-28zm7.67-24h-16c-6.627 0-12-5.373-12-12v-.381c0-70.343 77.44-63.619 77.44-107.408 0-20.016-17.761-40.211-57.44-40.211-29.144 0-44.265 9.649-59.211 28.692-3.908 4.98-11.054 5.995-16.248 2.376l-13.134-9.15c-5.625-3.919-6.86-11.771-2.645-17.177C185.658 133.514 210.842 116 255.67 116c52.32 0 97.44 29.751 97.44 80.211 0 67.414-77.44 63.849-77.44 107.408V304c0 6.627-5.373 12-12 12zM256 40c118.621 0 216 96.075 216 216 0 119.291-96.61 216-216 216-119.244 0-216-96.562-216-216 0-119.203 96.602-216 216-216m0-32C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8z" fill="%23999999" stroke="%23999999"/></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.5ex;
+ margin-inline-end: 0.5ex;
+ margin-top: -0.2em;
+}
+
+.documentation-button::selection {
+ color: transparent;
+}
+
+.documentation-button:hover {
+ color: transparent;
+}
+
+.copy-button {
+ cursor: pointer;
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M433.941 193.941l-51.882-51.882A48 48 0 0 0 348.118 128H320V80c0-26.51-21.49-48-48-48h-66.752C198.643 13.377 180.858 0 160 0s-38.643 13.377-45.248 32H48C21.49 32 0 53.49 0 80v288c0 26.51 21.49 48 48 48h80v48c0 26.51 21.49 48 48 48h224c26.51 0 48-21.49 48-48V227.882a48 48 0 0 0-14.059-33.941zm-22.627 22.627a15.888 15.888 0 0 1 4.195 7.432H352v-63.509a15.88 15.88 0 0 1 7.431 4.195l51.883 51.882zM160 30c9.941 0 18 8.059 18 18s-8.059 18-18 18-18-8.059-18-18 8.059-18 18-18zM48 384c-8.822 0-16-7.178-16-16V80c0-8.822 7.178-16 16-16h66.752c6.605 18.623 24.389 32 45.248 32s38.643-13.377 45.248-32H272c8.822 0 16 7.178 16 16v48H176c-26.51 0-48 21.49-48 48v208H48zm352 96H176c-8.822 0-16-7.178-16-16V176c0-8.822 7.178-16 16-16h144v72c0 13.2 10.8 24 24 24h72v208c0 8.822-7.178 16-16 16z" fill="%23999999" stroke="%23999999"/></svg>');
+ background-size: contain;
+ background-repeat: no-repeat;
+ vertical-align: middle;
+ margin-inline-start: 0.5ex;
+ margin-top: -0.2em;
+}
+
+.groups{
+ display: flex;
+ border-bottom: 1px solid #EDEEEF;
+ flex: 1 0 100%;
+}
+
+.uncategorized {
+ display: flex;
+ border-top: 4px solid #EDEEEF;
+ flex: 1 0 100%;
+}
+
+.group-selector {
+ padding: 0 52px 24px 0;
+ font-size: 0.9rem;
+ font-weight: bold;
+ color: #999999;
+ cursor: pointer;
+}
+
+.group-selector__count {
+ margin: 0 8px;
+ border-radius: 8px;
+ background-color: #999;
+ color: #fff;
+ padding: 1px 8px 2px;
+ font-size: 0.75rem;
+}
+
+.group-selector--active {
+ color: #02303A;
+ cursor: auto;
+}
+
+.group-selector--active .group-selector__count {
+ background-color: #686868;
+}
+
+.group-selector--disabled {
+ cursor: not-allowed;
+}
+
+.accordion-header {
+ cursor: pointer;
+}
+
+.container {
+ padding-left: 0.5em;
+ padding-right: 0.5em;
+}
+
+.stacktrace {
+ border-radius: 4px;
+ overflow-x: auto;
+ padding: 0.5rem;
+ margin-bottom: 0;
+ min-width: 1000px;
+}
+
+/* Lato (bold, regular) */
+@font-face {
+ font-display: swap;
+ font-family: Lato;
+ font-weight: 500;
+ font-style: normal;
+ src: url("https://assets.gradle.com/lato/fonts/lato-semibold/lato-semibold.woff2") format("woff2"),
+ url("https://assets.gradle.com/lato/fonts/lato-semibold/lato-semibold.woff") format("woff");
+}
+
+@font-face {
+ font-display: swap;
+ font-family: Lato;
+ font-weight: bold;
+ font-style: normal;
+ src: url("https://assets.gradle.com/lato/fonts/lato-bold/lato-bold.woff2") format("woff2"),
+ url("https://assets.gradle.com/lato/fonts/lato-bold/lato-bold.woff") format("woff");
+}
+
+* {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+
+html,
+body {
+ margin: 0;
+ padding: 0;
+}
+
+html {
+ font-family: "Lato", "Helvetica Neue", Arial, sans-serif;
+ font-size: 16px;
+ font-weight: 400;
+ line-height: 1.5;
+}
+
+body {
+ color: #02303A;
+ background-color: #ffffff;
+ -webkit-text-size-adjust: 100%;
+ -ms-text-size-adjust: 100%;
+ -webkit-font-smoothing: antialiased;
+}
+
+
+/* typography */
+h1, h2, h3, h4, h5, h6 {
+ color: #02303A;
+ text-rendering: optimizeLegibility;
+ margin: 0;
+}
+
+h1 {
+ font-size: 1rem;
+}
+
+h2 {
+ font-size: 0.9rem;
+}
+
+h3 {
+ font-size: 1.125rem;
+}
+
+h4, h5, h6 {
+ font-size: 0.875rem;
+}
+
+h1 code {
+ font-weight: bold;
+}
+
+ul, ol, dl {
+ list-style-position: outside;
+ line-height: 1.6;
+ padding: 0;
+ margin: 0 0 0 20px;
+ list-style-type: none;
+}
+
+li {
+ line-height: 2;
+}
+
+a {
+ color: #1DA2BD;
+ text-decoration: none;
+ transition: all 0.3s ease, visibility 0s;
+}
+
+a:hover {
+ color: #35c1e4;
+}
+
+/* code */
+code, pre {
+ font-family: Inconsolata, Monaco, "Courier New", monospace;
+ font-style: normal;
+ font-variant-ligatures: normal;
+ font-variant-caps: normal;
+ font-variant-numeric: normal;
+ font-variant-east-asian: normal;
+ font-weight: normal;
+ font-stretch: normal;
+ color: #686868;
+}
+
+*:not(pre) > code {
+ letter-spacing: 0;
+ padding: 0.1em 0.5ex;
+ text-rendering: optimizeSpeed;
+ word-spacing: -0.15em;
+ word-wrap: break-word;
+}
+
+pre {
+ font-size: 0.75rem;
+ line-height: 1.8;
+ margin-top: 0;
+ margin-bottom: 1.5em;
+ padding: 1rem;
+}
+
+pre code {
+ background-color: transparent;
+ color: inherit;
+ line-height: 1.8;
+ font-size: 100%;
+ padding: 0;
+}
+
+a code {
+ color: #1BA8CB;
+}
+
+pre.code, pre.programlisting, pre.screen, pre.tt {
+ background-color: #f7f7f8;
+ border-radius: 4px;
+ font-size: 1em;
+ line-height: 1.45;
+ margin-bottom: 1.25em;
+ overflow-x: auto;
+ padding: 1rem;
+}
+
+li em, p em {
+ padding: 0 1px;
+}
+
+code em, tt em {
+ text-decoration: none;
+}
+
+code + .copy-button {
+ margin-inline-start: 0.2ex;
+}
+
+.java-exception {
+ font-size: 0.75rem;
+ padding-left: 24px;
+}
+
+.java-exception ul {
+ margin: 0;
+ line-height: inherit;
+}
+
+.java-exception code {
+ white-space: pre;
+}
+
+.java-exception-part-toggle {
+ user-select: none;
+ cursor: pointer;
+ border-radius: 2px;
+ padding: 0.1em 0.2em;
+ background: azure;
+ color: #686868;
+}
+
+ </style>
+ <!-- Inconsolata is used as a default monospace font in the report. -->
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata:400,700" />
+
+ <title>Gradle Configuration Cache</title>
+</head>
+<body>
+
+<div id="playground"></div>
+
+<div class="report" id="report">
+ Loading...
+</div>
+
+<script type="text/javascript">
+function configurationCacheProblems() { return (
+// begin-report-data
+{"diagnostics":[{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('checkAllWarnings = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('warningsAsErrors = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('compileSdk = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('minSdk = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = <value>') instead."}]]},{"locations":[{}],"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.14/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = <value>') instead."}]]}],"problemsReport":{"totalProblemCount":15,"buildName":"android","requestedTasks":"assembleDebug","documentationLink":"https://docs.gradle.org/8.14/userguide/reporting_problems.html","documentationLinkCaption":"Problem report","summaries":[{"problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"count":13}]}}
+// end-report-data
+);}
+</script>
+ <script type="text/javascript">
+ !function(n,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["configuration-cache-report"]=t():n["configuration-cache-report"]=t()}(this,(()=>(({70:function(){void 0===ArrayBuffer.isView&&(ArrayBuffer.isView=function(n){return null!=n&&null!=n.__proto__&&n.__proto__.__proto__===Int8Array.prototype.__proto__}),void 0===Math.imul&&(Math.imul=function(n,t){return(4294901760&n)*(65535&t)+(65535&n)*(0|t)|0}),this["configuration-cache-report"]=function(n){"use strict";var t,r,i,e,u,o,f,s,c,a,h,l,_,v,d,g,w,b,p,m,k,q,y,B,C,x,j,P,I,S,z,T,E,L,N,A,M,F,D,O,R,H,$,G,U,V,Q,Z,Y,W,K,X,J,nn,tn,rn,en,un,on,fn,sn,cn,an,hn,ln,_n,vn,dn,gn,wn,bn,pn,mn,kn,qn,yn,Bn,Cn,xn,jn,Pn,In,Sn,zn,Tn,En,Ln,Nn,An,Mn=Math.imul,Fn=ArrayBuffer.isView;function Dn(n,t){if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));return function(n,t){if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));if(0===t)return Ct();if(t>=n.length)return function(n){switch(n.length){case 0:return Ct();case 1:return qr(n[0]);default:return function(n){return Hr(function(n){return new It(n,!1)}(n))}(n)}}(n);if(1===t)return qr(n[0]);var r=0,i=Rr(),e=0,u=n.length;n:for(;e<u;){var o=n[e];if(e=e+1|0,i.d(o),(r=r+1|0)===t)break n}return i}(n,rt(n.length-t|0,0))}function On(n,t,r,i,e,u,o){return t=t===A?", ":t,r=r===A?"":r,i=i===A?"":i,e=e===A?-1:e,u=u===A?"...":u,o=o===A?null:o,function(n,t,r,i,e,u,o,f){r=r===A?", ":r,i=i===A?"":i,e=e===A?"":e,u=u===A?-1:u,o=o===A?"...":o,f=f===A?null:f,t.e(i);var s=0,c=0,a=n.length;n:for(;c<a;){var h=n[c];if(c=c+1|0,(s=s+1|0)>1&&t.e(r),!(u<0||s<=u))break n;Jt(t,h,f)}return u>=0&&s>u&&t.e(o),t.e(e),t}(n,Bi(),t,r,i,e,u,o).toString()}function Rn(n){return n.length-1|0}function Hn(n,t){if(null==t){var r=0,i=n.length-1|0;if(r<=i)do{var e=r;if(r=r+1|0,null==n[e])return e}while(r<=i)}else{var u=0,o=n.length-1|0;if(u<=o)do{var f=u;if(u=u+1|0,le(t,n[f]))return f}while(u<=o)}return-1}function $n(n,t,r,i,e,u,o){return t=t===A?", ":t,r=r===A?"":r,i=i===A?"":i,e=e===A?-1:e,u=u===A?"...":u,o=o===A?null:o,Gn(n,Bi(),t,r,i,e,u,o).toString()}function Gn(n,t,r,i,e,u,o,f){r=r===A?", ":r,i=i===A?"":i,e=e===A?"":e,u=u===A?-1:u,o=o===A?"...":o,f=f===A?null:f,t.e(i);var s=0,c=n.f();n:for(;c.g();){var a=c.h();if((s=s+1|0)>1&&t.e(r),!(u<0||s<=u))break n;Jt(t,a,f)}return u>=0&&s>u&&t.e(o),t.e(e),t}function Un(n){if(n.i())throw xu("List is empty.");return n.j(0)}function Vn(n){return new tt(n)}function Qn(n){if(Ke(n,Di)){var t;switch(n.k()){case 0:t=Ct();break;case 1:t=qr(Ke(n,Fi)?n.j(0):n.f().h());break;default:t=Zn(n)}return t}return xt(Xn(n))}function Zn(n){return Hr(n)}function Yn(n){if(Ke(n,Di)&&n.k()<=1)return Qn(n);var t=Xn(n);return function(n){var t=(n.k()/2|0)-1|0;if(t<0)return br();var r=jt(n),i=0;if(i<=t)do{var e=i;i=i+1|0;var u=n.j(e);n.f4(e,n.j(r)),n.f4(r,u),r=r-1|0}while(e!==t)}(t),t}function Wn(n,t){if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));return function(n,t){if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));if(0===t)return Ct();if(Ke(n,Di)){if(t>=n.k())return Qn(n);if(1===t)return qr(function(n){if(Ke(n,Fi))return Un(n);var t=n.f();if(!t.g())throw xu("Collection is empty.");return t.h()}(n))}var r=0,i=Rr(),e=n.f();n:for(;e.g();){var u=e.h();if(i.d(u),(r=r+1|0)===t)break n}return xt(i)}(n,rt(n.k()-t|0,0))}function Kn(n,t){if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));if(0===t)return Ct();var r=n.k();if(t>=r)return Qn(n);if(1===t)return qr(Jn(n));var i=Rr();if(Ke(n,bi)){var e=r-t|0;if(e<r)do{var u=e;e=e+1|0,i.d(n.j(u))}while(e<r)}else for(var o=n.l(r-t|0);o.g();){var f=o.h();i.d(f)}return i}function Xn(n){return Ke(n,Di)?Zn(n):nt(n,Or())}function Jn(n){if(n.i())throw xu("List is empty.");return n.j(jt(n))}function nt(n,t){for(var r=n.f();r.g();){var i=r.h();t.d(i)}return t}function tt(n){this.n_1=n}function rt(n,t){return n<t?t:n}function it(n,t){return n>t?t:n}function et(n,t){return Kt().q(n,t,-1)}function ut(n,t){return new Ft(n,t)}function ot(n){var t=n.f();if(!t.g())return Ct();var r=t.h();if(!t.g())return qr(r);var i=Or();for(i.d(r);t.g();)i.d(t.h());return i}function ft(n){this.r_1=n}function st(n,t){this.s_1=n,this.t_1=t}function ct(){}function at(n){this.x_1=n,this.w_1=0}function ht(n,t){this.a1_1=n,at.call(this,n),_t().b1(t,this.a1_1.k()),this.w_1=t}function lt(){t=this}function _t(){return null==t&&new lt,t}function vt(){_t(),ct.call(this)}function dt(n){this.h1_1=n}function gt(n,t){return t===n?"(this Map)":Vi(t)}function wt(n,t){var r;n:{for(var i=n.o().f();i.g();){var e=i.h();if(le(e.j1(),t)){r=e;break n}}r=null}return r}function bt(){r=this}function pt(){return null==r&&new bt,r}function mt(n){this.q1_1=n,ct.call(this)}function kt(){pt(),this.n1_1=null,this.o1_1=null}function qt(){i=this}function yt(){return null==i&&new qt,i}function Bt(n){return n.length>0?ou(n):Ct()}function Ct(){return null==e&&new Pt,e}function xt(n){switch(n.k()){case 0:return Ct();case 1:return qr(n.j(0));default:return n}}function jt(n){return n.k()-1|0}function Pt(){e=this,this.z1_1=new ke(-1478467534,-1720727600)}function It(n,t){this.b2_1=n,this.c2_1=t}function St(){u=this}function zt(){return null==u&&new St,u}function Tt(n,t){return Ke(n,Di)?n.k():t}function Et(n,t){if(Ke(t,Di))return n.m(t);for(var r=!1,i=t.f();i.g();){var e=i.h();n.d(e)&&(r=!0)}return r}function Lt(){}function Nt(n,t){this.h2_1=n,this.g2_1=n.i2_1.l(function(n,t){if(!(0<=t&&t<=n.k()))throw du("Position index "+t+" must be in range ["+Ve(0,n.k())+"].");return n.k()-t|0}(n,t))}function At(n){vt.call(this),this.i2_1=n}function Mt(n){this.k2_1=n,this.j2_1=n.l2_1.f()}function Ft(n,t){this.l2_1=n,this.m2_1=t}function Dt(n){for(;n.n2_1.g();){var t=n.n2_1.h();if(n.q2_1.t2_1(t)===n.q2_1.s2_1)return n.p2_1=t,n.o2_1=1,br()}n.o2_1=0}function Ot(n){this.q2_1=n,this.n2_1=n.r2_1.f(),this.o2_1=-1,this.p2_1=null}function Rt(n,t,r){t=t===A||t,this.r2_1=n,this.s2_1=t,this.t2_1=r}function Ht(){return null==o&&new $t,o}function $t(){o=this,this.u2_1=new ke(1993859828,793161749)}function Gt(n,t,r){return Ut(Ut(n,r)-Ut(t,r)|0,r)}function Ut(n,t){var r=n%t|0;return r>=0?r:r+t|0}function Vt(){f=this,this.p_1=new Zt(1,0)}function Qt(){return null==f&&new Vt,f}function Zt(n,t){Qt(),Xt.call(this,n,t,1)}function Yt(n,t,r){Lt.call(this),this.d3_1=r,this.e3_1=t,this.f3_1=this.d3_1>0?n<=t:n>=t,this.g3_1=this.f3_1?n:this.e3_1}function Wt(){s=this}function Kt(){return null==s&&new Wt,s}function Xt(n,t,r){if(Kt(),0===r)throw _u("Step must be non-zero.");if(r===mr().MIN_VALUE)throw _u("Step must be greater than Int.MIN_VALUE to avoid overflow on negation.");this.z2_1=n,this.a3_1=function(n,t,r){var i;if(r>0)i=n>=t?t:t-Gt(t,n,r)|0;else{if(!(r<0))throw _u("Step is zero.");i=n<=t?t:t+Gt(n,t,0|-r)|0}return i}(n,t,r),this.b3_1=r}function Jt(n,t,r){null!=r?n.e(r(t)):null==t||nu(t)?n.e(t):t instanceof Mi?n.i3(t.h3_1):n.e(Vi(t))}function nr(n,t,r){if(n===t)return!0;if(!(r=r!==A&&r))return!1;var i=xi(n),e=xi(t);return i===e||le(new Mi(ne(Li(i).toLowerCase(),0)),new Mi(ne(Li(e).toLowerCase(),0)))}function tr(n){return re(n)-1|0}function rr(n,t,r,i){return r=r===A?0:r,(i=i!==A&&i)||"string"!=typeof n?ir(n,t,r,re(n),i):n.indexOf(t,r)}function ir(n,t,r,i,e,u){var o=(u=u!==A&&u)?et(it(r,tr(n)),rt(i,0)):Ve(rt(r,0),it(i,re(n)));if("string"==typeof n&&"string"==typeof t){var f=o.z2_1,s=o.a3_1,c=o.b3_1;if(c>0&&f<=s||c<0&&s<=f)do{var a=f;if(f=f+c|0,Ti(t,0,n,a,re(t),e))return a}while(a!==s)}else{var h=o.z2_1,l=o.a3_1,_=o.b3_1;if(_>0&&h<=l||_<0&&l<=h)do{var v=h;if(h=h+_|0,fr(t,0,n,v,re(t),e))return v}while(v!==l)}return-1}function er(n){var t=0,r=re(n)-1|0,i=!1;n:for(;t<=r;){var e=ji(ne(n,i?r:t));if(i){if(!e)break n;r=r-1|0}else e?t=t+1|0:i=!0}return ie(n,t,r+1|0)}function ur(n,t){return ce(ie(n,t.y2(),t.c3()+1|0))}function or(n,t,r,i,e){r=r===A?0:r,i=i!==A&&i,sr(e=e===A?0:e);var u,o,f=ou(t);return new hr(n,r,e,(u=f,o=i,function(n,t){var r=function(n,t,r,i){if(!i&&1===t.k()){var e=function(n){if(Ke(n,Fi))return function(n){var t;switch(n.k()){case 0:throw xu("List is empty.");case 1:t=n.j(0);break;default:throw _u("List has more than one element.")}return t}(n);var t=n.f();if(!t.g())throw xu("Collection is empty.");var r=t.h();if(t.g())throw _u("Collection has more than one element.");return r}(t),u=rr(n,e,r);return u<0?null:_r(u,e)}var o=Ve(rt(r,0),re(n));if("string"==typeof n){var f=o.z2_1,s=o.a3_1,c=o.b3_1;if(c>0&&f<=s||c<0&&s<=f)do{var a,h=f;f=f+c|0;n:{for(var l=t.f();l.g();){var _=l.h();if(Ti(_,0,n,h,_.length,i)){a=_;break n}}a=null}if(null!=a)return _r(h,a)}while(h!==s)}else{var v=o.z2_1,d=o.a3_1,g=o.b3_1;if(g>0&&v<=d||g<0&&d<=v)do{var w,b=v;v=v+g|0;n:{for(var p=t.f();p.g();){var m=p.h();if(fr(m,0,n,b,m.length,i)){w=m;break n}}w=null}if(null!=w)return _r(b,w)}while(b!==d)}return null}(n,u,t,o);return null==r?null:_r(r.t3_1,r.u3_1.length)}))}function fr(n,t,r,i,e,u){if(i<0||t<0||t>(re(n)-e|0)||i>(re(r)-e|0))return!1;var o=0;if(o<e)do{var f=o;if(o=o+1|0,!nr(ne(n,t+f|0),ne(r,i+f|0),u))return!1}while(o<e);return!0}function sr(n){if(!(n>=0))throw _u(ce("Limit must be non-negative, but was "+n))}function cr(n){if(n.l3_1<0)n.j3_1=0,n.m3_1=null;else{var t;if(n.o3_1.r3_1>0?(n.n3_1=n.n3_1+1|0,t=n.n3_1>=n.o3_1.r3_1):t=!1,t||n.l3_1>re(n.o3_1.p3_1))n.m3_1=Ve(n.k3_1,tr(n.o3_1.p3_1)),n.l3_1=-1;else{var r=n.o3_1.s3_1(n.o3_1.p3_1,n.l3_1);if(null==r)n.m3_1=Ve(n.k3_1,tr(n.o3_1.p3_1)),n.l3_1=-1;else{var i=r.v3(),e=r.w3();n.m3_1=function(n,t){return t<=mr().MIN_VALUE?Qt().p_1:Ve(n,t-1|0)}(n.k3_1,i),n.k3_1=i+e|0,n.l3_1=n.k3_1+(0===e?1:0)|0}}n.j3_1=1}}function ar(n){this.o3_1=n,this.j3_1=-1,this.k3_1=function(n,t,r){if(0>r)throw _u("Cannot coerce value to an empty range: maximum "+r+" is less than minimum 0.");return n<0?0:n>r?r:n}(n.q3_1,0,re(n.p3_1)),this.l3_1=this.k3_1,this.m3_1=null,this.n3_1=0}function hr(n,t,r,i){this.p3_1=n,this.q3_1=t,this.r3_1=r,this.s3_1=i}function lr(n,t){this.t3_1=n,this.u3_1=t}function _r(n,t){return new lr(n,t)}function vr(){}function dr(){}function gr(){}function wr(){c=this}function br(){return null==c&&new wr,c}function pr(){a=this,this.MIN_VALUE=-2147483648,this.MAX_VALUE=2147483647,this.SIZE_BYTES=4,this.SIZE_BITS=32}function mr(){return null==a&&new pr,a}function kr(n){for(var t=[],r=n.f();r.g();)t.push(r.h());return t}function qr(n){return 0===(t=[n]).length?Or():Hr(new It(t,!0));var t}function yr(n){return n<0&&function(){throw Pu("Index overflow has happened.")}(),n}function Br(n){return void 0!==n.toArray?n.toArray():kr(n)}function Cr(n){return function(n,t){for(var r=0,i=n.length;r<i;){var e=n[r];r=r+1|0,t.d(e)}return t}(t=[n],(r=t.length,i=de(ve(ni)),function(n,t,r){Mr.call(r),ni.call(r),r.y5_1=function(n){return Kr(n,0,de(ve(Xr)))}(n)}(r,0,i),i));var t,r,i}function xr(){ct.call(this)}function jr(n){this.j4_1=n,this.h4_1=0,this.i4_1=-1}function Pr(n,t){this.n4_1=n,jr.call(this,n),_t().b1(t,this.n4_1.k()),this.h4_1=t}function Ir(){xr.call(this),this.o4_1=0}function Sr(n){this.r4_1=n}function zr(n){this.s4_1=n}function Tr(n,t){this.t4_1=n,this.u4_1=t}function Er(){Mr.call(this)}function Lr(n){this.x4_1=n,Mr.call(this)}function Nr(n){this.e5_1=n,xr.call(this)}function Ar(){kt.call(this),this.c5_1=null,this.d5_1=null}function Mr(){xr.call(this)}function Fr(){h=this;var n=Rr();n.c_1=!0,this.i5_1=n}function Dr(){return null==h&&new Fr,h}function Or(){return n=de(ve(Gr)),t=[],Gr.call(n,t),n;var n,t}function Rr(n){return t=de(ve(Gr)),r=[],Gr.call(t,r),t;var t,r}function Hr(n){return function(n,t){var r;return r=Br(n),Gr.call(t,r),t}(n,de(ve(Gr)))}function $r(n,t){return _t().e1(t,n.k()),t}function Gr(n){Dr(),Ir.call(this),this.b_1=n,this.c_1=!1}function Ur(n,t,r,i,e){if(r===i)return n;var u=(r+i|0)/2|0,o=Ur(n,t,r,u,e),f=Ur(n,t,u+1|0,i,e),s=o===t?n:t,c=r,a=u+1|0,h=r;if(h<=i)do{var l=h;if(h=h+1|0,c<=u&&a<=i){var _=o[c],v=f[a];e.compare(_,v)<=0?(s[l]=_,c=c+1|0):(s[l]=v,a=a+1|0)}else c<=u?(s[l]=o[c],c=c+1|0):(s[l]=f[a],a=a+1|0)}while(l!==i);return s}function Vr(n,t){return(3&n)-(3&t)|0}function Qr(){_=this}function Zr(n){this.n5_1=n,Er.call(this)}function Yr(n){return function(n,t){Ar.call(t),Xr.call(t),t.t5_1=n,t.u5_1=n.w5()}(new ui((null==_&&new Qr,_)),n),n}function Wr(){return Yr(de(ve(Xr)))}function Kr(n,t,r){if(Yr(r),!(n>=0))throw _u(ce("Negative initial capacity: "+n));if(!(t>=0))throw _u(ce("Non-positive load factor: "+t));return r}function Xr(){this.v5_1=null}function Jr(n,t){return Mr.call(t),ni.call(t),t.y5_1=n,t}function ni(){}function ti(n,t){var r=ii(n,n.h6_1.m5(t));if(null==r)return null;var i=r;if(null!=i&&Xe(i))return ri(i,n,t);var e=i;return n.h6_1.l5(e.j1(),t)?e:null}function ri(n,t,r){var i;n:{for(var e=0,u=n.length;e<u;){var o=n[e];if(e=e+1|0,t.h6_1.l5(o.j1(),r)){i=o;break n}}i=null}return i}function ii(n,t){var r=n.i6_1[t];return void 0===r?null:r}function ei(n){this.g6_1=n,this.z5_1=-1,this.a6_1=Object.keys(n.i6_1),this.b6_1=-1,this.c6_1=null,this.d6_1=!1,this.e6_1=-1,this.f6_1=null}function ui(n){this.h6_1=n,this.i6_1=this.k6(),this.j6_1=0}function oi(){}function fi(n){this.n6_1=n,this.l6_1=null,this.m6_1=null,this.m6_1=this.n6_1.y6_1.v6_1}function si(){v=this;var n,t=(_i(0,0,n=de(ve(vi))),n);t.x6_1=!0,this.e7_1=t}function ci(){return null==v&&new si,v}function ai(n,t,r){this.d7_1=n,Tr.call(this,t,r),this.b7_1=null,this.c7_1=null}function hi(n){this.y6_1=n,Er.call(this)}function li(){return Yr(n=de(ve(vi))),vi.call(n),n.w6_1=Wr(),n;var n}function _i(n,t,r){return Kr(n,t,r),vi.call(r),r.w6_1=Wr(),r}function vi(){ci(),this.v6_1=null,this.x6_1=!1}function di(){d=this;var n=gi(0),t=n.y5_1;(t instanceof vi?t:pe()).j5(),this.f7_1=n}function gi(n){return function(n,t){return function(n,t,r){Jr(function(n,t){return _i(n,t,de(ve(vi)))}(n,t),r),wi.call(r)}(n,0,t),t}(n,de(ve(wi)))}function wi(){null==d&&new di}function bi(){}function pi(){}function mi(n){pi.call(this),this.k7_1=n}function ki(){qi.call(this)}function qi(){pi.call(this),this.m7_1=""}function yi(){if(!w){w=!0;var n="undefined"!=typeof process&&process.versions&&!!process.versions.node;g=n?new mi(process.stdout):new ki}}function Bi(){return n=de(ve(Ci)),Ci.call(n,""),n;var n}function Ci(n){this.o7_1=void 0!==n?n:""}function xi(n){var t=Li(n).toUpperCase();return t.length>1?n:ne(t,0)}function ji(n){return function(n){return 9<=n&&n<=13||28<=n&&n<=32||160===n||n>4096&&(5760===n||8192<=n&&n<=8202||8232===n||8233===n||8239===n||8287===n||12288===n)}(n)}function Pi(){b=this,this.q7_1=new RegExp("[\\\\^$*+?.()|[\\]{}]","g"),this.r7_1=new RegExp("[\\\\$]","g"),this.s7_1=new RegExp("\\$","g")}function Ii(){return null==b&&new Pi,b}function Si(n,t){Ii(),this.v7_1=n,this.w7_1=function(n){if(Ke(n,Di)){var t;switch(n.k()){case 0:t=Ht();break;case 1:t=Cr(Ke(n,Fi)?n.j(0):n.f().h());break;default:t=nt(n,gi(n.k()))}return t}return function(n){switch(n.k()){case 0:return Ht();case 1:return Cr(n.f().h());default:return n}}(nt(n,(r=de(ve(wi)),Jr(li(),r),wi.call(r),r)));var r}(t),this.x7_1=new RegExp(n,$n(t,"","gu",A,A,A,zi)),this.y7_1=null,this.z7_1=null}function zi(n){return n.d8_1}function Ti(n,t,r,i,e,u){return fr(n,t,r,i,e,u=u!==A&&u)}function Ei(n,t){return n-t|0}function Li(n){return String.fromCharCode(n)}function Ni(){p=this,this.e8_1=0,this.f8_1=65535,this.g8_1=55296,this.h8_1=56319,this.i8_1=56320,this.j8_1=57343,this.k8_1=55296,this.l8_1=57343,this.m8_1=2,this.n8_1=16}function Ai(){return null==p&&new Ni,p}function Mi(n){Ai(),this.h3_1=n}function Fi(){}function Di(){}function Oi(){}function Ri(){}function Hi(){}function $i(){}function Gi(){m=this}function Ui(n,t){null==m&&new Gi,this.p8_1=n,this.q8_1=t}function Vi(n){var t=null==n?null:ce(n);return null==t?"null":t}function Qi(n){return new Zi(n)}function Zi(n){this.t8_1=n,this.s8_1=0}function Yi(){return Ji(),k}function Wi(){return Ji(),q}function Ki(){return Ji(),y}function Xi(){return Ji(),B}function Ji(){x||(x=!0,k=new ArrayBuffer(8),q=new Float64Array(Yi()),new Float32Array(Yi()),y=new Int32Array(Yi()),Wi()[0]=-1,B=0!==Ki()[0]?1:0,C=1-Xi()|0)}function ne(n,t){var r;if(te(n)){var i,e=n.charCodeAt(t);if(Ai(),e<0?i=!0:(Ai(),i=e>65535),i)throw _u("Invalid Char code: "+e);r=Ue(e)}else r=n.y3(t);return r}function te(n){return"string"==typeof n}function re(n){return te(n)?n.length:n.x3()}function ie(n,t,r){return te(n)?n.substring(t,r):n.z3(t,r)}function ee(n){return ce(n)}function ue(n,t){var r;switch(typeof n){case"number":r="number"==typeof t?oe(n,t):t instanceof ke?oe(n,t.w8()):fe(n,t);break;case"string":case"boolean":r=fe(n,t);break;default:r=function(n,t){return n.a4(t)}(n,t)}return r}function oe(n,t){var r;if(n<t)r=-1;else if(n>t)r=1;else if(n===t){var i;if(0!==n)i=0;else{var e=1/n;i=e===1/t?0:e<0?-1:1}r=i}else r=n!=n?t!=t?0:1:-1;return r}function fe(n,t){return n<t?-1:n>t?1:0}function se(n){if(!("kotlinHashCodeValue$"in n)){var t=4294967296*Math.random()|0,r=new Object;r.value=t,r.enumerable=!1,Object.defineProperty(n,"kotlinHashCodeValue$",r)}return n.kotlinHashCodeValue$}function ce(n){return null==n?"null":function(n){return!!Ye(n)||Fn(n)}(n)?"[...]":n.toString()}function ae(n){if(null==n)return 0;var t;switch(typeof n){case"object":t="function"==typeof n.hashCode?n.hashCode():se(n);break;case"function":t=se(n);break;case"number":t=function(n){return Ji(),(0|n)===n?Ge(n):(Wi()[0]=n,Mn(Ki()[(Ji(),C)],31)+Ki()[Xi()]|0)}(n);break;case"boolean":t=n?1:0;break;default:t=he(String(n))}return t}function he(n){var t=0,r=0,i=n.length-1|0;if(r<=i)do{var e=r;r=r+1|0;var u=n.charCodeAt(e);t=Mn(t,31)+u|0}while(e!==i);return t}function le(n,t){return null==n?null==t:null!=t&&("object"==typeof n&&"function"==typeof n.equals?n.equals(t):n!=n?t!=t:"number"==typeof n&&"number"==typeof t?n===t&&(0!==n||1/n==1/t):n===t)}function _e(n,t){null!=Error.captureStackTrace?Error.captureStackTrace(n,t):n.stack=(new Error).stack}function ve(n){return n.prototype}function de(n){return Object.create(n)}function ge(n,t,r){Error.call(n),function(n,t,r){var i=eu(Object.getPrototypeOf(n));if(!(1&i)){var e;if(null==t){var u;if(null!==t){var o=null==r?null:r.toString();u=null==o?A:o}else u=A;e=u}else e=t;n.message=e}2&i||(n.cause=r),n.name=Object.getPrototypeOf(n).constructor.name}(n,t,r)}function we(n){var t;return null==n?function(){throw Eu()}():t=n,t}function be(){throw Nu()}function pe(){throw Mu()}function me(){j=this,this.x8_1=new ke(0,-2147483648),this.y8_1=new ke(-1,2147483647),this.z8_1=8,this.a9_1=64}function ke(n,t){null==j&&new me,gr.call(this),this.u8_1=n,this.v8_1=t}function qe(){return $e(),P}function ye(){return $e(),I}function Be(){return $e(),S}function Ce(){return $e(),T}function xe(){return $e(),E}function je(n,t){if($e(),Te(n,t))return 0;var r=Ne(n),i=Ne(t);return r&&!i?-1:!r&&i?1:Ne(Ie(n,t))?-1:1}function Pe(n,t){$e();var r=n.v8_1>>>16|0,i=65535&n.v8_1,e=n.u8_1>>>16|0,u=65535&n.u8_1,o=t.v8_1>>>16|0,f=65535&t.v8_1,s=t.u8_1>>>16|0,c=0,a=0,h=0,l=0;return c=(c=c+((a=(a=a+((h=(h=h+((l=l+(u+(65535&t.u8_1)|0)|0)>>>16|0)|0)+(e+s|0)|0)>>>16|0)|0)+(i+f|0)|0)>>>16|0)|0)+(r+o|0)|0,new ke((h&=65535)<<16|(l&=65535),(c&=65535)<<16|(a&=65535))}function Ie(n,t){return $e(),Pe(n,t.e9())}function Se(n,t){if($e(),Ae(n))return qe();if(Ae(t))return qe();if(Te(n,Ce()))return Me(t)?Ce():qe();if(Te(t,Ce()))return Me(n)?Ce():qe();if(Ne(n))return Ne(t)?Se(Fe(n),Fe(t)):Fe(Se(Fe(n),t));if(Ne(t))return Fe(Se(n,Fe(t)));if(De(n,xe())&&De(t,xe()))return Oe(ze(n)*ze(t));var r=n.v8_1>>>16|0,i=65535&n.v8_1,e=n.u8_1>>>16|0,u=65535&n.u8_1,o=t.v8_1>>>16|0,f=65535&t.v8_1,s=t.u8_1>>>16|0,c=65535&t.u8_1,a=0,h=0,l=0,_=0;return l=l+((_=_+Mn(u,c)|0)>>>16|0)|0,_&=65535,h=(h=h+((l=l+Mn(e,c)|0)>>>16|0)|0)+((l=(l&=65535)+Mn(u,s)|0)>>>16|0)|0,l&=65535,a=(a=(a=a+((h=h+Mn(i,c)|0)>>>16|0)|0)+((h=(h&=65535)+Mn(e,s)|0)>>>16|0)|0)+((h=(h&=65535)+Mn(u,f)|0)>>>16|0)|0,h&=65535,a=a+(((Mn(r,c)+Mn(i,s)|0)+Mn(e,f)|0)+Mn(u,o)|0)|0,new ke(l<<16|_,(a&=65535)<<16|h)}function ze(n){return $e(),4294967296*n.v8_1+function(n){return $e(),n.u8_1>=0?n.u8_1:4294967296+n.u8_1}(n)}function Te(n,t){return $e(),n.v8_1===t.v8_1&&n.u8_1===t.u8_1}function Ee(n,t){if($e(),t<2||36<t)throw mu("radix out of range: "+t);if(Ae(n))return"0";if(Ne(n)){if(Te(n,Ce())){var r=Le(t),i=n.d9(r),e=Ie(Se(i,r),n).g9();return Ee(i,t)+e.toString(t)}return"-"+Ee(Fe(n),t)}for(var u=2===t?31:t<=10?9:t<=21?7:t<=35?6:5,o=Oe(Math.pow(t,u)),f=n,s="";;){var c=f.d9(o),a=Ie(f,Se(c,o)).g9().toString(t);if(Ae(f=c))return a+s;for(;a.length<u;)a="0"+a;s=a+s}}function Le(n){return $e(),new ke(n,n<0?-1:0)}function Ne(n){return $e(),n.v8_1<0}function Ae(n){return $e(),0===n.v8_1&&0===n.u8_1}function Me(n){return $e(),!(1&~n.u8_1)}function Fe(n){return $e(),n.e9()}function De(n,t){return $e(),je(n,t)<0}function Oe(n){if($e(),(t=n)!=t)return qe();if(n<=-0x8000000000000000)return Ce();if(n+1>=0x8000000000000000)return $e(),z;if(n<0)return Fe(Oe(-n));var t,r=4294967296;return new ke(n%r|0,n/r|0)}function Re(n,t){return $e(),je(n,t)>0}function He(n,t){return $e(),je(n,t)>=0}function $e(){L||(L=!0,P=Le(0),I=Le(1),S=Le(-1),z=new ke(-1,2147483647),T=new ke(0,-2147483648),E=Le(16777216))}function Ge(n){return n instanceof ke?n.g9():function(n){return n>2147483647?2147483647:n<-2147483648?-2147483648:0|n}(n)}function Ue(n){var t;return t=function(n){return n<<16>>16}(Ge(n)),function(n){return 65535&n}(t)}function Ve(n,t){return new Zt(n,t)}function Qe(n,t,r,i){return Ze("class",n,t,r,i,null)}function Ze(n,t,r,i,e,u){return{kind:n,simpleName:t,associatedObjectKey:r,associatedObjects:i,suspendArity:e,$kClass$:A,iid:u}}function Ye(n){return Array.isArray(n)}function We(n,t,r,i,e,u,o,f){null!=i&&(n.prototype=Object.create(i.prototype),n.prototype.constructor=n);var s=r(t,u,o,null==f?[]:f);n.$metadata$=s,null!=e&&((null!=s.iid?n:n.prototype).$imask$=function(n){for(var t=1,r=[],i=0,e=n.length;i<e;){var u=n[i];i=i+1|0;var o=t,f=u.prototype.$imask$,s=null==f?u.$imask$:f;null!=s&&(r.push(s),o=s.length);var c=u.$metadata$.iid,a=null==c?null:(l=void 0,v=1<<(31&(h=c)),(l=new Int32Array(1+(h>>5)|0))[_=h>>5]=l[_]|v,l);null!=a&&(r.push(a),o=Math.max(o,a.length)),o>t&&(t=o)}var h,l,_,v;return function(n,t){for(var r=0,i=new Int32Array(n);r<n;){for(var e=r,u=0,o=0,f=t.length;o<f;){var s=t[o];o=o+1|0,e<s.length&&(u|=s[e])}i[e]=u,r=r+1|0}return i}(t,r)}(e))}function Ke(n,t){return function(n,t){var r=n.$imask$;return null!=r&&function(n,t){var r=t>>5;if(r>n.length)return!1;var i=1<<(31&t);return!!(n[r]&i)}(r,t)}(n,t.$metadata$.iid)}function Xe(n){return!!Ye(n)&&!n.$type$}function Je(n){var t;switch(typeof n){case"string":case"number":case"boolean":case"function":t=!0;break;default:t=n instanceof Object}return t}function nu(n){return"string"==typeof n||Ke(n,vr)}function tu(n,t,r,i){return Ze("interface",n,t,r,i,(null==N&&(N=0),N=ru()+1|0,ru()))}function ru(){if(null!=N)return N;!function(){throw Du("lateinit property iid has not been initialized")}()}function iu(n,t,r,i){return Ze("object",n,t,r,i,null)}function eu(n){var t=n.constructor,r=null==t?null:t.$metadata$,i=null==r?null:r.errorInfo;if(null!=i)return i;var e,u=0;if(uu(n,"message")&&(u|=1),uu(n,"cause")&&(u|=2),3!==u){var o=(e=n,Object.getPrototypeOf(e));o!=Error.prototype&&(u|=eu(o))}return null!=r&&(r.errorInfo=u),u}function uu(n,t){return n.hasOwnProperty(t)}function ou(n){return new Gr(n)}function fu(n,t,r){for(var i=new Int32Array(r),e=0,u=0,o=0,f=0,s=n.length;f<s;){var c=ne(n,f);f=f+1|0;var a=t[c];if(u|=(31&a)<<o,a<32){var h=e;e=h+1|0,i[h]=u,u=0,o=0}else o=o+5|0}return i}function su(n,t){for(var r=0,i=n.length-1|0,e=-1,u=0;r<=i;)if(t>(u=n[e=(r+i|0)/2|0]))r=e+1|0;else{if(t===u)return e;i=e-1|0}return e-(t<u?1:0)|0}function cu(){M=this;var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=new Int32Array(128),r=0,i=re(n)-1|0;if(r<=i)do{var e=r;r=r+1|0,t[ne(n,e)]=e}while(r<=i);var u=fu("hCgBpCQGYHZH5BRpBPPPPPPRMP5BPPlCPP6BkEPPPPcPXPzBvBrB3BOiDoBHwD+E3DauCnFmBmB2D6E1BlBTiBmBlBP5BhBiBrBvBjBqBnBPRtBiCmCtBlB0BmB5BiB7BmBgEmChBZgCoEoGVpBSfRhBPqKQ2BwBYoFgB4CJuTiEvBuCuDrF5DgEgFlJ1DgFmBQtBsBRGsB+BPiBlD1EIjDPRPPPQPPPPPGQSQS/DxENVNU+B9zCwBwBPPCkDPNnBPqDYY1R8B7FkFgTgwGgwUwmBgKwBuBScmEP/BPPPPPPrBP8B7F1B/ErBqC6B7BiBmBfQsBUwCw/KwqIwLwETPcPjQgJxFgBlBsD",t,222),o=new Int32Array(u.length),f=0,s=u.length-1|0;if(f<=s)do{var c=f;f=f+1|0,o[c]=0===c?u[c]:o[c-1|0]+u[c]|0}while(f<=s);this.h9_1=o,this.i9_1=fu("aaMBXHYH5BRpBPPPPPPRMP5BPPlCPPzBDOOPPcPXPzBvBjB3BOhDmBBpB7DoDYxB+EiBP1DoExBkBQhBekBPmBgBhBctBiBMWOOXhCsBpBkBUV3Ba4BkB0DlCgBXgBtD4FSdBfPhBPpKP0BvBXjEQ2CGsT8DhBtCqDpFvD1D3E0IrD2EkBJrBDOBsB+BPiBlB1EIjDPPPPPPPPPPPGPPMNLsBNPNPKCvBvBPPCkDPBmBPhDXXgD4B6FzEgDguG9vUtkB9JcuBSckEP/BPPPPPPBPf4FrBjEhBpC3B5BKaWPrBOwCk/KsCuLqDHPbPxPsFtEaaqDL",t,222),this.j9_1=fu("GFjgggUHGGFFZZZmzpz5qB6s6020B60ptltB6smt2sB60mz22B1+vv+8BZZ5s2850BW5q1ymtB506smzBF3q1q1qB1q1q1+Bgii4wDTm74g3KiggxqM60q1q1Bq1o1q1BF1qlrqrBZ2q5wprBGFZWWZGHFsjiooLowgmOowjkwCkgoiIk7ligGogiioBkwkiYkzj2oNoi+sbkwj04DghhkQ8wgiYkgoioDsgnkwC4gikQ//v+85BkwvoIsgoyI4yguI0whiwEowri4CoghsJowgqYowgm4DkwgsY/nwnzPowhmYkg6wI8yggZswikwHgxgmIoxgqYkwgk4DkxgmIkgoioBsgssoBgzgyI8g9gL8g9kI0wgwJoxgkoC0wgioFkw/wI0w53iF4gioYowjmgBHGq1qkgwBF1q1q8qBHwghuIwghyKk0goQkwgoQk3goQHGFHkyg0pBgxj6IoinkxDswno7Ikwhz9Bo0gioB8z48Rwli0xN0mpjoX8w78pDwltoqKHFGGwwgsIHFH3q1q16BFHWFZ1q10q1B2qlwq1B1q10q1B2q1yq1B6q1gq1Biq1qhxBir1qp1Bqt1q1qB1g1q1+B//3q16B///q1qBH/qlqq9Bholqq9B1i00a1q10qD1op1HkwmigEigiy6Cptogq1Bixo1kDq7/j00B2qgoBWGFm1lz50B6s5q1+BGWhggzhwBFFhgk4//Bo2jigE8wguI8wguI8wgugUog1qoB4qjmIwwi2KgkYHHH4lBgiFWkgIWoghssMmz5smrBZ3q1y50B5sm7gzBtz1smzB5smz50BqzqtmzB5sgzqzBF2/9//5BowgoIwmnkzPkwgk4C8ys65BkgoqI0wgy6FghquZo2giY0ghiIsgh24B4ghsQ8QF/v1q1OFs0O8iCHHF1qggz/B8wg6Iznv+//B08QgohsjK0QGFk7hsQ4gB",t,222)}function au(){return null==M&&new cu,M}function hu(){F=this,this.k9_1=new Int32Array([170,186,688,704,736,837,890,7468,7544,7579,8305,8319,8336,8560,9424,11388,42652,42864,43e3,43868]),this.l9_1=new Int32Array([1,1,9,2,5,1,1,63,1,37,1,1,13,16,26,2,2,1,2,4])}function lu(){return null==F&&new hu,F}function _u(n){var t=function(n,t){return yu(n,t),vu.call(t),t}(n,de(ve(vu)));return _e(t,_u),t}function vu(){_e(this,vu)}function du(n){var t=function(n,t){return yu(n,t),gu.call(t),t}(n,de(ve(gu)));return _e(t,du),t}function gu(){_e(this,gu)}function wu(n){var t=function(n,t){return yu(n,t),bu.call(t),t}(n,de(ve(bu)));return _e(t,wu),t}function bu(){_e(this,bu)}function pu(n,t){return ge(t,n),ku.call(t),t}function mu(n){var t=pu(n,de(ve(ku)));return _e(t,mu),t}function ku(){_e(this,ku)}function qu(n){return function(n){ge(n),ku.call(n)}(n),Bu.call(n),n}function yu(n,t){return pu(n,t),Bu.call(t),t}function Bu(){_e(this,Bu)}function Cu(){var n,t=(qu(n=de(ve(ju))),ju.call(n),n);return _e(t,Cu),t}function xu(n){var t=function(n,t){return yu(n,t),ju.call(t),t}(n,de(ve(ju)));return _e(t,xu),t}function ju(){_e(this,ju)}function Pu(n){var t=function(n,t){return yu(n,t),Iu.call(t),t}(n,de(ve(Iu)));return _e(t,Pu),t}function Iu(){_e(this,Iu)}function Su(){var n,t=(qu(n=de(ve(Tu))),Tu.call(n),n);return _e(t,Su),t}function zu(n){var t=function(n,t){return yu(n,t),Tu.call(t),t}(n,de(ve(Tu)));return _e(t,zu),t}function Tu(){_e(this,Tu)}function Eu(){var n,t=(qu(n=de(ve(Lu))),Lu.call(n),n);return _e(t,Eu),t}function Lu(){_e(this,Lu)}function Nu(){var n,t=(qu(n=de(ve(Au))),Au.call(n),n);return _e(t,Nu),t}function Au(){_e(this,Au)}function Mu(){var n,t=(qu(n=de(ve(Fu))),Fu.call(n),n);return _e(t,Mu),t}function Fu(){_e(this,Fu)}function Du(n){var t=function(n,t){return yu(n,t),Ou.call(t),t}(n,de(ve(Ou)));return _e(t,Du),t}function Ou(){_e(this,Ou)}function Ru(n,t){var r,i=n.className;return(r="(^|.*\\s+)"+t+"($|\\s+.*)",function(n,t){return Si.call(t,n,Ht()),t}(r,de(ve(Si)))).a8(i)}function Hu(n,t){this.o9_1=n,this.p9_1=t}function $u(n){this.q9_1=n}function Gu(n,t,r){var i,e=Gf(),u=ro(),o=$f().ga(t),f=ro();if(0===re(r))i=Of();else{var s=n.ia_1,c=null==s?null:new $u(s).v9(r,"Copy reference to the clipboard");i=null==c?Of():c}return e.ja([u,o,f,i])}function Uu(n){n=n===A?null:n,this.ia_1=n}function Vu(n,t,r){to.call(this),this.ma_1=n,this.na_1=t,this.oa_1=r}function Qu(n,t){this.ra_1=n,this.sa_1=t}function Zu(n,t){to.call(this),this.va_1=n,this.wa_1=t}function Yu(n,t){to.call(this),this.xa_1=n,this.ya_1=t}function Wu(n){to.call(this),this.za_1=n}function Ku(n){to.call(this),this.ab_1=n}function Xu(n){to.call(this),this.bb_1=n}function Ju(n,t){to.call(this),this.cb_1=n,this.db_1=t}function no(n){to.call(this),this.eb_1=n}function to(){}function ro(){return so(),D}function io(){return so(),O}function eo(){return so(),R}function uo(){return so(),H}function oo(n){return so(),Gf().fb(us(fo),n)}function fo(n){return so(),n.gb(["invisible-text","text-for-copy"]),br()}function so(){$||($=!0,D=oo("`"),O=oo(" "),R=oo("("),H=oo(")"))}function co(n,t){to.call(this),this.hb_1=n,this.ib_1=t}function ao(n){to.call(this),this.jb_1=n}function ho(n,t){to.call(this),this.kb_1=n,this.lb_1=t}function lo(n){to.call(this),this.mb_1=n}function _o(n){to.call(this),this.nb_1=n}function vo(n){to.call(this),this.ob_1=n}function go(n,t,r){to.call(this),this.pb_1=n,this.qb_1=t,this.rb_1=r}function wo(n){to.call(this),this.sb_1=n}function bo(n){to.call(this),this.tb_1=n}function po(n){return n.xb_1.vb_1.k()}function mo(){if(Z)return br();Z=!0,G=new jo("Inputs",0,"Build configuration inputs"),U=new jo("ByMessage",1,"Problems grouped by message"),V=new jo("ByLocation",2,"Problems grouped by location"),Q=new jo("IncompatibleTasks",3,"Incompatible tasks")}function ko(n){Fc.call(this),this.yb_1=n}function qo(n){Fc.call(this),this.ac_1=n}function yo(n){Fc.call(this),this.bc_1=n}function Bo(n){Fc.call(this),this.cc_1=n}function Co(n){Po.call(this),this.dc_1=n}function xo(n,t,r,i,e,u,o,f){this.ec_1=n,this.fc_1=t,this.gc_1=r,this.hc_1=i,this.ic_1=e,this.jc_1=u,this.kc_1=o,this.lc_1=f}function jo(n,t,r){Ui.call(this,n,t),this.qc_1=r}function Po(){Oc.call(this)}function Io(n,t){var r=Hf(),i=us(Oo),e=Hf().y9(us(Ro),[]),u=function(n,t){var r,i=Hf(),e=us(Vo),u=Gf().ga("Learn more about the "),o=Yf();return i.y9(e,[u,o.fb(us((r=t,function(n){return n.bd(r.tc_1),br()})),t.sc_1),Gf().ga(".")])}(0,t.gc_1),o=Hf().y9(us(Ho),[zo(0,t)]),f=Hf();return r.y9(i,[e,u,o,f.y9(us($o),[No(0,Qo(),t.lc_1,po(t.jc_1)),No(0,Zo(),t.lc_1,po(t.hc_1)),No(0,Yo(),t.lc_1,po(t.ic_1)),No(0,Wo(),t.lc_1,po(t.kc_1))])])}function So(n,t){var r,i,e=Hf(),u=us(Go);switch(t.lc_1.q8_1){case 0:r=Mo(0,t.jc_1,((i=function(n){return new yo(n)}).callableName="<init>",i));break;case 3:r=Mo(0,t.kc_1,function(){var n=function(n){return new Bo(n)};return n.callableName="<init>",n}());break;case 1:r=Mo(0,t.hc_1,function(){var n=function(n){return new qo(n)};return n.callableName="<init>",n}());break;case 2:r=Mo(0,t.ic_1,function(){var n=function(n){return new ko(n)};return n.callableName="<init>",n}());break;default:be()}return e.y9(u,[r])}function zo(n,t){return Hf().ja([Lo(0,t),To(0,t)])}function To(n,t){for(var r=Hf(),i=t.fc_1,e=Or(),u=0,o=i.f();o.g();){var f=o.h(),s=u;u=s+1|0,Et(e,0===yr(s)?qr(Eo(Xo(),f)):Bt([Wf().ja([]),Eo(Xo(),f)]))}return r.ha(e)}function Eo(n,t){return Uf().ja([Uc(t)])}function Lo(n,t){return Rf().ja([$c().ka(t.ec_1)])}function No(n,t,r,i){var e,u,o;return Hf().y9(us((e=i,u=t,o=r,function(n){return n.t9("group-selector"),0===e?(n.t9("group-selector--disabled"),br()):u.equals(o)?(n.t9("group-selector--active"),br()):(n.u9(function(n){return function(t){return new Co(n)}}(u)),br()),br()})),[Gf().rc(t.qc_1,[Ao(0,i)])])}function Ao(n,t){return Gf().y9(us(Uo),[io(),eo(),Gf().ga(""+t),uo()])}function Mo(n,t,r){return function(n,t,r){var i,e=Hf(),u=Vf();return e.ja([u.ha(Ps(t,(i=r,function(n){var t,r=n.cd().ub_1;return r instanceof Zu?Kc(i,(Xo(),(t=function(n){return Fo(0,n)}).callableName="viewNode",t),n,r.va_1,r.wa_1,Rc()):r instanceof Yu?Kc(i,function(){var n=function(n){return Fo(0,n)};return n.callableName="viewNode",n}(Xo()),n,r.xa_1,r.ya_1,Hc()):r instanceof co?Kc(i,function(){var n=function(n){return Fo(0,n)};return n.callableName="viewNode",n}(Xo()),n,r.hb_1,r.ib_1,A,Ao(Xo(),n.cd().vb_1.k())):r instanceof Vu?Wc(i,n,r):Kc(i,function(){var n=function(n){return Fo(0,n)};return n.callableName="viewNode",n}(Xo()),n,r)})))])}(0,t.xb_1.uc().vc(),r)}function Fo(n,t){var r;return t instanceof ao?Vc((r=t,function(n){return n.ed("project "),n.fd(r.jb_1),br()})):t instanceof go?Vc(function(n){return function(t){return t.ed(n.pb_1+" "),t.fd(n.qb_1),t.ed(" of "),t.fd(n.rb_1),br()}}(t)):t instanceof vo?Vc(function(n){return function(t){return t.ed("system property "),t.fd(n.ob_1),br()}}(t)):t instanceof ho?Vc(function(n){return function(t){return t.ed("task "),t.fd(n.kb_1),t.ed(" of type "),t.fd(n.lb_1),br()}}(t)):t instanceof _o?Vc(function(n){return function(t){return t.ed("bean of type "),t.fd(n.nb_1),br()}}(t)):t instanceof wo?Vc(function(n){return function(t){return t.ed(n.sb_1),br()}}(t)):t instanceof bo?Vc(function(n){return function(t){return t.ed("class "),t.fd(n.tb_1),br()}}(t)):t instanceof no?Vc(function(n){return function(t){return t.ed(n.eb_1),br()}}(t)):t instanceof Wu?Uc(t.za_1):t instanceof Ju?Jo(t):Gf().ga(ce(t))}function Do(n){return n.t9("report-wrapper"),br()}function Oo(n){return n.t9("header"),br()}function Ro(n){return n.t9("gradle-logo"),br()}function Ho(n){return n.t9("title"),br()}function $o(n){return n.t9("groups"),br()}function Go(n){return n.t9("content"),br()}function Uo(n){return n.t9("group-selector__count"),br()}function Vo(n){return n.t9("learn-more"),br()}function Qo(){return mo(),G}function Zo(){return mo(),U}function Yo(){return mo(),V}function Wo(){return mo(),Q}function Ko(){Y=this}function Xo(){return null==Y&&new Ko,Y}function Jo(n){var t;return Yf().fb(us((t=n,function(n){return n.t9("documentation-button"),n.bd(t.cb_1),br()})),n.db_1)}function nf(n,t,r){this.kd_1=n,this.ld_1=t,this.md_1=r}function tf(n,t,r){this.nd_1=n,this.od_1=t,this.pd_1=r}function rf(n,t){for(var r=mf(n),i=t.trace,e=Rr(i.length),u=0,o=i.length;u<o;){var f,s=i[u];u=u+1|0,f=of(s),e.d(f)}return new nf(t,r,e)}function ef(n,t){var r,i=null==(r=t.kd_1.error)?null:ff(r);null==i||n.d(i)}function uf(n){return function(n,t,r){var i=null==n.error?null:new Zu(t,r);return null==i?new Yu(t,r):i}(n.kd_1,new Wu(n.ld_1),af(n.kd_1))}function of(n){var t;switch(n.kind){case"Project":t=new ao(n.path);break;case"Task":t=new ho(n.path,n.type);break;case"TaskPath":t=new lo(n.path);break;case"Bean":t=new _o(n.type);break;case"Field":t=new go("field",n.name,n.declaringType);break;case"InputProperty":t=new go("input property",n.name,n.task);break;case"OutputProperty":t=new go("output property",n.name,n.task);break;case"SystemProperty":t=new vo(n.name);break;case"PropertyUsage":t=new go("property",n.name,n.from);break;case"BuildLogic":t=new wo(n.location);break;case"BuildLogicClass":t=new bo(n.type);break;default:t=new no("Gradle runtime")}return t}function ff(n){var t=n.parts;if(null==t){var r=n.summary;return null==r?null:new Wu(mf(r))}for(var i=n.summary,e=null==i?null:mf(i),u=Or(),o=Qi(t);o.g();){var f=cf(o.h());null==f||u.d(f)}for(var s=$n(u,"\n"),c=Or(),a=Qi(t);a.g();){var h=sf(a.h());null==h||c.d(h)}return new Vu(e,s,c)}function sf(n){var t=cf(n);if(null==t)return null;var r,i,e=ot(new Rt(function(n,t,r,i){var e;return ut(or(n,["\r\n","\n","\r"],A,r=r!==A&&r,i=i===A?0:i),(e=n,function(n){return ur(e,n)}))}(t),!0,bf));return new Qu(e,(r=!(null==n.internalText),i=e.k(),r&&i>1?Cs():null))}function cf(n){var t=n.text;return null==t?n.internalText:t}function af(n){var t=n.documentationLink;return null==t?null:new Ju(t,"")}function hf(n,t){return new ds(lf(n,Ef().sd(t),Cs()))}function lf(n,t,r){return new js(n,function(n,t){var r,i=ut(Vn(n.o()),Nf);return ot(ut(new st(i,new _f(pf)),(r=t,function(n){return lf(n.v3(),n.w3().wd_1,r)})))}(t,1===Lf(t)?xs():Cs()),0===Lf(t)?Cs():r)}function _f(n){this.td_1=n}function vf(n){var t=Or(),r=n.ld_1,i=Un(r.ca_1).fa_1,e=ce(er(nu(i)?i:pe())),u=r.vd(function(n,t){var r;if(!(t>=0))throw _u(ce("Requested element count "+t+" is less than zero."));if(0===t)return Qn(n);if(Ke(n,Di)){var i=n.k()-t|0;if(i<=0)return Ct();if(1===i)return qr(function(n){if(Ke(n,Fi))return Jn(n);var t=n.f();if(!t.g())throw xu("Collection is empty.");for(var r=t.h();t.g();)r=t.h();return r}(n));if(r=Rr(),Ke(n,Fi)){if(Ke(n,bi)){var e=t,u=n.k();if(e<u)do{var o=e;e=e+1|0,r.d(n.j(o))}while(e<u)}else for(var f=n.l(t);f.g();){var s=f.h();r.d(s)}return r}}else r=Or();for(var c=0,a=n.f();a.g();){var h=a.h();c>=t?r.d(h):c=c+1|0}return xt(r)}(r.ca_1,1));return t.d(new co(new no(e),af(n.kd_1))),t.d(new Wu(u)),t.m(n.md_1),t.j5()}function df(n){var t=Or(),r=n.ld_1,i=r.vd(r.ca_1);return t.d(new Yu(new Wu(i),af(n.kd_1))),t.j5()}function gf(n){var t=Or();return t.d(uf(n)),t.m(n.md_1),ef(t,n),t.j5()}function wf(n){var t=Or();return t.m(new At(n.md_1)),t.d(uf(n)),ef(t,n),t.j5()}function bf(n){return re(n)>0}function pf(n,t){return function(n,t){return n===t?0:null==n?-1:null==t?1:ue(null!=n&&("string"==(i=typeof(r=n))||"boolean"===i||function(n){return"number"==typeof n||n instanceof ke}(r)||Ke(r,dr))?n:pe(),t);var r,i}(Vi(n.v3()),Vi(t.v3()))}function mf(n){var t;return Sf().qd((t=n,function(n){for(var r=t,i=0,e=r.length;i<e;){var u=r[i];i=i+1|0;var o=u.text;null==o||n.ed(o);var f=u.name;null==f||(n.fd(f),br())}return br()}))}function kf(n,t){return(0!==(r=n)?r.toString():"No")+" "+qf(t,n)+" "+yf(n)+" found";var r}function qf(n,t){return t<2?n:n+"s"}function yf(n){return n<=1?"was":"were"}function Bf(n,t){this.sc_1=n,this.tc_1=t}function Cf(n){jf.call(this),this.fa_1=n}function xf(n,t){jf.call(this),this.da_1=n,this.ea_1=t}function jf(){}function Pf(){this.dd_1=Or()}function If(){W=this}function Sf(){return null==W&&new If,W}function zf(n){Sf(),this.ca_1=n}function Tf(){K=this}function Ef(){return null==K&&new Tf,K}function Lf(n){return n.k()}function Nf(n){var t=n.j1(),r=n.i1();return _r(t,new Af(Ke(r,Ri)?r:pe()))}function Af(n){Ef(),this.wd_1=n}function Mf(n,t,r){var i;Df(t,n,r),i="Component mounted at #"+n.id+".",yi(),(yi(),g).j7(i)}function Ff(n){var t=document.getElementById(n);if(null==t)throw wu("'"+n+"' element missing");return t}function Df(n,t,r){var i,e,u;i=n.z9(r),e=t,u=function(n,t,r){return function(i){return Df(n,r,n.ba(i,t)),br()}}(n,r,t),_s(),e.innerHTML="",hs(e,i,u)}function Of(){return _s(),X}function Rf(){return _s(),J}function Hf(){return _s(),nn}function $f(){return _s(),tn}function Gf(){return _s(),rn}function Uf(){return _s(),en}function Vf(){return _s(),un}function Qf(){return _s(),on}function Zf(){return _s(),fn}function Yf(){return _s(),sn}function Wf(){return _s(),cn}function Kf(n){this.x9_1=n}function Xf(){an=this}function Jf(){return null==an&&new Xf,an}function ns(){hn=this,es.call(this)}function ts(){return null==hn&&new ns,hn}function rs(n,t,r,i){t=t===A?Ct():t,r=r===A?null:r,i=i===A?Ct():i,es.call(this),this.be_1=n,this.ce_1=t,this.de_1=r,this.ee_1=i}function is(){}function es(){Jf()}function us(n){_s();var t,r=Or();return n(new os((t=r,function(n){return t.d(n),br()}))),r}function os(n){this.r9_1=n}function fs(n,t){as.call(this),this.fe_1=n,this.ge_1=t}function ss(n){as.call(this),this.he_1=n}function cs(n,t){as.call(this),this.ie_1=n,this.je_1=t}function as(){}function hs(n,t,r){if(_s(),t instanceof rs)!function(n,t,r){var i=function(n,t,r){var i=n.createElement(t);return r(i),i}(we(n.ownerDocument),t,r);n.appendChild(i)}(n,t.be_1,(e=t,u=r,function(n){for(var t=e.ce_1.f();t.g();)ls(n,t.h(),u);var r=e.de_1;null==r||function(n,t){n.appendChild(we(n.ownerDocument).createTextNode(t))}(n,r);for(var i=e.ee_1.f();i.g();)hs(n,i.h(),u);return br()}));else if(t instanceof is){var i=t instanceof is?t:pe();hs(n,i.ke_1,function(n,t){return function(r){return n(t.le_1(r)),br()}}(r,i))}else if(le(t,ts()))return br();var e,u}function ls(n,t,r){var i,e;_s(),t instanceof cs?n.setAttribute(t.ie_1,t.je_1):t instanceof ss?function(n,t){for(var r=Or(),i=0,e=t.length;i<e;){var u=t[i];i=i+1|0,Ru(n,u)||r.d(u)}var o=r;if(!o.i()){var f=n.className,s=ce(er(nu(f)?f:pe())),c=Bi();c.p7(s),0!==re(s)&&c.p7(" "),Gn(o,c," "),n.className=c.toString()}}(n,[t.he_1]):t instanceof fs&&n.addEventListener(t.fe_1,(i=r,e=t,function(n){return n.stopPropagation(),i(e.ge_1(n)),br()}))}function _s(){ln||(ln=!0,X=ts(),new Kf("hr"),J=new Kf("h1"),new Kf("h2"),nn=new Kf("div"),new Kf("pre"),tn=new Kf("code"),rn=new Kf("span"),en=new Kf("small"),un=new Kf("ol"),on=new Kf("ul"),fn=new Kf("li"),sn=new Kf("a"),cn=new Kf("br"),new Kf("p"))}function vs(n){gs.call(this),this.ne_1=n}function ds(n){this.xb_1=n}function gs(){}function ws(n){return n.me(A,A,n.wb_1.ad())}function bs(){_n=this}function ps(){return null==_n&&new bs,_n}function ms(){if(gn)return br();gn=!0,vn=new ys("Collapsed",0),dn=new ys("Expanded",1)}function ks(n){Bs.call(this),this.ve_1=n}function qs(n,t,r){Bs.call(this),this.se_1=n,this.te_1=t,this.ue_1=r}function ys(n,t){Ui.call(this,n,t)}function Bs(){}function Cs(){return ms(),vn}function xs(){return ms(),dn}function js(n,t,r){t=t===A?Ct():t,r=r===A?Cs():r,this.ub_1=n,this.vb_1=t,this.wb_1=r}function Ps(n,t){return ot(ut(n,(r=t,function(n){return function(n,t){var r,i=n.cd(),e=Zf(),u=t(n),o=i.vb_1;r=null==(i.wb_1.equals(xs())&&!o.i()?o:null)?null:function(n,t){return Qf().ha(function(n,t){return Ps(n.vc(),t)}(n,t))}(n,t);var f=r;return e.ja([u,null==f?Of():f])}(n,r)})));var r}function Is(){if(xn)return br();xn=!0,kn=new Ss("ByMessage",0,"Messages"),qn=new Ss("ByGroup",1,"Group"),yn=new Ss("ByFileLocation",2,"File Locations"),Bn=new Ss("ByPluginLocation",3,"Plugin Locations"),Cn=new Ss("ByTaskLocation",4,"Task Locations")}function Ss(n,t,r){Ui.call(this,n,t),this.cf_1=r}function zs(n,t){this.df_1=n,this.ef_1=t}function Ts(n,t){this.ff_1=n,this.gf_1=t}function Es(n,t,r){ec();for(var i=Or(),e=li(),u=0,o=n.length;u<o;){var f=n[u];u=u+1|0;var s=f.locations;null==s||0===s.length?i.d(Os(f)):r(f,e)||i.d(Os(f))}var c=function(n,t,r){ec();for(var i=n.w1(),e=Rr(Tt(i,10)),u=i.f();u.g();){var o;o=u.h().t3_1,e.d(o)}var f=Zn(e);return t.i()||f.d(new js(new oc(Sf().rd("no location"),!0),t)),r>0&&f.d(Ns(r)),f}(e,i,t);return new ds(new js(new uc("text"),c))}function Ls(n){return ec(),t=n,function(n,r){var i,e=n.locations;if(null==e)i=null;else{for(var u=Or(),o=Qi(e);o.g();){var f=o.h();null!=t(f)&&u.d(f)}i=u}var s,c=i;if(null==c||c.i())s=!1;else{for(var a=c.f();a.g();){var h=a.h();As(r,we(t(h)),n,h)}s=!0}return s};var t}function Ns(n){return ec(),new js(new Wu(Sf().rd(n+" more problem"+(n>1?"s have":" has")+" been skipped")))}function As(n,t,r,i){ec();var e,u,o=n.v1(t);if(null==o){var f=Or(),s=_r(new js(new oc(Sf().qd((u=t,function(n){return n.fd(u),br()}))),f,xs()),f);n.h5(t,s),e=s}else e=o;e.u3_1.d(Os(r,i))}function Ms(n,t,r,i){var e,u;if(t=t===A?Or():t,r=r===A?li():r,i===A){var o=(ec(),mn);u=o+1|0,ec(),mn=u,e=o}else e=i;i=e,this.hf_1=n,this.if_1=t,this.jf_1=r,this.kf_1=i}function Fs(n,t){if(ec(),t.i())return null;for(var r,i=n,e=null,u=t.f();u.g();){var o=u.h();r=e;var f,s=i,c=o.ef_1+" ("+o.df_1+")",a=s.v1(c);if(null==a){var h=Or(),l=new Ms(new js(new oc(Sf().qd(Ys(o))),h,xs()),h);s.h5(c,l),f=l}else f=a;e=f,null==r||we(r).if_1.u(we(e).hf_1)||we(r).if_1.d(we(e).hf_1),i=we(e).jf_1}return e}function Ds(n,t){if(ec(),n.k()===t.length){var r;n:{var i=function(n,t){var r=t.length,i=Tt(n,10),e=Rr(Math.min(i,r)),u=0,o=n.f();t:for(;o.g();){var f,s=o.h();if(u>=r)break t;var c=u;u=c+1|0,f=_r(s,t[c]),e.d(f)}return e}(n,t);if(Ke(i,Di)&&i.i())r=!0;else{for(var e=i.f();e.g();){var u=e.h();if(u.t3_1.df_1!==u.u3_1.name||u.t3_1.ef_1!==u.u3_1.displayName){r=!1;break n}}r=!0}}return r}return!1}function Os(n,t,r){t=t===A?null:t,r=r!==A&&r,ec();var i=function(n,t,r){t=t===A?null:t,r=r!==A&&r,ec();var i=$s(function(n,t){return ec(),n&&null!=t.contextualLabel?we(t.contextualLabel):Rs(t)}(r,n),t).j5();return Hs(n,new Wu(i))}(n,t,r),e=function(n,t,r){r=r!==A&&r,ec();var i,e=n.problemDetails;if(null==e)i=null;else{var u,o=e[0].text,f=null==o?null:function(n,t,r,i){if(r=r!==A&&r,i=i===A?0:i,1===t.length){var e=t[0];if(0!==re(e))return function(n,t,r,i){sr(i);var e=0,u=rr(n,t,e,r);if(-1===u||1===i)return qr(ce(n));var o,f=i>0,s=Rr(f&&it(i,10));n:do{var c;if(c=ce(ie(n,e,u)),s.d(c),e=u+t.length|0,f&&s.k()===(i-1|0))break n;u=rr(n,t,e,r)}while(-1!==u);return o=ce(ie(n,e,re(n))),s.d(o),s}(n,e,r,i)}for(var u=function(n){return new ft(n)}(or(n,t,A,r,i)),o=Rr(Tt(u,10)),f=u.f();f.g();){var s;s=ur(n,f.h()),o.d(s)}return o}(o,["\n"]);if(null==f)u=null;else{for(var s=Rr(Tt(f,10)),c=f.f();c.g();){var a,h=c.h();a=Us(n)?Sf().qd(Ks(h)):Sf().rd(h),s.d(a)}u=s}var l,_=u;if(null==_)l=null;else{for(var v=Rr(Tt(_,10)),d=_.f();d.g();){var g;g=new js(new Wu(d.h())),v.d(g)}l=v}var w=null==l?null:Zn(l);i=null==w?Or():w}var b=i,p=null==b?Or():b;r||null==n.contextualLabel||p.d(new js(new Wu(Sf().rd(we(n.contextualLabel)))));var m=function(n){ec();var t=n.solutions;if(null==t||0===t.length)return null;for(var r=new Xu(Sf().rd("Solutions")),i=we(n.solutions),e=Rr(i.length),u=0,o=i.length;u<o;){var f,s=i[u];u=u+1|0,f=new js(new Ku(mf(s))),e.d(f)}return new js(r,e)}(n);null==m||p.d(m);var k,q=n.error,y=null==q?null:ff(q);if(null==y||p.d(new js(y)),t){var B=n.locations;k=!(null==B||0===B.length)}else k=!1;return k&&p.d(function(n){ec();var t,r=n.locations;if(null==r)t=null;else{for(var i=Rr(r.length),e=Qi(r);e.g();){var u,o=e.h();u=new js(new Wu(Sf().qd(Xs(o)))),i.d(u)}t=i}var f=t;return new js(new no("Locations"),null==f?Ct():f)}(n)),p}(n,null==t,r);return new js(i,e)}function Rs(n){return ec(),function(n){if(0===n.length)throw xu("Array is empty.");return n[Rn(n)]}(n.problemId).displayName}function Hs(n,t){var r;switch(ec(),n.severity){case"WARNING":var i=n.documentationLink;r=new Yu(t,null==i?null:new Ju(i,""));break;case"ERROR":var e=n.documentationLink;r=new Zu(t,null==e?null:new Ju(e,""));break;case"ADVICE":var u=n.documentationLink;r=new fc(t,null==u?null:new Ju(u,""));break;default:console.error("no severity "+n.severity),r=t}return r}function $s(n,t){t=t===A?null:t,ec();var r,i=new Pf;if(i.ed(n),null==t);else if(null!=t.line){var e=Gs(t);i.xd(e+(r=t,ec(),null==r.line||null==r.length?"":"-"+r.length),""+t.path+e),br()}else null!=t.taskPath?(i.fd(we(t.taskPath)),br()):null!=t.pluginId&&(i.fd(we(t.pluginId)),br());return i}function Gs(n){var t;if(ec(),null==n.line)t=null;else{var r,i=":"+n.line,e=n.column;t=i+(null==(r=null==e?null:":"+e)?"":r)}return null==t?"":t}function Us(n){var t;ec();var r,i=n.problemId;n:{for(var e=0,u=i.length;e<u;){var o=i[e];if(e=e+1|0,"compilation"===o.name){r=o;break n}}r=null}if(null!=r){var f,s=n.problemId;n:{for(var c=0,a=s.length;c<a;){var h=s[c];if(c=c+1|0,"java"===h.name){f=h;break n}}f=null}t=!(null==f)}else t=!1;return t}function Vs(n){return ec(),n.path}function Qs(n){return ec(),n.pluginId}function Zs(n){return ec(),n.taskPath}function Ys(n){return function(t){return t.ed(n.ef_1),t.fd(n.df_1),br()}}function Ws(n){return ec(),n.name}function Ks(n){return function(t){return t.xd(function(n,t,r,i){i=i!==A&&i;var e=new RegExp(Ii().t7(" "),i?"gui":"gu"),u=Ii().u7(" ");return n.replace(e,u)}(n),""),br()}}function Xs(n){return function(t){var r;return t.ed("- "),t.fd((r=n,ec(),null!=r.path?""+r.path+Gs(r):null!=r.taskPath?we(r.taskPath):"<undefined>")),br()}}function Js(){return Is(),kn}function nc(){return Is(),qn}function tc(){return Is(),yn}function rc(){return Is(),Bn}function ic(){return Is(),Cn}function ec(){jn||(jn=!0,wn=Ls(Vs),bn=Ls(Qs),pn=Ls(Zs),mn=0)}function uc(n){sc.call(this),this.lf_1=n}function oc(n,t){t=t!==A&&t,sc.call(this),this.mf_1=n,this.nf_1=t}function fc(n,t){t=t===A?null:t,to.call(this),this.of_1=n,this.pf_1=t}function sc(){to.call(this)}function cc(n){Fc.call(this),this.qf_1=n}function ac(n){Fc.call(this),this.rf_1=n}function hc(n){Fc.call(this),this.sf_1=n}function lc(n){Fc.call(this),this.tf_1=n}function _c(n){Fc.call(this),this.uf_1=n}function vc(n){gc.call(this),this.vf_1=n}function dc(n,t,r,i,e,u,o,f,s,c){this.wf_1=n,this.xf_1=t,this.yf_1=r,this.zf_1=i,this.ag_1=e,this.bg_1=u,this.cg_1=o,this.dg_1=f,this.eg_1=s,this.fg_1=c}function gc(){Oc.call(this)}function wc(n,t){var r=Or();po(t.zf_1)>0&&r.d(yc(0,Js(),t.fg_1,t.eg_1)),po(t.ag_1)>0&&r.d(yc(0,nc(),t.fg_1,t.eg_1)),po(t.bg_1)>0&&r.d(yc(0,tc(),t.fg_1,t.eg_1)),po(t.cg_1)>0&&r.d(yc(0,rc(),t.fg_1,t.eg_1)),po(t.dg_1)>0&&r.d(yc(0,ic(),t.fg_1,t.eg_1));var i=Hf(),e=us(jc),u=Hf().y9(us(Pc),[]),o=function(n,t){var r,i=Hf(),e=us(Ec),u=Gf().ga("Learn more about "),o=Yf();return i.y9(e,[u,o.fb(us((r=t,function(n){return n.bd(r.tc_1),br()})),t.sc_1),Gf().ga(".")])}(0,t.yf_1),f=Hf().y9(us(Ic),[pc(0,t)]),s=Hf();return i.y9(e,[u,o,f,s.zd(us(Sc),r)])}function bc(n,t){var r,i,e=Hf(),u=us(zc);switch(t.fg_1.q8_1){case 0:r=Bc(0,t.zf_1,((i=function(n){return new cc(n)}).callableName="<init>",i));break;case 1:r=Bc(0,t.ag_1,function(){var n=function(n){return new ac(n)};return n.callableName="<init>",n}());break;case 2:r=Bc(0,t.bg_1,function(){var n=function(n){return new hc(n)};return n.callableName="<init>",n}());break;case 3:r=Bc(0,t.cg_1,function(){var n=function(n){return new lc(n)};return n.callableName="<init>",n}());break;case 4:r=Bc(0,t.dg_1,function(){var n=function(n){return new _c(n)};return n.callableName="<init>",n}());break;default:be()}return e.y9(u,[r])}function pc(n,t){return Hf().ja([qc(0,t),mc(0,t)])}function mc(n,t){for(var r=Hf(),i=t.xf_1,e=Or(),u=0,o=i.f();o.g();){var f=o.h(),s=u;u=s+1|0,Et(e,0===yr(s)?qr(kc(Nc(),f)):Bt([Wf().ja([]),kc(Nc(),f)]))}return r.ha(e)}function kc(n,t){return Uf().ja([Uc(t)])}function qc(n,t){return Rf().ja([$c().ka(t.wf_1)])}function yc(n,t,r,i){var e,u,o,f;return Hf().y9(us((e=i,u=t,o=r,function(n){return n.t9("group-selector"),0===e?(n.t9("group-selector--disabled"),br()):u.equals(o)?(n.t9("group-selector--active"),br()):(n.u9(function(n){return function(t){return new vc(n)}}(u)),br()),br()})),[Gf().rc(t.cf_1,[(f=i,Gf().y9(us(Tc),[io(),eo(),Gf().ga(""+f),uo()]))])])}function Bc(n,t,r){return function(n,t,r){var i,e=Hf(),u=Vf();return e.ja([u.ha(Ps(t,(i=r,function(n){return function(n,t,r,i){var e,u;return t instanceof uc?Uc(Sf().rd(t.lf_1)):t instanceof oc?Hf().y9(us((u=t,function(n){return u.nf_1&&(n.t9("uncategorized"),br()),br()})),[Hf().ja([Qc(r,i),Uc(t.mf_1)])]):t instanceof Vu?Wc(i,r,t):t instanceof Wu?Uc(t.za_1):t instanceof Ku?Hf().ja([(sa(),Tn),Uc(t.ab_1)]):t instanceof Xu?Hf().ja([Qc(r,i),Uc(t.bb_1)]):t instanceof Zu?Kc(i,((e=function(n){return Cc(0,n)}).callableName="viewIt",e),r,t.va_1,t.wa_1,Rc()):t instanceof fc?Kc(i,function(){var n=function(n){return Cc(0,n)};return n.callableName="viewIt",n}(),r,t.of_1,t.pf_1,(sa(),Sn)):t instanceof Yu?Kc(i,function(){var n=function(n){return Cc(0,n)};return n.callableName="viewIt",n}(),r,t.xa_1,t.ya_1,Hc()):t instanceof no?Hf().ja([Qc(r,i),Uc(Sf().rd(t.eb_1))]):Gf().ga("Unknown node type viewNode: "+t)}(Nc(),n.cd().ub_1,n,i)})))])}(0,t.xb_1.uc().vc(),r)}function Cc(n,t){var r;if(t instanceof Ju)r=Jo(t);else if(t instanceof no)r=Uc(Sf().rd(t.eb_1));else if(t instanceof Wu)r=Uc(t.za_1);else{var i="Unknown node type viewIt: "+t;console.error(i),r=Gf().ga(i)}return r}function xc(n){return n.t9("report-wrapper"),br()}function jc(n){return n.t9("header"),br()}function Pc(n){return n.t9("gradle-logo"),br()}function Ic(n){return n.t9("title"),br()}function Sc(n){return n.t9("groups"),br()}function zc(n){return n.t9("content"),br()}function Tc(n){return n.t9("group-selector__count"),br()}function Ec(n){return n.t9("learn-more"),br()}function Lc(){Pn=this,document.title="Gradle - Problems Report"}function Nc(){return null==Pn&&new Lc,Pn}function Ac(n,t,r){return n.pe(t.zb().oe(),r)}function Mc(n){Oc.call(this),this.hd_1=n}function Fc(){Oc.call(this)}function Dc(n,t){Oc.call(this),this.wc_1=n,this.xc_1=t}function Oc(){}function Rc(){return sa(),In}function Hc(){return sa(),zn}function $c(){return sa(),En}function Gc(){return sa(),Ln}function Uc(n){return sa(),Gc().ka(n)}function Vc(n){return sa(),Gc().ka(Sf().qd(n))}function Qc(n,t){return sa(),n.cd().ye()?Xc(n,t):function(n){return sa(),Gf().fb(us(oa),Jc(n))}(n)}function Zc(n,t,r,i){var e,u,o;return sa(),Gf().fb(us((e=r,u=t,o=i,function(n){return n.t9("java-exception-part-toggle"),n.u9(function(n,t){return function(r){return new Dc(n,t())}}(u,o)),n.s9("Click to "+function(n){var t;switch(sa(),n.q8_1){case 0:t="show";break;case 1:t="hide";break;default:be()}return t}(e)),br()})),"("+n+" internal "+qf("line",n)+" "+function(n){var t;switch(sa(),n.q8_1){case 0:t="hidden";break;case 1:t="shown";break;default:be()}return t}(r)+")")}function Yc(n,t){t=t===A?Of():t,sa();for(var r=Qf(),i=Rr(Tt(n,10)),e=0,u=n.f();u.g();){var o,f=e;e=f+1|0,s=u.h(),c=(c=0===yr(f)?t:Of())===A?Of():c,sa(),o=Zf().ja([$f().ga(s),c]),i.d(o)}var s,c;return r.ha(i)}function Wc(n,t,r){sa();var i,e,u,o=Hf(),f=Xc(t,n),s=Gf().ga("Exception"),c=Gf().ja([(sa(),Nn).v9(r.na_1,"Copy exception to the clipboard")]),a=null==r.ma_1?null:Gf().ga(" "),h=null==a?Of():a,l=r.ma_1,_=null==l?null:Uc(l),v=null==_?Of():_;switch(t.cd().wb_1.q8_1){case 0:i=Of();break;case 1:i=function(n,t){sa();for(var r=Hf(),i=us(fa),e=n.oa_1,u=Rr(Tt(e,10)),o=0,f=e.f();f.g();){var s,c=f.h(),a=o;o=a+1|0;var h,l=yr(a);if(null!=c.sa_1){var _,v=Zc(c.ra_1.k(),l,c.sa_1,t),d=c.sa_1;switch(null==d?-1:d.q8_1){case 0:_=Yc(Kn(c.ra_1,1),v);break;case 1:_=Yc(c.ra_1,v);break;default:be()}h=_}else h=Yc(c.ra_1);s=h,u.d(s)}return r.zd(i,u)}(r,(e=n,u=t,function(){return e(new vs(u))}));break;default:be()}return o.ja([f,s,c,h,v,i])}function Kc(n,t,r,i,e,u,o){e=e===A?null:e,u=u===A?Of():u,o=o===A?Of():o,sa();var f=Hf(),s=Qc(r,n),c=t(i),a=null==e?null:t(e);return f.ja([s,u,c,null==a?Of():a,o])}function Xc(n,t){var r,i;return sa(),Gf().fb(us((r=n,i=t,function(n){return n.gb(["invisible-text","tree-btn"]),r.cd().wb_1===Cs()&&(n.t9("collapsed"),br()),r.cd().wb_1===xs()&&(n.t9("expanded"),br()),n.s9("Click to "+function(n){var t;switch(sa(),n.q8_1){case 0:t="expand";break;case 1:t="collapse";break;default:be()}return t}(r.cd().wb_1)),n.u9(function(n,t){return function(r){return n(new vs(t))}}(i,r)),br()})),Jc(n))}function Jc(n){return sa(),function(n,t){var r;if(!(t>=0))throw _u(ce("Count 'n' must be non-negative, but was "+t+"."));switch(t){case 0:r="";break;case 1:r=ce(n);break;default:var i="";if(0!==re(n))for(var e=ce(n),u=t;1&~u||(i+=e),0!=(u=u>>>1|0);)e+=e;return i}return r}(" ",n.we()-1|0)+"- "}function na(n){return sa(),n.gb(["invisible-text","error-icon"]),br()}function ta(n){return sa(),n.gb(["invisible-text","advice-icon"]),br()}function ra(n){return sa(),n.gb(["invisible-text","warning-icon"]),br()}function ia(n){return sa(),n.gb(["invisible-text","enum-icon"]),br()}function ea(n){return sa(),new Mc(n)}function ua(n){return sa(),new Mc(n)}function oa(n){return sa(),n.gb(["invisible-text","leaf-icon"]),br()}function fa(n){return sa(),n.t9("java-exception"),br()}function sa(){if(!An){An=!0;var n=Gf();In=n.fb(us(na),"[error] ");var t=Gf();Sn=t.fb(us(ta),"[advice] ");var r=Gf();zn=r.fb(us(ra),"[warn] ");var i=Gf();Tn=i.fb(us(ia),"[enum] "),En=new Uu,Ln=new Uu(ea),Nn=new $u(ua)}}return We(tt,A,Qe),We(ft,A,Qe),We(st,A,Qe),We(Di,"Collection",tu),We(ct,"AbstractCollection",Qe,A,[Di]),We(at,"IteratorImpl",Qe),We(ht,"ListIteratorImpl",Qe,at),We(lt,"Companion",iu),We(Fi,"List",tu,A,[Di]),We(vt,"AbstractList",Qe,ct,[ct,Fi]),We(dt,A,Qe),We(bt,"Companion",iu),We(mt,A,Qe,ct),We(Ri,"Map",tu),We(kt,"AbstractMap",Qe,A,[Ri]),We(qt,"Companion",iu),We(bi,"RandomAccess",tu),We(Pt,"EmptyList",iu,A,[Fi,bi]),We(It,"ArrayAsCollection",Qe,A,[Di]),We(St,"EmptyIterator",iu),We(Lt,"IntIterator",Qe),We(Nt,A,Qe),We(At,"ReversedListReadOnly",Qe,vt),We(Mt,A,Qe),We(Ft,"TransformingSequence",Qe),We(Ot,A,Qe),We(Rt,"FilteringSequence",Qe),We($i,"Set",tu,A,[Di]),We($t,"EmptySet",iu,A,[$i]),We(Vt,"Companion",iu),We(Xt,"IntProgression",Qe),We(Zt,"IntRange",Qe,Xt),We(Yt,"IntProgressionIterator",Qe,Lt),We(Wt,"Companion",iu),We(ar,A,Qe),We(hr,"DelimitedRangesSequence",Qe),We(lr,"Pair",Qe),We(vr,"CharSequence",tu),We(dr,"Comparable",tu),We(gr,"Number",Qe),We(wr,"Unit",iu),We(pr,"IntCompanionObject",iu),We(xr,"AbstractMutableCollection",Qe,ct,[ct,Di]),We(jr,"IteratorImpl",Qe),We(Pr,"ListIteratorImpl",Qe,jr),We(Ir,"AbstractMutableList",Qe,xr,[xr,Di,Fi]),We(Sr,A,Qe),We(zr,A,Qe),We(Oi,"Entry",tu),We(Hi,"MutableEntry",tu,A,[Oi]),We(Tr,"SimpleEntry",Qe,A,[Hi]),We(Mr,"AbstractMutableSet",Qe,xr,[xr,$i,Di]),We(Er,"AbstractEntrySet",Qe,Mr),We(Lr,A,Qe,Mr),We(Nr,A,Qe,xr),We(Ar,"AbstractMutableMap",Qe,kt,[kt,Ri]),We(Fr,"Companion",iu),We(Gr,"ArrayList",Qe,Ir,[Ir,Di,Fi,bi]),We(Qr,"HashCode",iu),We(Zr,"EntrySet",Qe,Er),We(Xr,"HashMap",Qe,Ar,[Ar,Ri]),We(ni,"HashSet",Qe,Mr,[Mr,$i,Di]),We(ei,A,Qe),We(oi,"InternalMap",tu),We(ui,"InternalHashCodeMap",Qe,A,[oi]),We(fi,"EntryIterator",Qe),We(si,"Companion",iu),We(ai,"ChainEntry",Qe,Tr),We(hi,"EntrySet",Qe,Er),We(vi,"LinkedHashMap",Qe,Xr,[Xr,Ri]),We(di,"Companion",iu),We(wi,"LinkedHashSet",Qe,ni,[ni,$i,Di]),We(pi,"BaseOutput",Qe),We(mi,"NodeJsOutput",Qe,pi),We(qi,"BufferedOutput",Qe,pi),We(ki,"BufferedOutputToConsoleLog",Qe,qi),We(Ci,"StringBuilder",Qe,A,[vr]),We(Pi,"Companion",iu),We(Si,"Regex",Qe),We(Ni,"Companion",iu),We(Mi,"Char",Qe,A,[dr]),We(Gi,"Companion",iu),We(Ui,"Enum",Qe,A,[dr]),We(Zi,A,Qe),We(me,"Companion",iu),We(ke,"Long",Qe,gr,[gr,dr]),We(cu,"Letter",iu),We(hu,"OtherLowercase",iu),We(ku,"Exception",Qe,Error),We(Bu,"RuntimeException",Qe,ku),We(vu,"IllegalArgumentException",Qe,Bu),We(gu,"IndexOutOfBoundsException",Qe,Bu),We(bu,"IllegalStateException",Qe,Bu),We(ju,"NoSuchElementException",Qe,Bu),We(Iu,"ArithmeticException",Qe,Bu),We(Tu,"UnsupportedOperationException",Qe,Bu),We(Lu,"NullPointerException",Qe,Bu),We(Au,"NoWhenBranchMatchedException",Qe,Bu),We(Fu,"ClassCastException",Qe,Bu),We(Ou,"UninitializedPropertyAccessException",Qe,Bu),We(Hu,"Model",Qe),We($u,"CopyButtonComponent",Qe),We(Uu,"PrettyTextComponent",Qe),We(to,"ProblemNode",Qe),We(Vu,"Exception",Qe,to),We(Qu,"StackTracePart",Qe),We(Zu,"Error",Qe,to),We(Yu,"Warning",Qe,to),We(Wu,"Message",Qe,to),We(Ku,"ListElement",Qe,to),We(Xu,"TreeNode",Qe,to),We(Ju,"Link",Qe,to),We(no,"Label",Qe,to),We(co,"Info",Qe,to),We(ao,"Project",Qe,to),We(ho,"Task",Qe,to),We(lo,"TaskPath",Qe,to),We(_o,"Bean",Qe,to),We(vo,"SystemProperty",Qe,to),We(go,"Property",Qe,to),We(wo,"BuildLogic",Qe,to),We(bo,"BuildLogicClass",Qe,to),We(Oc,"BaseIntent",Qe),We(Fc,"TreeIntent",Qe,Oc),We(ko,"TaskTreeIntent",Qe,Fc),We(qo,"MessageTreeIntent",Qe,Fc),We(yo,"InputTreeIntent",Qe,Fc),We(Bo,"IncompatibleTaskTreeIntent",Qe,Fc),We(Po,"Intent",Qe,Oc),We(Co,"SetTab",Qe,Po),We(xo,"Model",Qe),We(jo,"Tab",Qe,Ui),We(Ko,"ConfigurationCacheReportPage",iu),We(nf,"ImportedProblem",Qe),We(tf,"ImportedDiagnostics",Qe),We(_f,"sam$kotlin_Comparator$0",Qe),We(Bf,"LearnMore",Qe),We(jf,"Fragment",Qe),We(Cf,"Text",Qe,jf),We(xf,"Reference",Qe,jf),We(Pf,"Builder",Qe),We(If,"Companion",iu),We(zf,"PrettyText",Qe),We(Tf,"Companion",iu),We(Af,"Trie",Qe),We(Kf,"ViewFactory",Qe),We(Xf,"Companion",iu),We(es,"View",Qe),We(ns,"Empty",iu,es),We(rs,"Element",Qe,es),We(is,"MappedView",Qe,es),We(os,"Attributes",Qe),We(as,"Attribute",Qe),We(fs,"OnEvent",Qe,as),We(ss,"ClassName",Qe,as),We(cs,"Named",Qe,as),We(gs,"Intent",Qe),We(vs,"Toggle",Qe,gs),We(ds,"Model",Qe),We(bs,"TreeView",iu),We(Bs,"Focus",Qe),We(ks,"Original",Qe,Bs),We(qs,"Child",Qe,Bs),We(ys,"ViewState",Qe,Ui),We(js,"Tree",Qe),We(Ss,"Tab",Qe,Ui),We(zs,"ProblemIdElement",Qe),We(Ts,"ProblemSummary",Qe),We(Ms,"ProblemNodeGroup",Qe),We(sc,"ProblemApiNode",Qe,to),We(uc,"Text",Qe,sc),We(oc,"ProblemIdNode",Qe,sc),We(fc,"Advice",Qe,to),We(cc,"MessageTreeIntent",Qe,Fc),We(ac,"ProblemIdTreeIntent",Qe,Fc),We(hc,"FileLocationTreeIntent",Qe,Fc),We(lc,"PluginLocationTreeIntent",Qe,Fc),We(_c,"TaskLocationTreeIntent",Qe,Fc),We(gc,"Intent",Qe,Oc),We(vc,"SetTab",Qe,gc),We(dc,"Model",Qe),We(Lc,"ProblemsReportPage",iu),We(Mc,"Copy",Qe,Oc),We(Dc,"ToggleStackTracePart",Qe,Oc),ve(tt).f=function(){return this.n_1.f()},ve(ft).f=function(){return this.r_1.f()},ve(st).f=function(){var n,t,r=function(n,t){for(var r=n.f();r.g();){var i=r.h();t.d(i)}return t}(this.s_1,Or());return n=r,t=this.t_1,function(n,t){if(n.k()<=1)return br();var r=Br(n);!function(n,t){if(function(){if(null!=l)return l;l=!1;var n=[],t=0;if(t<600)do{var r=t;t=t+1|0,n.push(r)}while(t<600);var i=Vr;n.sort(i);var e=1,u=n.length;if(e<u)do{var o=e;e=e+1|0;var f=n[o-1|0],s=n[o];if((3&f)==(3&s)&&f>=s)return!1}while(e<u);return l=!0,!0}()){var r=(i=t,function(n,t){return i.compare(n,t)});n.sort(r)}else!function(n,t,r,i){var e=n.length,u=function(n){var t=0,r=n.length-1|0;if(t<=r)do{var i=t;t=t+1|0,n[i]=null}while(i!==r);return n}(Array(e)),o=Ur(n,u,0,r,i);if(o!==n){var f=0;if(f<=r)do{var s=f;f=f+1|0,n[s]=o[s]}while(s!==r)}}(n,0,Rn(n),t);var i}(r,t);var i=0,e=r.length;if(i<e)do{var u=i;i=i+1|0,n.f4(u,r[u])}while(i<e)}(n,t),r.f()},ve(ct).u=function(n){var t;n:if(Ke(this,Di)&&this.i())t=!1;else{for(var r=this.f();r.g();)if(le(r.h(),n)){t=!0;break n}t=!1}return t},ve(ct).v=function(n){var t;n:if(Ke(n,Di)&&n.i())t=!0;else{for(var r=n.f();r.g();){var i=r.h();if(!this.u(i)){t=!1;break n}}t=!0}return t},ve(ct).i=function(){return 0===this.k()},ve(ct).toString=function(){return $n(this,", ","[","]",A,A,(n=this,function(t){return t===n?"(this Collection)":Vi(t)}));var n},ve(ct).toArray=function(){return kr(this)},ve(at).g=function(){return this.w_1<this.x_1.k()},ve(at).h=function(){if(!this.g())throw Cu();var n=this.w_1;return this.w_1=n+1|0,this.x_1.j(n)},ve(ht).c1=function(){return this.w_1>0},ve(ht).d1=function(){if(!this.c1())throw Cu();return this.w_1=this.w_1-1|0,this.a1_1.j(this.w_1)},ve(lt).e1=function(n,t){if(n<0||n>=t)throw du("index: "+n+", size: "+t)},ve(lt).b1=function(n,t){if(n<0||n>t)throw du("index: "+n+", size: "+t)},ve(lt).f1=function(n){for(var t=1,r=n.f();r.g();){var i=r.h(),e=Mn(31,t),u=null==i?null:ae(i);t=e+(null==u?0:u)|0}return t},ve(lt).g1=function(n,t){if(n.k()!==t.k())return!1;for(var r=t.f(),i=n.f();i.g();)if(!le(i.h(),r.h()))return!1;return!0},ve(vt).f=function(){return new at(this)},ve(vt).l=function(n){return new ht(this,n)},ve(vt).equals=function(n){return n===this||!(null==n||!Ke(n,Fi))&&_t().g1(this,n)},ve(vt).hashCode=function(){return _t().f1(this)},ve(dt).g=function(){return this.h1_1.g()},ve(dt).h=function(){return this.h1_1.h().i1()},ve(bt).k1=function(n){var t=n.j1(),r=null==t?null:ae(t),i=null==r?0:r,e=n.i1(),u=null==e?null:ae(e);return i^(null==u?0:u)},ve(bt).l1=function(n){return Vi(n.j1())+"="+Vi(n.i1())},ve(bt).m1=function(n,t){return!(null==t||!Ke(t,Oi))&&!!le(n.j1(),t.j1())&&le(n.i1(),t.i1())},ve(mt).r1=function(n){return this.q1_1.s1(n)},ve(mt).u=function(n){return!(null!=n&&!Je(n))&&this.r1(null==n||Je(n)?n:pe())},ve(mt).f=function(){return new dt(this.q1_1.o().f())},ve(mt).k=function(){return this.q1_1.k()},ve(kt).t1=function(n){return!(null==wt(this,n))},ve(kt).s1=function(n){var t;n:{var r=this.o();if(Ke(r,Di)&&r.i())t=!1;else{for(var i=r.f();i.g();)if(le(i.h().i1(),n)){t=!0;break n}t=!1}}return t},ve(kt).u1=function(n){if(null==n||!Ke(n,Oi))return!1;var t=n.j1(),r=n.i1(),i=(Ke(this,Ri)?this:pe()).v1(t);return!(!le(r,i)||null==i&&!(Ke(this,Ri)?this:pe()).t1(t))},ve(kt).equals=function(n){if(n===this)return!0;if(null==n||!Ke(n,Ri))return!1;if(this.k()!==n.k())return!1;var t;n:{var r=n.o();if(Ke(r,Di)&&r.i())t=!0;else{for(var i=r.f();i.g();){var e=i.h();if(!this.u1(e)){t=!1;break n}}t=!0}}return t},ve(kt).v1=function(n){var t=wt(this,n);return null==t?null:t.i1()},ve(kt).hashCode=function(){return ae(this.o())},ve(kt).i=function(){return 0===this.k()},ve(kt).k=function(){return this.o().k()},ve(kt).toString=function(){var n;return $n(this.o(),", ","{","}",A,A,(n=this,function(t){return n.p1(t)}))},ve(kt).p1=function(n){return gt(this,n.j1())+"="+gt(this,n.i1())},ve(kt).w1=function(){return null==this.o1_1&&(this.o1_1=new mt(this)),we(this.o1_1)},ve(qt).x1=function(n){for(var t=0,r=n.f();r.g();){var i=r.h(),e=t,u=null==i?null:ae(i);t=e+(null==u?0:u)|0}return t},ve(qt).y1=function(n,t){return n.k()===t.k()&&n.v(t)},ve(Pt).equals=function(n){return!(null==n||!Ke(n,Fi))&&n.i()},ve(Pt).hashCode=function(){return 1},ve(Pt).toString=function(){return"[]"},ve(Pt).k=function(){return 0},ve(Pt).i=function(){return!0},ve(Pt).a2=function(n){return n.i()},ve(Pt).v=function(n){return this.a2(n)},ve(Pt).j=function(n){throw du("Empty list doesn't contain element at index "+n+".")},ve(Pt).f=function(){return zt()},ve(Pt).l=function(n){if(0!==n)throw du("Index: "+n);return zt()},ve(It).k=function(){return this.b2_1.length},ve(It).i=function(){return 0===this.b2_1.length},ve(It).d2=function(n){return function(n,t){return Hn(n,t)>=0}(this.b2_1,n)},ve(It).e2=function(n){var t;n:if(Ke(n,Di)&&n.i())t=!0;else{for(var r=n.f();r.g();){var i=r.h();if(!this.d2(i)){t=!1;break n}}t=!0}return t},ve(It).v=function(n){return this.e2(n)},ve(It).f=function(){return Qi(this.b2_1)},ve(St).g=function(){return!1},ve(St).c1=function(){return!1},ve(St).h=function(){throw Cu()},ve(St).d1=function(){throw Cu()},ve(Lt).h=function(){return this.f2()},ve(Nt).g=function(){return this.g2_1.c1()},ve(Nt).c1=function(){return this.g2_1.g()},ve(Nt).h=function(){return this.g2_1.d1()},ve(Nt).d1=function(){return this.g2_1.h()},ve(At).k=function(){return this.i2_1.k()},ve(At).j=function(n){return this.i2_1.j(function(n,t){if(!(0<=t&&t<=jt(n)))throw du("Element index "+t+" must be in range ["+Ve(0,jt(n))+"].");return jt(n)-t|0}(this,n))},ve(At).f=function(){return this.l(0)},ve(At).l=function(n){return new Nt(this,n)},ve(Mt).h=function(){return this.k2_1.m2_1(this.j2_1.h())},ve(Mt).g=function(){return this.j2_1.g()},ve(Ft).f=function(){return new Mt(this)},ve(Ot).h=function(){if(-1===this.o2_1&&Dt(this),0===this.o2_1)throw Cu();var n=this.p2_1;return this.p2_1=null,this.o2_1=-1,null==n||Je(n)?n:pe()},ve(Ot).g=function(){return-1===this.o2_1&&Dt(this),1===this.o2_1},ve(Rt).f=function(){return new Ot(this)},ve($t).equals=function(n){return!(null==n||!Ke(n,$i))&&n.i()},ve($t).hashCode=function(){return 0},ve($t).toString=function(){return"[]"},ve($t).k=function(){return 0},ve($t).i=function(){return!0},ve($t).a2=function(n){return n.i()},ve($t).v=function(n){return this.a2(n)},ve($t).f=function(){return zt()},ve(Zt).y2=function(){return this.z2_1},ve(Zt).c3=function(){return this.a3_1},ve(Zt).i=function(){return this.z2_1>this.a3_1},ve(Zt).equals=function(n){return n instanceof Zt&&(!(!this.i()||!n.i())||this.z2_1===n.z2_1&&this.a3_1===n.a3_1)},ve(Zt).hashCode=function(){return this.i()?-1:Mn(31,this.z2_1)+this.a3_1|0},ve(Zt).toString=function(){return this.z2_1+".."+this.a3_1},ve(Yt).g=function(){return this.f3_1},ve(Yt).f2=function(){var n=this.g3_1;if(n===this.e3_1){if(!this.f3_1)throw Cu();this.f3_1=!1}else this.g3_1=this.g3_1+this.d3_1|0;return n},ve(Wt).q=function(n,t,r){return new Xt(n,t,r)},ve(Xt).f=function(){return new Yt(this.z2_1,this.a3_1,this.b3_1)},ve(Xt).i=function(){return this.b3_1>0?this.z2_1>this.a3_1:this.z2_1<this.a3_1},ve(Xt).equals=function(n){return n instanceof Xt&&(!(!this.i()||!n.i())||this.z2_1===n.z2_1&&this.a3_1===n.a3_1&&this.b3_1===n.b3_1)},ve(Xt).hashCode=function(){return this.i()?-1:Mn(31,Mn(31,this.z2_1)+this.a3_1|0)+this.b3_1|0},ve(Xt).toString=function(){return this.b3_1>0?this.z2_1+".."+this.a3_1+" step "+this.b3_1:this.z2_1+" downTo "+this.a3_1+" step "+(0|-this.b3_1)},ve(ar).h=function(){if(-1===this.j3_1&&cr(this),0===this.j3_1)throw Cu();var n=this.m3_1,t=n instanceof Zt?n:pe();return this.m3_1=null,this.j3_1=-1,t},ve(ar).g=function(){return-1===this.j3_1&&cr(this),1===this.j3_1},ve(hr).f=function(){return new ar(this)},ve(lr).toString=function(){return"("+this.t3_1+", "+this.u3_1+")"},ve(lr).v3=function(){return this.t3_1},ve(lr).w3=function(){return this.u3_1},ve(lr).hashCode=function(){var n=null==this.t3_1?0:ae(this.t3_1);return Mn(n,31)+(null==this.u3_1?0:ae(this.u3_1))|0},ve(lr).equals=function(n){if(this===n)return!0;if(!(n instanceof lr))return!1;var t=n instanceof lr?n:pe();return!!le(this.t3_1,t.t3_1)&&!!le(this.u3_1,t.u3_1)},ve(wr).toString=function(){return"kotlin.Unit"},ve(pr).b4=function(){return this.MIN_VALUE},ve(pr).c4=function(){return this.MAX_VALUE},ve(pr).d4=function(){return this.SIZE_BYTES},ve(pr).e4=function(){return this.SIZE_BITS},ve(xr).m=function(n){this.g4();for(var t=!1,r=n.f();r.g();){var i=r.h();this.d(i)&&(t=!0)}return t},ve(xr).toJSON=function(){return this.toArray()},ve(xr).g4=function(){},ve(jr).g=function(){return this.h4_1<this.j4_1.k()},ve(jr).h=function(){if(!this.g())throw Cu();var n=this.h4_1;return this.h4_1=n+1|0,this.i4_1=n,this.j4_1.j(this.i4_1)},ve(Pr).c1=function(){return this.h4_1>0},ve(Pr).d1=function(){if(!this.c1())throw Cu();return this.h4_1=this.h4_1-1|0,this.i4_1=this.h4_1,this.n4_1.j(this.i4_1)},ve(Ir).d=function(n){return this.g4(),this.p4(this.k(),n),!0},ve(Ir).f=function(){return new jr(this)},ve(Ir).u=function(n){return this.q4(n)>=0},ve(Ir).q4=function(n){var t=0,r=jt(this);if(t<=r)do{var i=t;if(t=t+1|0,le(this.j(i),n))return i}while(i!==r);return-1},ve(Ir).l=function(n){return new Pr(this,n)},ve(Ir).equals=function(n){return n===this||!(null==n||!Ke(n,Fi))&&_t().g1(this,n)},ve(Ir).hashCode=function(){return _t().f1(this)},ve(Sr).g=function(){return this.r4_1.g()},ve(Sr).h=function(){return this.r4_1.h().j1()},ve(zr).g=function(){return this.s4_1.g()},ve(zr).h=function(){return this.s4_1.h().i1()},ve(Tr).j1=function(){return this.t4_1},ve(Tr).i1=function(){return this.u4_1},ve(Tr).v4=function(n){var t=this.u4_1;return this.u4_1=n,t},ve(Tr).hashCode=function(){return pt().k1(this)},ve(Tr).toString=function(){return pt().l1(this)},ve(Tr).equals=function(n){return pt().m1(this,n)},ve(Er).u=function(n){return this.w4(n)},ve(Lr).y4=function(n){throw zu("Add is not supported on keys")},ve(Lr).d=function(n){return this.y4(null==n||Je(n)?n:pe())},ve(Lr).z4=function(n){return this.x4_1.t1(n)},ve(Lr).u=function(n){return!(null!=n&&!Je(n))&&this.z4(null==n||Je(n)?n:pe())},ve(Lr).f=function(){return new Sr(this.x4_1.o().f())},ve(Lr).k=function(){return this.x4_1.k()},ve(Lr).g4=function(){return this.x4_1.g4()},ve(Nr).f5=function(n){throw zu("Add is not supported on values")},ve(Nr).d=function(n){return this.f5(null==n||Je(n)?n:pe())},ve(Nr).r1=function(n){return this.e5_1.s1(n)},ve(Nr).u=function(n){return!(null!=n&&!Je(n))&&this.r1(null==n||Je(n)?n:pe())},ve(Nr).f=function(){return new zr(this.e5_1.o().f())},ve(Nr).k=function(){return this.e5_1.k()},ve(Nr).g4=function(){return this.e5_1.g4()},ve(Ar).g5=function(){return null==this.c5_1&&(this.c5_1=new Lr(this)),we(this.c5_1)},ve(Ar).w1=function(){return null==this.d5_1&&(this.d5_1=new Nr(this)),we(this.d5_1)},ve(Ar).g4=function(){},ve(Mr).equals=function(n){return n===this||!(null==n||!Ke(n,$i))&&yt().y1(this,n)},ve(Mr).hashCode=function(){return yt().x1(this)},ve(Gr).j5=function(){return this.g4(),this.c_1=!0,this.k()>0?this:Dr().i5_1},ve(Gr).k=function(){return this.b_1.length},ve(Gr).j=function(n){var t=this.b_1[$r(this,n)];return null==t||Je(t)?t:pe()},ve(Gr).f4=function(n,t){this.g4(),$r(this,n);var r=this.b_1[n];this.b_1[n]=t;var i=r;return null==i||Je(i)?i:pe()},ve(Gr).d=function(n){return this.g4(),this.b_1.push(n),this.o4_1=this.o4_1+1|0,!0},ve(Gr).p4=function(n,t){this.g4(),this.b_1.splice(function(n,t){return _t().b1(t,n.k()),t}(this,n),0,t),this.o4_1=this.o4_1+1|0},ve(Gr).m=function(n){if(this.g4(),n.i())return!1;for(var t,r,i,e=(t=this,r=n.k(),i=t.k(),t.b_1.length=t.k()+r|0,i),u=0,o=n.f();o.g();){var f=o.h(),s=u;u=s+1|0;var c=yr(s);this.b_1[e+c|0]=f}return this.o4_1=this.o4_1+1|0,!0},ve(Gr).q4=function(n){return Hn(this.b_1,n)},ve(Gr).toString=function(){return On(this.b_1,", ","[","]",A,A,ee)},ve(Gr).k5=function(){return[].slice.call(this.b_1)},ve(Gr).toArray=function(){return this.k5()},ve(Gr).g4=function(){if(this.c_1)throw Su()},ve(Qr).l5=function(n,t){return le(n,t)},ve(Qr).m5=function(n){var t=null==n?null:ae(n);return null==t?0:t},ve(Zr).o5=function(n){throw zu("Add is not supported on entries")},ve(Zr).d=function(n){return this.o5(null!=n&&Ke(n,Hi)?n:pe())},ve(Zr).w4=function(n){return this.n5_1.u1(n)},ve(Zr).f=function(){return this.n5_1.t5_1.f()},ve(Zr).k=function(){return this.n5_1.k()},ve(Xr).t1=function(n){return this.t5_1.z4(n)},ve(Xr).s1=function(n){var t;n:{var r=this.t5_1;if(Ke(r,Di)&&r.i())t=!1;else{for(var i=r.f();i.g();){var e=i.h();if(this.u5_1.l5(e.i1(),n)){t=!0;break n}}t=!1}}return t},ve(Xr).o=function(){return null==this.v5_1&&(this.v5_1=this.x5()),we(this.v5_1)},ve(Xr).x5=function(){return new Zr(this)},ve(Xr).v1=function(n){return this.t5_1.v1(n)},ve(Xr).h5=function(n,t){return this.t5_1.h5(n,t)},ve(Xr).k=function(){return this.t5_1.k()},ve(ni).d=function(n){return null==this.y5_1.h5(n,this)},ve(ni).u=function(n){return this.y5_1.t1(n)},ve(ni).i=function(){return this.y5_1.i()},ve(ni).f=function(){return this.y5_1.g5().f()},ve(ni).k=function(){return this.y5_1.k()},ve(ei).g=function(){return-1===this.z5_1&&(this.z5_1=function(n){if(null!=n.c6_1&&n.d6_1){var t=n.c6_1.length;if(n.e6_1=n.e6_1+1|0,n.e6_1<t)return 0}if(n.b6_1=n.b6_1+1|0,n.b6_1<n.a6_1.length){n.c6_1=n.g6_1.i6_1[n.a6_1[n.b6_1]];var r=n,i=n.c6_1;return r.d6_1=null!=i&&Xe(i),n.e6_1=0,0}return n.c6_1=null,1}(this)),0===this.z5_1},ve(ei).h=function(){if(!this.g())throw Cu();var n=this.d6_1?this.c6_1[this.e6_1]:this.c6_1;return this.f6_1=n,this.z5_1=-1,n},ve(ui).w5=function(){return this.h6_1},ve(ui).k=function(){return this.j6_1},ve(ui).h5=function(n,t){var r=this.h6_1.m5(n),i=ii(this,r);if(null==i)this.i6_1[r]=new Tr(n,t);else{if(null==i||!Xe(i)){var e,u=i;return this.h6_1.l5(u.j1(),n)?u.v4(t):(e=[u,new Tr(n,t)],this.i6_1[r]=e,this.j6_1=this.j6_1+1|0,null)}var o=i,f=ri(o,this,n);if(null!=f)return f.v4(t);o.push(new Tr(n,t))}return this.j6_1=this.j6_1+1|0,null},ve(ui).z4=function(n){return!(null==ti(this,n))},ve(ui).v1=function(n){var t=ti(this,n);return null==t?null:t.i1()},ve(ui).f=function(){return new ei(this)},ve(fi).g=function(){return!(null===this.m6_1)},ve(fi).h=function(){if(!this.g())throw Cu();var n=we(this.m6_1);this.l6_1=n;var t,r=n.b7_1;return t=r!==this.n6_1.y6_1.v6_1?r:null,this.m6_1=t,n},ve(ai).v4=function(n){return this.d7_1.g4(),ve(Tr).v4.call(this,n)},ve(hi).o5=function(n){throw zu("Add is not supported on entries")},ve(hi).d=function(n){return this.o5(null!=n&&Ke(n,Hi)?n:pe())},ve(hi).w4=function(n){return this.y6_1.u1(n)},ve(hi).f=function(){return new fi(this)},ve(hi).k=function(){return this.y6_1.k()},ve(hi).g4=function(){return this.y6_1.g4()},ve(vi).j5=function(){var n;if(this.g4(),this.x6_1=!0,this.k()>0)n=this;else{var t=ci().e7_1;n=Ke(t,Ri)?t:pe()}return n},ve(vi).t1=function(n){return this.w6_1.t1(n)},ve(vi).s1=function(n){var t=this.v6_1;if(null==t)return!1;var r=t;do{if(le(r.i1(),n))return!0;r=we(r.b7_1)}while(r!==this.v6_1);return!1},ve(vi).x5=function(){return new hi(this)},ve(vi).v1=function(n){var t=this.w6_1.v1(n);return null==t?null:t.i1()},ve(vi).h5=function(n,t){this.g4();var r=this.w6_1.v1(n);if(null==r){var i=new ai(this,n,t);return this.w6_1.h5(n,i),function(n,t){if(null!=n.b7_1||null!=n.c7_1)throw wu(ce("Check failed."));var r=t.v6_1;if(null==r)t.v6_1=n,n.b7_1=n,n.c7_1=n;else{var i=r.c7_1;if(null==i)throw wu(ce("Required value was null."));var e=i;n.c7_1=e,n.b7_1=r,r.c7_1=n,e.b7_1=n}}(i,this),null}return r.v4(t)},ve(vi).k=function(){return this.w6_1.k()},ve(vi).g4=function(){if(this.x6_1)throw Su()},ve(wi).g4=function(){return this.y5_1.g4()},ve(pi).h7=function(){this.i7("\n")},ve(pi).j7=function(n){this.i7(n),this.h7()},ve(mi).i7=function(n){var t=String(n);this.k7_1.write(t)},ve(ki).i7=function(n){var t=String(n),r=t.lastIndexOf("\n",0);if(r>=0){var i=this.m7_1;this.m7_1=i+t.substring(0,r),this.n7();var e=r+1|0;t=t.substring(e)}this.m7_1=this.m7_1+t},ve(ki).n7=function(){console.log(this.m7_1),this.m7_1=""},ve(qi).i7=function(n){var t=this.m7_1;this.m7_1=t+String(n)},ve(Ci).x3=function(){return this.o7_1.length},ve(Ci).y3=function(n){var t=this.o7_1;if(!(n>=0&&n<=tr(t)))throw du("index: "+n+", length: "+this.x3()+"}");return ne(t,n)},ve(Ci).z3=function(n,t){return this.o7_1.substring(n,t)},ve(Ci).i3=function(n){return this.o7_1=this.o7_1+new Mi(n),this},ve(Ci).e=function(n){return this.o7_1=this.o7_1+Vi(n),this},ve(Ci).p7=function(n){var t=this.o7_1;return this.o7_1=t+(null==n?"null":n),this},ve(Ci).toString=function(){return this.o7_1},ve(Pi).t7=function(n){var t=this.q7_1;return n.replace(t,"\\$&")},ve(Pi).u7=function(n){var t=this.s7_1;return n.replace(t,"$$$$")},ve(Si).a8=function(n){this.x7_1.lastIndex=0;var t=this.x7_1.exec(ce(n));return null!=t&&0===t.index&&this.x7_1.lastIndex===re(n)},ve(Si).toString=function(){return this.x7_1.toString()},ve(Mi).o8=function(n){return Ei(this.h3_1,n)},ve(Mi).a4=function(n){return function(n,t){return Ei(n.h3_1,t instanceof Mi?t.h3_1:pe())}(this,n)},ve(Mi).equals=function(n){return function(n,t){return t instanceof Mi&&n===t.h3_1}(this.h3_1,n)},ve(Mi).hashCode=function(){return this.h3_1},ve(Mi).toString=function(){return Li(this.h3_1)},ve(Ui).r8=function(n){return ue(this.q8_1,n.q8_1)},ve(Ui).a4=function(n){return this.r8(n instanceof Ui?n:pe())},ve(Ui).equals=function(n){return this===n},ve(Ui).hashCode=function(){return se(this)},ve(Ui).toString=function(){return this.p8_1},ve(Zi).g=function(){return!(this.s8_1===this.t8_1.length)},ve(Zi).h=function(){if(this.s8_1===this.t8_1.length)throw xu(""+this.s8_1);var n=this.s8_1;return this.s8_1=n+1|0,this.t8_1[n]},ve(ke).b9=function(n){return je(this,n)},ve(ke).a4=function(n){return this.b9(n instanceof ke?n:pe())},ve(ke).c9=function(n){return Pe(this,n)},ve(ke).d9=function(n){return function(n,t){if($e(),Ae(t))throw mu("division by zero");if(Ae(n))return qe();if(Te(n,Ce())){if(Te(t,ye())||Te(t,Be()))return Ce();if(Te(t,Ce()))return ye();var r=function(n){$e();return new ke(n.u8_1>>>1|n.v8_1<<31,n.v8_1>>1)}(n),i=function(n){$e();return new ke(n.u8_1<<1,n.v8_1<<1|n.u8_1>>>31)}(r.d9(t));return Te(i,qe())?Ne(t)?ye():Be():Pe(i,Ie(n,Se(t,i)).d9(t))}if(Te(t,Ce()))return qe();if(Ne(n))return Ne(t)?Fe(n).d9(Fe(t)):Fe(Fe(n).d9(t));if(Ne(t))return Fe(n.d9(Fe(t)));for(var e=qe(),u=n;He(u,t);){for(var o=ze(u)/ze(t),f=Math.max(1,Math.floor(o)),s=Math.ceil(Math.log(f)/Math.LN2),c=s<=48?1:Math.pow(2,s-48),a=Oe(f),h=Se(a,t);Ne(h)||Re(h,u);)h=Se(a=Oe(f-=c),t);Ae(a)&&(a=ye()),e=Pe(e,a),u=Ie(u,h)}return e}(this,n)},ve(ke).e9=function(){return this.f9().c9(new ke(1,0))},ve(ke).f9=function(){return new ke(~this.u8_1,~this.v8_1)},ve(ke).g9=function(){return this.u8_1},ve(ke).w8=function(){return ze(this)},ve(ke).valueOf=function(){return this.w8()},ve(ke).equals=function(n){return n instanceof ke&&Te(this,n)},ve(ke).hashCode=function(){return $e(),this.u8_1^this.v8_1},ve(ke).toString=function(){return Ee(this,10)},ve(Hu).toString=function(){return"Model(text="+this.o9_1+", tooltip="+this.p9_1+")"},ve(Hu).hashCode=function(){var n=he(this.o9_1);return Mn(n,31)+he(this.p9_1)|0},ve(Hu).equals=function(n){if(this===n)return!0;if(!(n instanceof Hu))return!1;var t=n instanceof Hu?n:pe();return this.o9_1===t.o9_1&&this.p9_1===t.p9_1},ve($u).v9=function(n,t){return this.w9(new Hu(n,t))},ve($u).w9=function(n){var t,r;return Uf().y9(us((t=n,r=this,function(n){return n.s9(t.p9_1),n.t9("copy-button"),n.u9(function(n,t){return function(r){return n.q9_1(t.o9_1)}}(r,t)),br()})),[])},ve($u).z9=function(n){return this.w9(n instanceof Hu?n:pe())},ve($u).aa=function(n,t){return t},ve($u).ba=function(n,t){var r=null==n||Je(n)?n:pe();return this.aa(r,t instanceof Hu?t:pe())},ve(Uu).ka=function(n){return function(n,t){for(var r=Gf(),i=t.ca_1,e=Rr(Tt(i,10)),u=i.f();u.g();){var o,f,s=u.h();s instanceof Cf?f=Gf().ga(s.fa_1):s instanceof xf?f=Gu(n,s.da_1,s.ea_1):be(),o=f,e.d(o)}return r.ha(e)}(this,n)},ve(Uu).z9=function(n){return this.ka(n instanceof zf?n:pe())},ve(Uu).la=function(n,t){return t},ve(Uu).ba=function(n,t){var r=null==n||Je(n)?n:pe();return this.la(r,t instanceof zf?t:pe())},ve(Vu).pa=function(n,t,r){return new Vu(n,t,r)},ve(Vu).qa=function(n,t,r,i){return n=n===A?this.ma_1:n,t=t===A?this.na_1:t,r=r===A?this.oa_1:r,i===A?this.pa(n,t,r):i.pa.call(this,n,t,r)},ve(Vu).toString=function(){return"Exception(summary="+this.ma_1+", fullText="+this.na_1+", parts="+this.oa_1+")"},ve(Vu).hashCode=function(){var n=null==this.ma_1?0:this.ma_1.hashCode();return n=Mn(n,31)+he(this.na_1)|0,Mn(n,31)+ae(this.oa_1)|0},ve(Vu).equals=function(n){if(this===n)return!0;if(!(n instanceof Vu))return!1;var t=n instanceof Vu?n:pe();return!!le(this.ma_1,t.ma_1)&&this.na_1===t.na_1&&!!le(this.oa_1,t.oa_1)},ve(Qu).ta=function(n,t){return new Qu(n,t)},ve(Qu).ua=function(n,t,r){return n=n===A?this.ra_1:n,t=t===A?this.sa_1:t,r===A?this.ta(n,t):r.ta.call(this,n,t)},ve(Qu).toString=function(){return"StackTracePart(lines="+this.ra_1+", state="+this.sa_1+")"},ve(Qu).hashCode=function(){var n=ae(this.ra_1);return Mn(n,31)+(null==this.sa_1?0:this.sa_1.hashCode())|0},ve(Qu).equals=function(n){if(this===n)return!0;if(!(n instanceof Qu))return!1;var t=n instanceof Qu?n:pe();return!!le(this.ra_1,t.ra_1)&&!!le(this.sa_1,t.sa_1)},ve(Zu).toString=function(){return"Error(label="+this.va_1+", docLink="+this.wa_1+")"},ve(Zu).hashCode=function(){var n=ae(this.va_1);return Mn(n,31)+(null==this.wa_1?0:ae(this.wa_1))|0},ve(Zu).equals=function(n){if(this===n)return!0;if(!(n instanceof Zu))return!1;var t=n instanceof Zu?n:pe();return!!le(this.va_1,t.va_1)&&!!le(this.wa_1,t.wa_1)},ve(Yu).toString=function(){return"Warning(label="+this.xa_1+", docLink="+this.ya_1+")"},ve(Yu).hashCode=function(){var n=ae(this.xa_1);return Mn(n,31)+(null==this.ya_1?0:ae(this.ya_1))|0},ve(Yu).equals=function(n){if(this===n)return!0;if(!(n instanceof Yu))return!1;var t=n instanceof Yu?n:pe();return!!le(this.xa_1,t.xa_1)&&!!le(this.ya_1,t.ya_1)},ve(Wu).toString=function(){return"Message(prettyText="+this.za_1+")"},ve(Wu).hashCode=function(){return this.za_1.hashCode()},ve(Wu).equals=function(n){if(this===n)return!0;if(!(n instanceof Wu))return!1;var t=n instanceof Wu?n:pe();return!!this.za_1.equals(t.za_1)},ve(Ku).toString=function(){return"ListElement(prettyText="+this.ab_1+")"},ve(Ku).hashCode=function(){return this.ab_1.hashCode()},ve(Ku).equals=function(n){if(this===n)return!0;if(!(n instanceof Ku))return!1;var t=n instanceof Ku?n:pe();return!!this.ab_1.equals(t.ab_1)},ve(Xu).toString=function(){return"TreeNode(prettyText="+this.bb_1+")"},ve(Xu).hashCode=function(){return this.bb_1.hashCode()},ve(Xu).equals=function(n){if(this===n)return!0;if(!(n instanceof Xu))return!1;var t=n instanceof Xu?n:pe();return!!this.bb_1.equals(t.bb_1)},ve(Ju).toString=function(){return"Link(href="+this.cb_1+", label="+this.db_1+")"},ve(Ju).hashCode=function(){var n=he(this.cb_1);return Mn(n,31)+he(this.db_1)|0},ve(Ju).equals=function(n){if(this===n)return!0;if(!(n instanceof Ju))return!1;var t=n instanceof Ju?n:pe();return this.cb_1===t.cb_1&&this.db_1===t.db_1},ve(no).toString=function(){return"Label(text="+this.eb_1+")"},ve(no).hashCode=function(){return he(this.eb_1)},ve(no).equals=function(n){if(this===n)return!0;if(!(n instanceof no))return!1;var t=n instanceof no?n:pe();return this.eb_1===t.eb_1},ve(co).toString=function(){return"Info(label="+this.hb_1+", docLink="+this.ib_1+")"},ve(co).hashCode=function(){var n=ae(this.hb_1);return Mn(n,31)+(null==this.ib_1?0:ae(this.ib_1))|0},ve(co).equals=function(n){if(this===n)return!0;if(!(n instanceof co))return!1;var t=n instanceof co?n:pe();return!!le(this.hb_1,t.hb_1)&&!!le(this.ib_1,t.ib_1)},ve(ao).toString=function(){return"Project(path="+this.jb_1+")"},ve(ao).hashCode=function(){return he(this.jb_1)},ve(ao).equals=function(n){if(this===n)return!0;if(!(n instanceof ao))return!1;var t=n instanceof ao?n:pe();return this.jb_1===t.jb_1},ve(ho).toString=function(){return"Task(path="+this.kb_1+", type="+this.lb_1+")"},ve(ho).hashCode=function(){var n=he(this.kb_1);return Mn(n,31)+he(this.lb_1)|0},ve(ho).equals=function(n){if(this===n)return!0;if(!(n instanceof ho))return!1;var t=n instanceof ho?n:pe();return this.kb_1===t.kb_1&&this.lb_1===t.lb_1},ve(lo).toString=function(){return"TaskPath(path="+this.mb_1+")"},ve(lo).hashCode=function(){return he(this.mb_1)},ve(lo).equals=function(n){if(this===n)return!0;if(!(n instanceof lo))return!1;var t=n instanceof lo?n:pe();return this.mb_1===t.mb_1},ve(_o).toString=function(){return"Bean(type="+this.nb_1+")"},ve(_o).hashCode=function(){return he(this.nb_1)},ve(_o).equals=function(n){if(this===n)return!0;if(!(n instanceof _o))return!1;var t=n instanceof _o?n:pe();return this.nb_1===t.nb_1},ve(vo).toString=function(){return"SystemProperty(name="+this.ob_1+")"},ve(vo).hashCode=function(){return he(this.ob_1)},ve(vo).equals=function(n){if(this===n)return!0;if(!(n instanceof vo))return!1;var t=n instanceof vo?n:pe();return this.ob_1===t.ob_1},ve(go).toString=function(){return"Property(kind="+this.pb_1+", name="+this.qb_1+", owner="+this.rb_1+")"},ve(go).hashCode=function(){var n=he(this.pb_1);return n=Mn(n,31)+he(this.qb_1)|0,Mn(n,31)+he(this.rb_1)|0},ve(go).equals=function(n){if(this===n)return!0;if(!(n instanceof go))return!1;var t=n instanceof go?n:pe();return this.pb_1===t.pb_1&&this.qb_1===t.qb_1&&this.rb_1===t.rb_1},ve(wo).toString=function(){return"BuildLogic(location="+this.sb_1+")"},ve(wo).hashCode=function(){return he(this.sb_1)},ve(wo).equals=function(n){if(this===n)return!0;if(!(n instanceof wo))return!1;var t=n instanceof wo?n:pe();return this.sb_1===t.sb_1},ve(bo).toString=function(){return"BuildLogicClass(type="+this.tb_1+")"},ve(bo).hashCode=function(){return he(this.tb_1)},ve(bo).equals=function(n){if(this===n)return!0;if(!(n instanceof bo))return!1;var t=n instanceof bo?n:pe();return this.tb_1===t.tb_1},ve(ko).zb=function(){return this.yb_1},ve(ko).toString=function(){return"TaskTreeIntent(delegate="+this.yb_1+")"},ve(ko).hashCode=function(){return ae(this.yb_1)},ve(ko).equals=function(n){if(this===n)return!0;if(!(n instanceof ko))return!1;var t=n instanceof ko?n:pe();return!!le(this.yb_1,t.yb_1)},ve(qo).zb=function(){return this.ac_1},ve(qo).toString=function(){return"MessageTreeIntent(delegate="+this.ac_1+")"},ve(qo).hashCode=function(){return ae(this.ac_1)},ve(qo).equals=function(n){if(this===n)return!0;if(!(n instanceof qo))return!1;var t=n instanceof qo?n:pe();return!!le(this.ac_1,t.ac_1)},ve(yo).zb=function(){return this.bc_1},ve(yo).toString=function(){return"InputTreeIntent(delegate="+this.bc_1+")"},ve(yo).hashCode=function(){return ae(this.bc_1)},ve(yo).equals=function(n){if(this===n)return!0;if(!(n instanceof yo))return!1;var t=n instanceof yo?n:pe();return!!le(this.bc_1,t.bc_1)},ve(Bo).zb=function(){return this.cc_1},ve(Bo).toString=function(){return"IncompatibleTaskTreeIntent(delegate="+this.cc_1+")"},ve(Bo).hashCode=function(){return ae(this.cc_1)},ve(Bo).equals=function(n){if(this===n)return!0;if(!(n instanceof Bo))return!1;var t=n instanceof Bo?n:pe();return!!le(this.cc_1,t.cc_1)},ve(Co).toString=function(){return"SetTab(tab="+this.dc_1+")"},ve(Co).hashCode=function(){return this.dc_1.hashCode()},ve(Co).equals=function(n){if(this===n)return!0;if(!(n instanceof Co))return!1;var t=n instanceof Co?n:pe();return!!this.dc_1.equals(t.dc_1)},ve(xo).mc=function(n,t,r,i,e,u,o,f){return new xo(n,t,r,i,e,u,o,f)},ve(xo).nc=function(n,t,r,i,e,u,o,f,s){return n=n===A?this.ec_1:n,t=t===A?this.fc_1:t,r=r===A?this.gc_1:r,i=i===A?this.hc_1:i,e=e===A?this.ic_1:e,u=u===A?this.jc_1:u,o=o===A?this.kc_1:o,f=f===A?this.lc_1:f,s===A?this.mc(n,t,r,i,e,u,o,f):s.mc.call(this,n,t,r,i,e,u,o,f)},ve(xo).toString=function(){return"Model(heading="+this.ec_1+", summary="+this.fc_1+", learnMore="+this.gc_1+", messageTree="+this.hc_1+", locationTree="+this.ic_1+", inputTree="+this.jc_1+", incompatibleTaskTree="+this.kc_1+", tab="+this.lc_1+")"},ve(xo).hashCode=function(){var n=this.ec_1.hashCode();return n=Mn(n,31)+ae(this.fc_1)|0,n=Mn(n,31)+this.gc_1.hashCode()|0,n=Mn(n,31)+this.hc_1.hashCode()|0,n=Mn(n,31)+this.ic_1.hashCode()|0,n=Mn(n,31)+this.jc_1.hashCode()|0,n=Mn(n,31)+this.kc_1.hashCode()|0,Mn(n,31)+this.lc_1.hashCode()|0},ve(xo).equals=function(n){if(this===n)return!0;if(!(n instanceof xo))return!1;var t=n instanceof xo?n:pe();return!!(this.ec_1.equals(t.ec_1)&&le(this.fc_1,t.fc_1)&&this.gc_1.equals(t.gc_1)&&this.hc_1.equals(t.hc_1)&&this.ic_1.equals(t.ic_1)&&this.jc_1.equals(t.jc_1)&&this.kc_1.equals(t.kc_1)&&this.lc_1.equals(t.lc_1))},ve(Ko).gd=function(n,t){var r,i;return n instanceof ko?r=t.nc(A,A,A,A,ps().id(n.yb_1,t.ic_1)):n instanceof qo?r=t.nc(A,A,A,ps().id(n.ac_1,t.hc_1)):n instanceof yo?r=t.nc(A,A,A,A,A,ps().id(n.bc_1,t.jc_1)):n instanceof Bo?r=t.nc(A,A,A,A,A,A,ps().id(n.cc_1,t.kc_1)):n instanceof Dc?r=function(n,t,r,i){var e;return r instanceof qo?e=n.nc(A,A,A,Ac(n.hc_1,r,i)):r instanceof ko?e=n.nc(A,A,A,A,Ac(n.ic_1,r,i)):r instanceof yo?e=n.nc(A,A,A,A,A,Ac(n.jc_1,r,i)):r instanceof Bo?e=n.nc(A,A,A,A,A,A,Ac(n.kc_1,r,i)):(console.error("Unhandled tree intent: "+r),e=n),e}(t,0,n.xc_1,(i=n,function(n){var t;if(!(n instanceof Vu))throw _u(ce("Failed requirement."));for(var r=n.oa_1,e=i.wc_1,u=Rr(Tt(r,10)),o=0,f=r.f();f.g();){var s,c,a=f.h(),h=o;if(o=h+1|0,e===yr(h)){var l=a.sa_1;c=a.ua(A,null==l?null:l.ad())}else c=a;s=c,u.d(s)}return t=u,n.qa(A,A,t)})):n instanceof Mc?(window.navigator.clipboard.writeText(n.hd_1),r=t):n instanceof Co?r=t.nc(A,A,A,A,A,A,A,n.dc_1):(console.error("Unhandled intent: "+n),r=t),r},ve(Ko).ba=function(n,t){var r=n instanceof Oc?n:pe();return this.gd(r,t instanceof xo?t:pe())},ve(Ko).jd=function(n){return Hf().y9(us(Do),[Io(0,n),So(0,n)])},ve(Ko).z9=function(n){return this.jd(n instanceof xo?n:pe())},ve(nf).toString=function(){return"ImportedProblem(problem="+this.kd_1+", message="+this.ld_1+", trace="+this.md_1+")"},ve(nf).hashCode=function(){var n=ae(this.kd_1);return n=Mn(n,31)+this.ld_1.hashCode()|0,Mn(n,31)+ae(this.md_1)|0},ve(nf).equals=function(n){if(this===n)return!0;if(!(n instanceof nf))return!1;var t=n instanceof nf?n:pe();return!!le(this.kd_1,t.kd_1)&&!!this.ld_1.equals(t.ld_1)&&!!le(this.md_1,t.md_1)},ve(_f).ud=function(n,t){return this.td_1(n,t)},ve(_f).compare=function(n,t){return this.ud(n,t)},ve(Bf).toString=function(){return"LearnMore(text="+this.sc_1+", documentationLink="+this.tc_1+")"},ve(Bf).hashCode=function(){var n=he(this.sc_1);return Mn(n,31)+he(this.tc_1)|0},ve(Bf).equals=function(n){if(this===n)return!0;if(!(n instanceof Bf))return!1;var t=n instanceof Bf?n:pe();return this.sc_1===t.sc_1&&this.tc_1===t.tc_1},ve(Cf).toString=function(){return"Text(text="+this.fa_1+")"},ve(Cf).hashCode=function(){return he(this.fa_1)},ve(Cf).equals=function(n){if(this===n)return!0;if(!(n instanceof Cf))return!1;var t=n instanceof Cf?n:pe();return this.fa_1===t.fa_1},ve(xf).toString=function(){return"Reference(name="+this.da_1+", clipboardString="+this.ea_1+")"},ve(xf).hashCode=function(){var n=he(this.da_1);return Mn(n,31)+he(this.ea_1)|0},ve(xf).equals=function(n){if(this===n)return!0;if(!(n instanceof xf))return!1;var t=n instanceof xf?n:pe();return this.da_1===t.da_1&&this.ea_1===t.ea_1},ve(Pf).ed=function(n){return this.dd_1.d(new Cf(n)),this},ve(Pf).xd=function(n,t){return this.dd_1.d(new xf(n,t)),this},ve(Pf).fd=function(n,t,r){return t=t===A?n:t,r===A?this.xd(n,t):r.xd.call(this,n,t)},ve(Pf).j5=function(){return new zf(Qn(this.dd_1))},ve(If).rd=function(n){return new zf(qr(new Cf(n)))},ve(If).qd=function(n){var t=new Pf;return n(t),t.j5()},ve(zf).vd=function(n){return new zf(n)},ve(zf).toString=function(){return"PrettyText(fragments="+this.ca_1+")"},ve(zf).hashCode=function(){return ae(this.ca_1)},ve(zf).equals=function(n){if(this===n)return!0;if(!(n instanceof zf))return!1;var t=n instanceof zf?n:pe();return!!le(this.ca_1,t.ca_1)},ve(Tf).sd=function(n){return function(n){for(var t=Wr(),r=n.f();r.g();)for(var i=t,e=r.h().f();e.g();){var u,o=e.h(),f=i,s=f.v1(o);if(null==s){var c=Wr();f.h5(o,c),u=c}else u=s;i=u instanceof Xr?u:pe()}return t}(n)},ve(Af).toString=function(){return"Trie(nestedMaps="+this.wd_1+")"},ve(Af).hashCode=function(){return ae(this.wd_1)},ve(Af).equals=function(n){return function(n,t){return t instanceof Af&&!!le(n,t instanceof Af?t.wd_1:pe())}(this.wd_1,n)},ve(Kf).ga=function(n){return Jf().yd(this.x9_1,A,n)},ve(Kf).ha=function(n){return Jf().yd(this.x9_1,A,A,n)},ve(Kf).ja=function(n){return Jf().yd(this.x9_1,A,A,ou(n))},ve(Kf).y9=function(n,t){return Jf().yd(this.x9_1,n,A,ou(t))},ve(Kf).zd=function(n,t){return Jf().yd(this.x9_1,n,A,t)},ve(Kf).fb=function(n,t){return Jf().yd(this.x9_1,n,t)},ve(Kf).rc=function(n,t){return Jf().yd(this.x9_1,A,n,ou(t))},ve(Kf).toString=function(){return"ViewFactory(elementName="+this.x9_1+")"},ve(Kf).hashCode=function(){return he(this.x9_1)},ve(Kf).equals=function(n){if(this===n)return!0;if(!(n instanceof Kf))return!1;var t=n instanceof Kf?n:pe();return this.x9_1===t.x9_1},ve(Xf).ae=function(n,t,r,i){return new rs(n,t,r,i)},ve(Xf).yd=function(n,t,r,i,e){return t=t===A?Ct():t,r=r===A?null:r,i=i===A?Ct():i,e===A?this.ae(n,t,r,i):e.ae.call(this,n,t,r,i)},ve(rs).toString=function(){return"Element(elementName="+this.be_1+", attributes="+this.ce_1+", innerText="+this.de_1+", children="+this.ee_1+")"},ve(rs).hashCode=function(){var n=he(this.be_1);return n=Mn(n,31)+ae(this.ce_1)|0,n=Mn(n,31)+(null==this.de_1?0:he(this.de_1))|0,Mn(n,31)+ae(this.ee_1)|0},ve(rs).equals=function(n){if(this===n)return!0;if(!(n instanceof rs))return!1;var t=n instanceof rs?n:pe();return this.be_1===t.be_1&&!!le(this.ce_1,t.ce_1)&&this.de_1==t.de_1&&!!le(this.ee_1,t.ee_1)},ve(os).u9=function(n){return this.r9_1(new fs("click",n))},ve(os).t9=function(n){return this.r9_1(new ss(n))},ve(os).gb=function(n){for(var t=0,r=n.length;t<r;){var i=n[t];t=t+1|0,this.r9_1(new ss(i))}return br()},ve(os).s9=function(n){return this.r9_1(new cs("title",n))},ve(os).bd=function(n){return this.r9_1(new cs("href",n))},ve(vs).oe=function(){return this.ne_1},ve(vs).toString=function(){return"Toggle(focus="+this.ne_1+")"},ve(vs).hashCode=function(){return ae(this.ne_1)},ve(vs).equals=function(n){if(this===n)return!0;if(!(n instanceof vs))return!1;var t=n instanceof vs?n:pe();return!!le(this.ne_1,t.ne_1)},ve(ds).pe=function(n,t){return this.re(n.qe((r=t,function(n){return n.me(r(n.ub_1))})));var r},ve(ds).re=function(n){return new ds(n)},ve(ds).toString=function(){return"Model(tree="+this.xb_1+")"},ve(ds).hashCode=function(){return this.xb_1.hashCode()},ve(ds).equals=function(n){if(this===n)return!0;if(!(n instanceof ds))return!1;var t=n instanceof ds?n:pe();return!!this.xb_1.equals(t.xb_1)},ve(bs).id=function(n,t){var r;if(n instanceof vs){var i=n.oe();r=t.re(i.qe(ws))}else be();return r},ve(ks).cd=function(){return this.ve_1},ve(ks).we=function(){return 0},ve(ks).qe=function(n){return n(this.ve_1)},ve(ks).toString=function(){return"Original(tree="+this.ve_1+")"},ve(ks).hashCode=function(){return this.ve_1.hashCode()},ve(ks).equals=function(n){if(this===n)return!0;if(!(n instanceof ks))return!1;var t=n instanceof ks?n:pe();return!!this.ve_1.equals(t.ve_1)},ve(qs).cd=function(){return this.ue_1},ve(qs).we=function(){return this.se_1.we()+1|0},ve(qs).qe=function(n){return this.se_1.qe((t=this,r=n,function(n){for(var i,e=n.vb_1,u=t.te_1,o=Rr(Tt(e,10)),f=0,s=e.f();s.g();){var c,a=s.h(),h=f;f=h+1|0,c=u===yr(h)?r(a):a,o.d(c)}return i=o,n.me(A,i)}));var t,r},ve(qs).toString=function(){return"Child(parent="+this.se_1+", index="+this.te_1+", tree="+this.ue_1+")"},ve(qs).hashCode=function(){var n=ae(this.se_1);return n=Mn(n,31)+this.te_1|0,Mn(n,31)+this.ue_1.hashCode()|0},ve(qs).equals=function(n){if(this===n)return!0;if(!(n instanceof qs))return!1;var t=n instanceof qs?n:pe();return!!le(this.se_1,t.se_1)&&this.te_1===t.te_1&&!!this.ue_1.equals(t.ue_1)},ve(ys).ad=function(){var n;switch(this.q8_1){case 0:n=xs();break;case 1:n=Cs();break;default:be()}return n},ve(Bs).vc=function(){var n,t;return ut(Vn(Ve(0,this.cd().vb_1.k()-1|0)),(n=this,(t=function(t){return n.xe(t)}).callableName="child",t))},ve(Bs).xe=function(n){return new qs(this,n,this.cd().vb_1.j(n))},ve(js).uc=function(){return new ks(this)},ve(js).ye=function(){return!this.vb_1.i()},ve(js).ze=function(n,t,r){return new js(n,t,r)},ve(js).me=function(n,t,r,i){return n=n===A?this.ub_1:n,t=t===A?this.vb_1:t,r=r===A?this.wb_1:r,i===A?this.ze(n,t,r):i.ze.call(this,n,t,r)},ve(js).toString=function(){return"Tree(label="+this.ub_1+", children="+this.vb_1+", state="+this.wb_1+")"},ve(js).hashCode=function(){var n=null==this.ub_1?0:ae(this.ub_1);return n=Mn(n,31)+ae(this.vb_1)|0,Mn(n,31)+this.wb_1.hashCode()|0},ve(js).equals=function(n){if(this===n)return!0;if(!(n instanceof js))return!1;var t=n instanceof js?n:pe();return!!le(this.ub_1,t.ub_1)&&!!le(this.vb_1,t.vb_1)&&!!this.wb_1.equals(t.wb_1)},ve(zs).toString=function(){return"ProblemIdElement(name="+this.df_1+", displayName="+this.ef_1+")"},ve(zs).hashCode=function(){var n=he(this.df_1);return Mn(n,31)+he(this.ef_1)|0},ve(zs).equals=function(n){if(this===n)return!0;if(!(n instanceof zs))return!1;var t=n instanceof zs?n:pe();return this.df_1===t.df_1&&this.ef_1===t.ef_1},ve(Ts).toString=function(){return"ProblemSummary(problemId="+this.ff_1+", count="+this.gf_1+")"},ve(Ts).hashCode=function(){var n=ae(this.ff_1);return Mn(n,31)+this.gf_1|0},ve(Ts).equals=function(n){if(this===n)return!0;if(!(n instanceof Ts))return!1;var t=n instanceof Ts?n:pe();return!!le(this.ff_1,t.ff_1)&&this.gf_1===t.gf_1},ve(Ms).toString=function(){return"ProblemNodeGroup(tree="+this.hf_1+", children="+this.if_1+", childGroups="+this.jf_1+", id="+this.kf_1+")"},ve(Ms).hashCode=function(){var n=this.hf_1.hashCode();return n=Mn(n,31)+ae(this.if_1)|0,n=Mn(n,31)+ae(this.jf_1)|0,Mn(n,31)+this.kf_1|0},ve(Ms).equals=function(n){if(this===n)return!0;if(!(n instanceof Ms))return!1;var t=n instanceof Ms?n:pe();return!!this.hf_1.equals(t.hf_1)&&!!le(this.if_1,t.if_1)&&!!le(this.jf_1,t.jf_1)&&this.kf_1===t.kf_1},ve(uc).toString=function(){return"Text(text="+this.lf_1+")"},ve(uc).hashCode=function(){return he(this.lf_1)},ve(uc).equals=function(n){if(this===n)return!0;if(!(n instanceof uc))return!1;var t=n instanceof uc?n:pe();return this.lf_1===t.lf_1},ve(oc).toString=function(){return"ProblemIdNode(prettyText="+this.mf_1+", separator="+this.nf_1+")"},ve(oc).hashCode=function(){var n=this.mf_1.hashCode();return Mn(n,31)+(0|this.nf_1)|0},ve(oc).equals=function(n){if(this===n)return!0;if(!(n instanceof oc))return!1;var t=n instanceof oc?n:pe();return!!this.mf_1.equals(t.mf_1)&&this.nf_1===t.nf_1},ve(fc).toString=function(){return"Advice(label="+this.of_1+", docLink="+this.pf_1+")"},ve(fc).hashCode=function(){var n=ae(this.of_1);return Mn(n,31)+(null==this.pf_1?0:ae(this.pf_1))|0},ve(fc).equals=function(n){if(this===n)return!0;if(!(n instanceof fc))return!1;var t=n instanceof fc?n:pe();return!!le(this.of_1,t.of_1)&&!!le(this.pf_1,t.pf_1)},ve(cc).zb=function(){return this.qf_1},ve(cc).toString=function(){return"MessageTreeIntent(delegate="+this.qf_1+")"},ve(cc).hashCode=function(){return ae(this.qf_1)},ve(cc).equals=function(n){if(this===n)return!0;if(!(n instanceof cc))return!1;var t=n instanceof cc?n:pe();return!!le(this.qf_1,t.qf_1)},ve(ac).zb=function(){return this.rf_1},ve(ac).toString=function(){return"ProblemIdTreeIntent(delegate="+this.rf_1+")"},ve(ac).hashCode=function(){return ae(this.rf_1)},ve(ac).equals=function(n){if(this===n)return!0;if(!(n instanceof ac))return!1;var t=n instanceof ac?n:pe();return!!le(this.rf_1,t.rf_1)},ve(hc).zb=function(){return this.sf_1},ve(hc).toString=function(){return"FileLocationTreeIntent(delegate="+this.sf_1+")"},ve(hc).hashCode=function(){return ae(this.sf_1)},ve(hc).equals=function(n){if(this===n)return!0;if(!(n instanceof hc))return!1;var t=n instanceof hc?n:pe();return!!le(this.sf_1,t.sf_1)},ve(lc).zb=function(){return this.tf_1},ve(lc).toString=function(){return"PluginLocationTreeIntent(delegate="+this.tf_1+")"},ve(lc).hashCode=function(){return ae(this.tf_1)},ve(lc).equals=function(n){if(this===n)return!0;if(!(n instanceof lc))return!1;var t=n instanceof lc?n:pe();return!!le(this.tf_1,t.tf_1)},ve(_c).zb=function(){return this.uf_1},ve(_c).toString=function(){return"TaskLocationTreeIntent(delegate="+this.uf_1+")"},ve(_c).hashCode=function(){return ae(this.uf_1)},ve(_c).equals=function(n){if(this===n)return!0;if(!(n instanceof _c))return!1;var t=n instanceof _c?n:pe();return!!le(this.uf_1,t.uf_1)},ve(vc).toString=function(){return"SetTab(tab="+this.vf_1+")"},ve(vc).hashCode=function(){return this.vf_1.hashCode()},ve(vc).equals=function(n){if(this===n)return!0;if(!(n instanceof vc))return!1;var t=n instanceof vc?n:pe();return!!this.vf_1.equals(t.vf_1)},ve(dc).gg=function(n,t,r,i,e,u,o,f,s,c){return new dc(n,t,r,i,e,u,o,f,s,c)},ve(dc).hg=function(n,t,r,i,e,u,o,f,s,c,a){return n=n===A?this.wf_1:n,t=t===A?this.xf_1:t,r=r===A?this.yf_1:r,i=i===A?this.zf_1:i,e=e===A?this.ag_1:e,u=u===A?this.bg_1:u,o=o===A?this.cg_1:o,f=f===A?this.dg_1:f,s=s===A?this.eg_1:s,c=c===A?this.fg_1:c,a===A?this.gg(n,t,r,i,e,u,o,f,s,c):a.gg.call(this,n,t,r,i,e,u,o,f,s,c)},ve(dc).toString=function(){return"Model(heading="+this.wf_1+", summary="+this.xf_1+", learnMore="+this.yf_1+", messageTree="+this.zf_1+", problemIdTree="+this.ag_1+", fileLocationTree="+this.bg_1+", pluginLocationTree="+this.cg_1+", taskLocationTree="+this.dg_1+", problemCount="+this.eg_1+", tab="+this.fg_1+")"},ve(dc).hashCode=function(){var n=this.wf_1.hashCode();return n=Mn(n,31)+ae(this.xf_1)|0,n=Mn(n,31)+this.yf_1.hashCode()|0,n=Mn(n,31)+this.zf_1.hashCode()|0,n=Mn(n,31)+this.ag_1.hashCode()|0,n=Mn(n,31)+this.bg_1.hashCode()|0,n=Mn(n,31)+this.cg_1.hashCode()|0,n=Mn(n,31)+this.dg_1.hashCode()|0,n=Mn(n,31)+this.eg_1|0,Mn(n,31)+this.fg_1.hashCode()|0},ve(dc).equals=function(n){if(this===n)return!0;if(!(n instanceof dc))return!1;var t=n instanceof dc?n:pe();return!!(this.wf_1.equals(t.wf_1)&&le(this.xf_1,t.xf_1)&&this.yf_1.equals(t.yf_1)&&this.zf_1.equals(t.zf_1)&&this.ag_1.equals(t.ag_1)&&this.bg_1.equals(t.bg_1)&&this.cg_1.equals(t.cg_1)&&this.dg_1.equals(t.dg_1)&&this.eg_1===t.eg_1&&this.fg_1.equals(t.fg_1))},ve(Lc).ig=function(n,t){var r,i;return n instanceof hc?r=t.hg(A,A,A,A,A,ps().id(n.sf_1,t.bg_1)):n instanceof lc?r=t.hg(A,A,A,A,A,A,ps().id(n.tf_1,t.cg_1)):n instanceof _c?r=t.hg(A,A,A,A,A,A,A,ps().id(n.uf_1,t.dg_1)):n instanceof ac?r=t.hg(A,A,A,A,ps().id(n.rf_1,t.ag_1)):n instanceof cc?r=t.hg(A,A,A,ps().id(n.qf_1,t.zf_1)):n instanceof Dc?r=function(n,t,r,i){var e;return r instanceof cc?e=n.hg(A,A,A,Ac(n.zf_1,r,i)):r instanceof ac?e=n.hg(A,A,A,A,Ac(n.ag_1,r,i)):r instanceof hc?e=n.hg(A,A,A,A,A,Ac(n.bg_1,r,i)):r instanceof lc?e=n.hg(A,A,A,A,A,A,Ac(n.cg_1,r,i)):r instanceof _c?e=n.hg(A,A,A,A,A,A,A,Ac(n.dg_1,r,i)):(console.error("Unhandled tree intent: "+r),e=n),e}(t,0,n.xc_1,(i=n,function(n){var t;if(!(n instanceof Vu))throw _u(ce("Failed requirement."));for(var r=n.oa_1,e=i.wc_1,u=Rr(Tt(r,10)),o=0,f=r.f();f.g();){var s,c,a=f.h(),h=o;if(o=h+1|0,e===yr(h)){var l=a.sa_1;c=a.ua(A,null==l?null:l.ad())}else c=a;s=c,u.d(s)}return t=u,n.qa(A,A,t)})):n instanceof Mc?(window.navigator.clipboard.writeText(n.hd_1),r=t):n instanceof vc?r=t.hg(A,A,A,A,A,A,A,A,A,n.vf_1):(console.error("Unhandled intent: "+n),r=t),r},ve(Lc).ba=function(n,t){var r=n instanceof Oc?n:pe();return this.ig(r,t instanceof dc?t:pe())},ve(Lc).jg=function(n){return Hf().y9(us(xc),[wc(0,n),bc(0,n)])},ve(Lc).z9=function(n){return this.jg(n instanceof dc?n:pe())},ve(Mc).toString=function(){return"Copy(text="+this.hd_1+")"},ve(Mc).hashCode=function(){return he(this.hd_1)},ve(Mc).equals=function(n){if(this===n)return!0;if(!(n instanceof Mc))return!1;var t=n instanceof Mc?n:pe();return this.hd_1===t.hd_1},ve(Dc).toString=function(){return"ToggleStackTracePart(partIndex="+this.wc_1+", location="+this.xc_1+")"},ve(Dc).hashCode=function(){var n=this.wc_1;return Mn(n,31)+ae(this.xc_1)|0},ve(Dc).equals=function(n){if(this===n)return!0;if(!(n instanceof Dc))return!1;var t=n instanceof Dc?n:pe();return this.wc_1===t.wc_1&&!!le(this.xc_1,t.xc_1)},ve(ui).k6=function(){var n=Object.create(null);return n.foo=1,delete n.foo,br(),n},l=null,function(){var n=configurationCacheProblems();if(null==n.problemsReport)Mf(Ff("report"),Xo(),function(n){var t,r,i,e,u,o,f,s,c,a,h=function(n){for(var t=Or(),r=Or(),i=Or(),e=0,u=n.length;e<u;){var o=n[e];e=e+1|0;var f,s=o.input,c=null==s?null:r.d(rf(s,o));if(null==c){var a=o.incompatibleTask;f=null==a?null:i.d(rf(a,o))}else f=c;if(null==f){var h=we(o.problem);t.d(rf(h,o))}}return new tf(t,r,i)}(n.diagnostics),l=n.totalProblemCount;return new xo((f=(t=n).buildName,s=t.requestedTasks,c=null==s?null:rr(s," ",A,r=r!==A&&r)>=0,a=null==c||c,Sf().qd((i=t,e=f,u=s,o=a,function(n){n.ed(function(n){var t;if(re(n)>0){var r,i=ne(n,0);r=function(n){return 97<=n&&n<=122||!(Ei(n,128)<0)&&function(n){var t;return t=1===function(n){var t=n,r=su(au().h9_1,t),i=au().h9_1[r],e=(i+au().i9_1[r]|0)-1|0,u=au().j9_1[r];if(t>e)return 0;var o=3&u;if(0===o){var f=2,s=i,c=0;if(c<=1)do{if(c=c+1|0,(s=s+(u>>f&127)|0)>t)return 3;if((s=s+(u>>(f=f+7|0)&127)|0)>t)return 0;f=f+7|0}while(c<=1);return 3}if(u<=7)return o;var a=t-i|0;return u>>Mn(2,u<=31?a%2|0:a)&3}(n)||function(n){var t=su(lu().k9_1,n);return t>=0&&n<(lu().k9_1[t]+lu().l9_1[t]|0)}(n),t}(n)}(i)?function(n){return function(n){var t=Li(n).toUpperCase();if(t.length>1){var r;if(329===n)r=t;else{var i=ne(t,0),e=t.substring(1).toLowerCase();r=Li(i)+e}return r}return Li(function(n){return function(n){var t=n;return 452<=t&&t<=460||497<=t&&t<=499?Ue(Mn(3,(t+1|0)/3|0)):4304<=t&&t<=4346||4349<=t&&t<=4351?n:xi(n)}(n)}(n))}(n)}(i):Li(i),t=ce(r)+n.substring(1)}else t=n;return t}(i.cacheAction)+" the configuration cache for ");var t=e;null==t||n.fd(t),null==e||n.ed(" build and ");var r=u;return null==(null==r?null:n.fd(r))&&n.ed("default"),n.ed(o?" tasks":" task"),br()}))),function(n,t){var r=n.cacheActionDescription,i=null==r?null:mf(r),e=Sf().rd(function(n){var t=n.od_1.k(),r=kf(t,"build configuration input");return t>0?r+" and will cause the cache to be discarded when "+(t<=1?"its":"their")+" value change":r}(t)),u=Sf().rd(function(n,t){var r=n.totalProblemCount,i=t.nd_1.k(),e=kf(r,"problem");return r>i?e+", only the first "+i+" "+yf(i)+" included in this report":e}(n,t));return function(n,t){for(var r=0,i=n.length;r<i;){var e=n[r];r=r+1|0,null!=e&&t.d(e)}return t}([i,e,u],Or())}(n,h),new Bf("Gradle Configuration Cache",n.documentationLink),hf(new no(Zo().qc_1),ut(Vn(h.nd_1),gf)),hf(new no(Yo().qc_1),function(n){return ut(Vn(n),wf)}(h.nd_1)),hf(new no(Qo().qc_1),ut(Vn(h.od_1),vf)),hf(new no(Wo().qc_1),ut(Vn(h.pd_1),df)),0===l?Qo():Zo())}(n));else{var t=n.problemsReport;Mf(Ff("report"),Nc(),function(n,t){ec();for(var r=n.summaries,i=Rr(r.length),e=0,u=r.length;e<u;){var o,f=r[e];e=e+1|0;for(var s=f.problemId,c=Rr(s.length),a=0,h=s.length;a<h;){var l,_=s[a];a=a+1|0,l=new zs(_.name,_.displayName),c.d(l)}o=new Ts(c,f.count),i.d(o)}for(var v=i,d=function(n,t){ec();for(var r=li(),i=0,e=n.length;i<e;){var u=n[i];i=i+1|0;var o,f=(a=u.problemId,ec(),On(a,":",A,A,A,A,Ws)),s=r.v1(f);if(null==s){var c=Or();r.h5(f,c),o=c}else o=s;o.d(u)}for(var a,h=r.o(),l=Rr(Tt(h,10)),_=h.f();_.g();){for(var v,d=_.h(),g=d.i1(),w=Rr(Tt(g,10)),b=g.f();b.g();){var p;p=Os(b.h(),null,!0),w.d(p)}var m,k=Zn(w),q=Un(d.i1()),y=Hs(q,new Wu($s(Rs(q)).ed(" ("+d.i1().k()+")").j5()));n:{for(var B=t.f();B.g();){var C=B.h();if(Ds(C.ff_1,q.problemId)){m=C;break n}}m=null}var x=m;null==x||k.d(Ns(x.gf_1)),v=new js(y,k),l.d(v)}var j=l;return new ds(new js(new uc("message tree root"),j))}(t,v),g=function(n,t){ec();for(var r=function(){ec();var n=Or();return new Ms(new js(new oc(Sf().rd("Ungrouped"),!0),n),n,li())}(),i=li(),e=0,u=n.length;e<u;){var o=n[e];e=e+1|0;for(var f=Yn(Dn(o.problemId,1)),s=Rr(Tt(f,10)),c=f.f();c.g();){var a,h=c.h();a=new zs(h.name,h.displayName),s.d(a)}var l=Fs(i,s),_=Os(o);null==l?r.if_1.d(_):l.if_1.d(_)}for(var v=Rr(Tt(t,10)),d=t.f();d.g();){var g,w=d.h();g=new Ts(Yn(Wn(w.ff_1,1)),w.gf_1),v.d(g)}for(var b=li(),p=v.f();p.g();){var m,k=p.h(),q=k.ff_1,y=b.v1(q);if(null==y){var B=Or();b.h5(q,B),m=B}else m=y;m.d(k)}for(var C=b.o(),x=Rr(Tt(C,10)),j=C.f();j.g();){for(var P,I=j.h(),S=I.j1(),z=0,T=I.i1().f();T.g();)z=z+T.h().gf_1|0;P=new Ts(S,z),x.d(P)}for(var E=x.f();E.g();){var L=E.h(),N=Fs(i,L.ff_1),A=null==N?null:N.if_1;null==A||A.d(Ns(L.gf_1))}for(var M=i.w1(),F=Rr(Tt(M,10)),D=M.f();D.g();){var O;O=D.h().hf_1,F.d(O)}var R=function(n,t){var r=Rr(n.k());return r.m(n),r.d(t),r}(F,r.hf_1);return new ds(new js(new uc("group tree root"),R))}(t,v),w=0,b=v.f();b.g();)w=w+b.h().gf_1|0;for(var p=Es(t,w,(ec(),wn)),m=0,k=v.f();k.g();)m=m+k.h().gf_1|0;for(var q=Es(t,m,(ec(),bn)),y=0,B=v.f();B.g();)y=y+B.h().gf_1|0;var C=Es(t,y,(ec(),pn));return new dc(Sf().rd("Problems Report"),function(n,t){ec();var r,i,e,u=n.description,o=null==u?null:qr(mf(u));return r=null==o?qr(Sf().qd((i=t,e=n,function(n){n.ed(i.length+" problems have been reported during the execution");var t=e.buildName;null==t||(n.ed(" of build "),n.fd(t));var r=e.requestedTasks;return null==r||(n.ed(" for the following tasks:"),n.fd(r),br()),br()}))):o,r}(n,t),new Bf("reporting problems",n.documentationLink),d,g,p,q,C,t.length,function(n,t,r,i,e){return ec(),po(r)>0?tc():po(n)>0?Js():po(t)>0?nc():po(i)>0?rc():po(e)>0?ic():Js()}(d,g,p,q,C))}(t,n.diagnostics))}}(),n}(void 0===this["configuration-cache-report"]?{}:this["configuration-cache-report"])}}[70](),{}))));
+//# sourceMappingURL=configuration-cache-report.js.map
+ </script>
+
+</body>
+</html>
diff --git a/android/gradle.properties b/android/gradle.properties
new file mode 100644
index 00000000..fbee1d8c
--- /dev/null
+++ b/android/gradle.properties
@@ -0,0 +1,2 @@
+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
+android.useAndroidX=true
diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..e4ef43fb
--- /dev/null
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 00000000..ca7fe065
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,26 @@
+pluginManagement {
+ val flutterSdkPath =
+ run {
+ val properties = java.util.Properties()
+ file("local.properties").inputStream().use { properties.load(it) }
+ val flutterSdkPath = properties.getProperty("flutter.sdk")
+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
+ flutterSdkPath
+ }
+
+ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
+
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+plugins {
+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"
+ id("com.android.application") version "8.11.1" apply false
+ id("org.jetbrains.kotlin.android") version "2.2.20" apply false
+}
+
+include(":app")
diff --git a/assets/icon/app_icon.png b/assets/icon/app_icon.png
new file mode 100644
index 00000000..37e907b0
Binary files /dev/null and b/assets/icon/app_icon.png differ
diff --git a/assets/icon/app_icon_foreground.png b/assets/icon/app_icon_foreground.png
new file mode 100644
index 00000000..a40919f5
Binary files /dev/null and b/assets/icon/app_icon_foreground.png differ
diff --git a/assets/icon/splash_logo.png b/assets/icon/splash_logo.png
new file mode 100644
index 00000000..d6a518d7
Binary files /dev/null and b/assets/icon/splash_logo.png differ
diff --git a/lib/main.dart b/lib/main.dart
new file mode 100644
index 00000000..5fafdcc4
--- /dev/null
+++ b/lib/main.dart
@@ -0,0 +1,272 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import 'package:dynamic_color/dynamic_color.dart';
+import 'package:permission_handler/permission_handler.dart';
+import 'package:device_info_plus/device_info_plus.dart';
+
+import 'providers/auth_provider.dart';
+import 'providers/library_provider.dart';
+import 'services/audio_player_service.dart';
+import 'services/api_service.dart';
+import 'services/download_service.dart';
+import 'services/download_notification_service.dart';
+import 'services/progress_sync_service.dart';
+import 'services/equalizer_service.dart';
+import 'services/sleep_timer_service.dart';
+import 'services/user_account_service.dart';
+import 'services/android_auto_service.dart';
+import 'services/chromecast_service.dart';
+import 'screens/login_screen.dart';
+import 'screens/app_shell.dart';
+import 'widgets/absorb_wave_icon.dart';
+
+void main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+
+ // Lock to portrait — no landscape support
+ await SystemChrome.setPreferredOrientations([
+ DeviceOrientation.portraitUp,
+ DeviceOrientation.portraitDown,
+ ]);
+
+ // Dark status bar to match Absorb theme
+ SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
+ statusBarColor: Colors.transparent,
+ statusBarIconBrightness: Brightness.light,
+ systemNavigationBarColor: Colors.black,
+ systemNavigationBarIconBrightness: Brightness.light,
+ ));
+
+ // Load device info for server identification
+ await ApiService.initDeviceId();
+ await ApiService.initVersion();
+ try {
+ final info = await DeviceInfoPlugin().androidInfo;
+ ApiService.deviceManufacturer = info.manufacturer;
+ ApiService.deviceModel = info.model;
+ } catch (_) {}
+
+ // Initialize download notification service
+ await DownloadNotificationService().init();
+
+ runApp(
+ MultiProvider(
+ providers: [
+ ChangeNotifierProvider(create: (_) => AuthProvider()),
+ ChangeNotifierProxyProvider<AuthProvider, LibraryProvider>(
+ create: (_) => LibraryProvider(),
+ update: (_, auth, lib) => lib!..updateAuth(auth),
+ ),
+ ],
+ child: const AbsorbApp(),
+ ),
+ );
+}
+
+class AbsorbApp extends StatelessWidget {
+ const AbsorbApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return DynamicColorBuilder(
+ builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
+ // Absorb is dark-first — use dynamic dark colors or our custom palette
+ ColorScheme darkScheme;
+ if (darkDynamic != null) {
+ darkScheme = darkDynamic.harmonized();
+ } else {
+ darkScheme = ColorScheme.fromSeed(
+ seedColor: const Color(0xFF7C6FBF), // deep muted purple
+ brightness: Brightness.dark,
+ );
+ }
+
+ // Light scheme for users who prefer it
+ ColorScheme lightScheme;
+ if (lightDynamic != null) {
+ lightScheme = lightDynamic.harmonized();
+ } else {
+ lightScheme = ColorScheme.fromSeed(
+ seedColor: const Color(0xFF7C6FBF),
+ brightness: Brightness.light,
+ );
+ }
+
+ // Smooth page transition theme
+ const pageTransition = PageTransitionsTheme(
+ builders: {
+ TargetPlatform.android: CupertinoPageTransitionsBuilder(),
+ TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
+ },
+ );
+
+ return MaterialApp(
+ title: 'Absorb',
+ debugShowCheckedModeBanner: false,
+ themeMode: ThemeMode.dark, // Absorb: dark by default
+ theme: ThemeData(
+ useMaterial3: true,
+ colorScheme: lightScheme,
+ pageTransitionsTheme: pageTransition,
+ ),
+ darkTheme: ThemeData(
+ useMaterial3: true,
+ colorScheme: darkScheme,
+ scaffoldBackgroundColor: const Color(0xFF0E0E0E),
+ cardTheme: CardThemeData(
+ color: darkScheme.surfaceContainerHigh,
+ elevation: 0,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(16),
+ ),
+ ),
+ navigationBarTheme: NavigationBarThemeData(
+ backgroundColor: const Color(0xFF0E0E0E),
+ indicatorColor: darkScheme.primary.withValues(alpha: 0.15),
+ labelTextStyle: WidgetStatePropertyAll(
+ TextStyle(
+ fontSize: 11,
+ fontWeight: FontWeight.w500,
+ color: darkScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ appBarTheme: AppBarTheme(
+ backgroundColor: const Color(0xFF0E0E0E),
+ surfaceTintColor: Colors.transparent,
+ scrolledUnderElevation: 0,
+ ),
+ searchBarTheme: SearchBarThemeData(
+ backgroundColor: WidgetStatePropertyAll(
+ darkScheme.surfaceContainerHigh,
+ ),
+ elevation: const WidgetStatePropertyAll(0),
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(16),
+ ),
+ ),
+ ),
+ bottomSheetTheme: const BottomSheetThemeData(
+ backgroundColor: Color(0xFF1A1A1A),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ ),
+ snackBarTheme: SnackBarThemeData(
+ backgroundColor: darkScheme.surfaceContainerHighest,
+ contentTextStyle: TextStyle(color: darkScheme.onSurface),
+ actionTextColor: darkScheme.primary,
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ ),
+ ),
+ pageTransitionsTheme: pageTransition,
+ ),
+ home: const AuthGate(),
+ );
+ },
+ );
+ }
+}
+
+class AuthGate extends StatefulWidget {
+ const AuthGate({super.key});
+
+ @override
+ State<AuthGate> createState() => _AuthGateState();
+}
+
+class _AuthGateState extends State<AuthGate> {
+ @override
+ void initState() {
+ super.initState();
+ _initServices();
+ }
+
+ Future<void> _initServices() async {
+ try {
+ await Permission.notification.request();
+ } catch (e) {
+ debugPrint('Permission request failed: $e');
+ }
+
+ try {
+ await AudioPlayerService.init();
+ } catch (e) {
+ debugPrint('AudioService init failed: $e');
+ }
+
+ // Initialize Chromecast
+ try {
+ await ChromecastService().init();
+ } catch (e) {
+ debugPrint('Chromecast init failed: $e');
+ }
+
+ // Initialize download tracker and progress sync
+ try {
+ await UserAccountService().init();
+ await DownloadService().init();
+ await ProgressSyncService().init();
+ await EqualizerService().init();
+ await SleepTimerService().loadAutoSleepSettings();
+ // Pre-populate Android Auto browse tree
+ AndroidAutoService().refresh();
+ } catch (e) {
+ debugPrint('Service init failed: $e');
+ }
+
+ if (mounted) {
+ context.read<AuthProvider>().tryRestoreSession();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final auth = context.watch<AuthProvider>();
+
+ if (auth.isLoading) {
+ return Scaffold(
+ body: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ AbsorbWaveIcon(
+ size: 48,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ const SizedBox(height: 20),
+ Text(
+ 'A B S O R B',
+ style: Theme.of(context).textTheme.headlineSmall?.copyWith(
+ color: Theme.of(context).colorScheme.primary,
+ letterSpacing: 6,
+ fontWeight: FontWeight.w300,
+ ),
+ ),
+ const SizedBox(height: 32),
+ SizedBox(
+ width: 24,
+ height: 24,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color:
+ Theme.of(context).colorScheme.primary.withValues(alpha: 0.5),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ if (auth.isAuthenticated) {
+ return const AppShell();
+ }
+
+ return const LoginScreen();
+ }
+}
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
new file mode 100644
index 00000000..de7b93f4
--- /dev/null
+++ b/lib/providers/auth_provider.dart
@@ -0,0 +1,373 @@
+import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import '../services/api_service.dart';
+import '../services/audio_player_service.dart';
+import '../services/user_account_service.dart';
+
+class AuthProvider extends ChangeNotifier {
+ String? _token;
+ String? _serverUrl;
+ String? _username;
+ String? _userId;
+ String? _defaultLibraryId;
+ Map<String, dynamic>? _userJson;
+ Map<String, dynamic>? _serverSettings;
+ String? _serverVersion;
+ bool _serverReachable = true;
+ Map<String, String> _customHeaders = {};
+
+ bool _isLoading = true;
+ String? _errorMessage;
+
+ // Getters
+ bool get isAuthenticated => _token != null && _serverUrl != null;
+ bool get isLoading => _isLoading;
+ bool get serverReachable => _serverReachable;
+ String? get token => _token;
+ String? get serverUrl => _serverUrl;
+ String? get username => _username;
+ String? get userId => _userId;
+ String? get defaultLibraryId => _defaultLibraryId;
+ String? get errorMessage => _errorMessage;
+ Map<String, dynamic>? get userJson => _userJson;
+ Map<String, dynamic>? get serverSettings => _serverSettings;
+ String? get serverVersion => _serverVersion;
+ Map<String, String> get customHeaders => _customHeaders;
+ bool get isAdmin {
+ final t = _userJson?['type'] as String?;
+ return t == 'admin' || t == 'root';
+ }
+
+ bool get isRoot => _userJson?['type'] == 'root';
+
+ ApiService? get apiService {
+ if (_serverUrl != null && _token != null) {
+ return ApiService(baseUrl: _serverUrl!, token: _token!, customHeaders: _customHeaders);
+ }
+ return null;
+ }
+
+ /// Try to restore a saved session from SharedPreferences.
+ /// If the server is unreachable, still restore credentials so offline mode works.
+ Future<void> tryRestoreSession() async {
+ _isLoading = true;
+ _serverReachable = true;
+ notifyListeners();
+
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final savedUrl = prefs.getString('server_url');
+ final savedToken = prefs.getString('token');
+ final savedUsername = prefs.getString('username');
+ final savedLibraryId = prefs.getString('default_library_id');
+
+ if (savedUrl != null && savedToken != null) {
+ // Always restore credentials so we can at least go offline
+ _serverUrl = savedUrl;
+ _token = savedToken;
+ _username = savedUsername;
+ _defaultLibraryId = savedLibraryId;
+
+ // Restore custom headers
+ final headersJson = prefs.getString('custom_headers');
+ if (headersJson != null) {
+ try {
+ _customHeaders = Map<String, String>.from(jsonDecode(headersJson) as Map);
+ } catch (_) {}
+ }
+
+ // Check if server is actually reachable
+ final reachable = await ApiService.pingServer(savedUrl, customHeaders: _customHeaders);
+ _serverReachable = reachable;
+
+ // Fetch full user info (needed for isAdmin, permissions, etc.)
+ if (reachable) {
+ try {
+ final api = ApiService(baseUrl: savedUrl, token: savedToken, customHeaders: _customHeaders);
+ final me = await api.getMe();
+ if (me != null) {
+ _userJson = me;
+ _userId = me['id'] as String?;
+ }
+ } catch (_) {}
+ }
+ }
+ } catch (_) {
+ // Restore failed — but if we already set credentials, keep them
+ _serverReachable = false;
+ }
+
+ _isLoading = false;
+ notifyListeners();
+ }
+
+ /// Login with username/password.
+ Future<bool> login({
+ required String serverUrl,
+ required String username,
+ required String password,
+ Map<String, String> customHeaders = const {},
+ }) async {
+ _errorMessage = null;
+ _isLoading = true;
+ notifyListeners();
+
+ // Normalize server URL
+ String url = serverUrl.trim();
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
+ url = 'http://$url';
+ }
+ if (url.endsWith('/')) {
+ url = url.substring(0, url.length - 1);
+ }
+
+ // Check server reachability
+ final reachable = await ApiService.pingServer(url, customHeaders: customHeaders);
+ if (!reachable) {
+ _errorMessage = 'Cannot reach server at $url';
+ _isLoading = false;
+ notifyListeners();
+ return false;
+ }
+
+ // Attempt login
+ final result = await ApiService.login(
+ serverUrl: url,
+ username: username,
+ password: password,
+ customHeaders: customHeaders,
+ );
+
+ if (result == null) {
+ _errorMessage = 'Invalid username or password';
+ _isLoading = false;
+ notifyListeners();
+ return false;
+ }
+
+ // Extract user info
+ final user = result['user'] as Map<String, dynamic>?;
+ if (user == null) {
+ _errorMessage = 'Unexpected server response';
+ _isLoading = false;
+ notifyListeners();
+ return false;
+ }
+
+ _serverUrl = url;
+ _token = user['token'] as String?;
+ _username = user['username'] as String?;
+ _userId = user['id'] as String?;
+ _defaultLibraryId = result['userDefaultLibraryId'] as String?;
+ _userJson = user;
+ _serverSettings = result['serverSettings'] as Map<String, dynamic>?;
+ _customHeaders = customHeaders;
+
+ // Fetch server version from /status endpoint (fire and forget)
+ _fetchServerVersion(url);
+
+ // Persist session
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('server_url', _serverUrl!);
+ if (_token != null) await prefs.setString('token', _token!);
+ if (_username != null) await prefs.setString('username', _username!);
+ if (_defaultLibraryId != null) {
+ await prefs.setString('default_library_id', _defaultLibraryId!);
+ }
+ // Persist custom headers as JSON
+ if (customHeaders.isNotEmpty) {
+ await prefs.setString('custom_headers', jsonEncode(customHeaders));
+ } else {
+ await prefs.remove('custom_headers');
+ }
+ } catch (_) {}
+
+ // Save to multi-account service
+ try {
+ await UserAccountService().saveAccount(SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _token ?? '',
+ userId: _userId,
+ ));
+ } catch (_) {}
+
+ _isLoading = false;
+ notifyListeners();
+ return true;
+ }
+
+ /// Login using OIDC callback response data.
+ /// [result] is the JSON from /auth/openid/callback — same shape as /login response.
+ Future<bool> loginWithOidc({
+ required String serverUrl,
+ required Map<String, dynamic> result,
+ }) async {
+ _errorMessage = null;
+
+ String url = serverUrl.trim();
+ if (url.endsWith('/')) url = url.substring(0, url.length - 1);
+
+ final user = result['user'] as Map<String, dynamic>?;
+ if (user == null) {
+ _errorMessage = 'SSO returned an unexpected response';
+ notifyListeners();
+ return false;
+ }
+
+ _serverUrl = url;
+ _token = user['token'] as String?;
+ _username = user['username'] as String?;
+ _userId = user['id'] as String?;
+ _defaultLibraryId = result['userDefaultLibraryId'] as String?;
+ _userJson = user;
+ _serverSettings = result['serverSettings'] as Map<String, dynamic>?;
+ _serverReachable = true;
+
+ // Fetch server version
+ _fetchServerVersion(url);
+
+ // Persist session
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('server_url', _serverUrl!);
+ if (_token != null) await prefs.setString('token', _token!);
+ if (_username != null) await prefs.setString('username', _username!);
+ if (_defaultLibraryId != null) {
+ await prefs.setString('default_library_id', _defaultLibraryId!);
+ }
+ } catch (_) {}
+
+ // Save to multi-account service
+ try {
+ await UserAccountService().saveAccount(SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _token ?? '',
+ userId: _userId,
+ ));
+ } catch (_) {}
+
+ _isLoading = false;
+ notifyListeners();
+ return true;
+ }
+
+ /// Logout and clear stored session.
+ /// Fetch server version asynchronously (non-blocking).
+ void _fetchServerVersion(String url) async {
+ try {
+ final version = await ApiService.getServerVersion(url, customHeaders: _customHeaders);
+ if (version != null) {
+ _serverVersion = version;
+ notifyListeners();
+ }
+ } catch (_) {}
+ }
+
+ Future<void> logout() async {
+ // Stop any active playback
+ try {
+ final player = AudioPlayerService();
+ if (player.hasBook) {
+ await player.pause();
+ await player.stop();
+ }
+ } catch (_) {}
+
+ _token = null;
+ _serverUrl = null;
+ _username = null;
+ _userId = null;
+ _defaultLibraryId = null;
+ _userJson = null;
+ _serverSettings = null;
+ _serverVersion = null;
+ _errorMessage = null;
+
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove('server_url');
+ await prefs.remove('token');
+ await prefs.remove('username');
+ await prefs.remove('default_library_id');
+ } catch (_) {}
+
+ notifyListeners();
+ }
+
+ /// Switch to a saved account without going through the login screen.
+ /// Stops playback, swaps credentials, and notifies listeners so the
+ /// app reloads with the new user's data.
+ Future<bool> switchToAccount(SavedAccount account) async {
+ // Stop current playback
+ try {
+ final player = AudioPlayerService();
+ if (player.hasBook) {
+ await player.pause();
+ await player.stop();
+ }
+ } catch (_) {}
+
+ // Set the new account as active in the account service
+ UserAccountService().switchTo(account.serverUrl, account.username);
+
+ // Set credentials
+ _serverUrl = account.serverUrl;
+ _token = account.token;
+ _username = account.username;
+ _userId = account.userId;
+ _defaultLibraryId = null;
+ _userJson = null;
+ _serverSettings = null;
+ _serverVersion = null;
+ _errorMessage = null;
+ _serverReachable = true;
+
+ // Persist as the active session
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('server_url', _serverUrl!);
+ if (_token != null) await prefs.setString('token', _token!);
+ if (_username != null) await prefs.setString('username', _username!);
+ } catch (_) {}
+
+ // Restore custom headers for this session
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final headersJson = prefs.getString('custom_headers');
+ if (headersJson != null) {
+ try {
+ _customHeaders = Map<String, String>.from(jsonDecode(headersJson) as Map);
+ } catch (_) {
+ _customHeaders = {};
+ }
+ } else {
+ _customHeaders = {};
+ }
+ } catch (_) {
+ _customHeaders = {};
+ }
+
+ // Verify the token still works and get user info
+ try {
+ final api = ApiService(baseUrl: _serverUrl!, token: _token!, customHeaders: _customHeaders);
+ final me = await api.getMe();
+ if (me != null) {
+ _userJson = me;
+ _userId = me['id'] as String?;
+ }
+ } catch (_) {
+ _serverReachable = false;
+ }
+
+ _fetchServerVersion(_serverUrl!);
+ notifyListeners();
+ return true;
+ }
+
+ /// Get all saved accounts (for the account switcher UI).
+ List<SavedAccount> get savedAccounts => UserAccountService().accounts;
+}
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
new file mode 100644
index 00000000..f28bcf00
--- /dev/null
+++ b/lib/providers/library_provider.dart
@@ -0,0 +1,945 @@
+import 'dart:async';
+import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:connectivity_plus/connectivity_plus.dart';
+import '../services/scoped_prefs.dart';
+import '../services/audio_player_service.dart';
+import 'auth_provider.dart';
+import '../services/api_service.dart';
+import '../services/progress_sync_service.dart';
+import '../services/download_service.dart';
+import '../services/android_auto_service.dart';
+
+/// Holds library data and personalized home sections.
+class LibraryProvider extends ChangeNotifier {
+ AuthProvider? _auth;
+ ApiService? get _api => _auth?.apiService;
+
+ // State
+ List<dynamic> _libraries = [];
+ String? _selectedLibraryId;
+ List<dynamic> _personalizedSections = [];
+ List<dynamic> _series = [];
+ bool _isLoading = false;
+ bool _isLoadingSeries = false;
+ String? _errorMessage;
+
+ // Offline mode
+ bool _manualOffline = false;
+ bool _networkOffline = false;
+ bool _deviceHasConnectivity = true; // false only when device has no network at all
+ Timer? _serverPingTimer;
+ bool get isOffline => _manualOffline || _networkOffline;
+ bool get isManualOffline => _manualOffline;
+
+ /// Toggle manual offline mode.
+ Future<void> setManualOffline(bool value) async {
+ debugPrint('[Library] setManualOffline($value)');
+ _manualOffline = value;
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('manual_offline_mode', value);
+ if (!value && !_networkOffline) {
+ // Going back online — flush pending syncs and refresh
+ if (_api != null) {
+ debugPrint('[Library] Manual offline off — flushing pending syncs');
+ ProgressSyncService().flushPendingSync(api: _api!);
+ }
+ if (_selectedLibraryId == null) {
+ loadLibraries();
+ } else {
+ refresh();
+ }
+ } else {
+ // Going offline — show downloaded books
+ _buildOfflineSections();
+ }
+ notifyListeners();
+ }
+
+ /// Called on init to restore manual offline preference.
+ Future<void> restoreOfflineMode() async {
+ final prefs = await SharedPreferences.getInstance();
+ _manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ }
+
+ /// Called when network connectivity changes.
+ void setNetworkOffline(bool offline) {
+ final wasOffline = _networkOffline;
+ _networkOffline = offline;
+ if (offline && !wasOffline) {
+ // Just went offline — show downloads, and force AA to clear server tabs
+ _buildOfflineSections();
+ notifyListeners();
+ AndroidAutoService().refresh(force: true);
+ // If the device still has connectivity, the server is just unreachable —
+ // start pinging so we auto-recover when it comes back.
+ if (_deviceHasConnectivity && !_manualOffline) {
+ _startServerPingTimer();
+ }
+ } else if (!offline && wasOffline && !_manualOffline) {
+ // Came back online — stop pinging, flush pending syncs, then refresh
+ _stopServerPingTimer();
+ if (_api != null) {
+ debugPrint('[Library] Back online — flushing pending syncs');
+ ProgressSyncService().flushPendingSync(api: _api!);
+ }
+ if (_selectedLibraryId == null) {
+ loadLibraries();
+ } else {
+ refresh();
+ }
+ AndroidAutoService().refresh(force: true);
+ }
+ }
+
+ /// Build home sections from downloaded books.
+ void _buildOfflineSections() {
+ final downloads = DownloadService().downloadedItems;
+ debugPrint('[Library] Building offline sections: ${downloads.length} downloads');
+ if (downloads.isEmpty) {
+ _personalizedSections = [];
+ _errorMessage = null;
+ _isLoading = false;
+ notifyListeners();
+ return;
+ }
+
+ // Build fake entities from download metadata
+ final entities = <Map<String, dynamic>>[];
+ for (final dl in downloads) {
+ // Try to extract duration from cached session data
+ double duration = 0;
+ List<dynamic> chapters = [];
+ if (dl.sessionData != null) {
+ try {
+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
+ duration = (session['duration'] as num?)?.toDouble() ?? 0;
+ chapters = session['chapters'] as List<dynamic>? ?? [];
+ } catch (_) {}
+ }
+
+ entities.add({
+ 'id': dl.itemId,
+ 'media': {
+ 'metadata': {
+ 'title': dl.title ?? 'Unknown Title',
+ 'authorName': dl.author ?? '',
+ },
+ 'duration': duration,
+ 'chapters': chapters,
+ },
+ });
+ }
+
+ final isPodcast = isPodcastLibrary;
+ _personalizedSections = [
+ {
+ 'id': 'downloaded-books',
+ 'label': isPodcast ? 'Downloaded Episodes' : 'Downloaded Books',
+ 'type': isPodcast ? 'podcast' : 'book',
+ 'entities': entities,
+ },
+ ];
+ _errorMessage = null;
+ _isLoading = false;
+ }
+
+ // User's media progress, keyed by libraryItemId
+ Map<String, Map<String, dynamic>> _progressMap = {};
+
+ // Getters
+ List<dynamic> get libraries => _libraries;
+ String? get selectedLibraryId => _selectedLibraryId;
+ List<dynamic> get personalizedSections => _personalizedSections;
+ List<dynamic> get series => _series;
+ bool get isLoading => _isLoading;
+ bool get isLoadingSeries => _isLoadingSeries;
+ String? get errorMessage => _errorMessage;
+
+ /// Get progress (0.0–1.0) for a library item by ID.
+ /// Checks local progress first (freshest), falls back to server data.
+ double getProgress(String? itemId) {
+ if (itemId == null) return 0;
+ // If item was reset this session, always return 0
+ if (_resetItems.contains(itemId)) return 0;
+ // Check local override first
+ final local = _localProgressOverrides[itemId];
+ if (local != null) return local;
+ // Fall back to server data
+ final mp = _progressMap[itemId];
+ if (mp == null) return 0;
+ return (mp['progress'] as num?)?.toDouble() ?? 0;
+ }
+
+ /// Get progress for a podcast episode using compound key.
+ double getEpisodeProgress(String itemId, String episodeId) {
+ final key = '$itemId-$episodeId';
+ if (_resetItems.contains(key)) return 0;
+ final local = _localProgressOverrides[key];
+ if (local != null) return local;
+ final mp = _progressMap[key];
+ if (mp == null) return 0;
+ return (mp['progress'] as num?)?.toDouble() ?? 0;
+ }
+
+ /// Get the raw progress data map for an item (includes isFinished, currentTime, etc.)
+ Map<String, dynamic>? getProgressData(String? itemId) {
+ if (itemId == null) return null;
+ if (_resetItems.contains(itemId)) return null;
+ return _progressMap[itemId];
+ }
+
+ /// Get raw progress data for a podcast episode.
+ Map<String, dynamic>? getEpisodeProgressData(String itemId, String episodeId) {
+ final key = '$itemId-$episodeId';
+ if (_resetItems.contains(key)) return null;
+ return _progressMap[key];
+ }
+
+ /// Count of books marked as finished in the progress map.
+ int get finishedCount => _progressMap.values
+ .where((p) => p['isFinished'] == true)
+ .length;
+
+ // Local progress overrides (from ProgressSyncService)
+ final Map<String, double> _localProgressOverrides = {};
+ // Items that have been reset — force progress to 0 until app restart
+ final Set<String> _resetItems = {};
+
+ /// Merge local progress into the display. Call after playback.
+ Future<void> refreshLocalProgress() async {
+ final sync = ProgressSyncService();
+ // Check both server-known items and downloaded items
+ final itemIds = <String>{..._progressMap.keys};
+ for (final dl in DownloadService().downloadedItems) {
+ itemIds.add(dl.itemId);
+ }
+ for (final itemId in itemIds) {
+ final data = await sync.getLocal(itemId);
+ if (data != null) {
+ final currentTime = (data['currentTime'] as num?)?.toDouble() ?? 0;
+ final duration = (data['duration'] as num?)?.toDouble() ?? 0;
+ if (duration > 0) {
+ _localProgressOverrides[itemId] = (currentTime / duration).clamp(0.0, 1.0);
+ // If item was reset but is now being played, clear the reset flag
+ if (currentTime > 0) _resetItems.remove(itemId);
+ }
+ }
+ }
+ notifyListeners();
+ }
+
+ /// Clear all local progress caches for an item (used after mark finished/not finished).
+ void clearProgressFor(String itemId) {
+ _progressMap.remove(itemId);
+ _localProgressOverrides.remove(itemId);
+ notifyListeners();
+ }
+
+ /// Clear progress AND mark as reset — forces 0 progress until playback resumes.
+ void resetProgressFor(String itemId) {
+ _progressMap.remove(itemId);
+ _localProgressOverrides.remove(itemId);
+ _resetItems.add(itemId);
+ notifyListeners();
+ }
+
+ Map<String, dynamic>? get selectedLibrary {
+ if (_selectedLibraryId == null) return null;
+ try {
+ return _libraries.firstWhere(
+ (l) => l['id'] == _selectedLibraryId,
+ ) as Map<String, dynamic>;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Whether the currently selected library is a podcast library.
+ bool get isPodcastLibrary {
+ final lib = selectedLibrary;
+ if (lib == null) return false;
+ return (lib['mediaType'] as String? ?? 'book') == 'podcast';
+ }
+
+ /// The media type of the selected library ('book' or 'podcast').
+ String get selectedMediaType {
+ final lib = selectedLibrary;
+ if (lib == null) return 'book';
+ return lib['mediaType'] as String? ?? 'book';
+ }
+
+ StreamSubscription? _connectivitySub;
+
+ /// Called by ProxyProvider when auth changes.
+ String? _lastAuthKey; // Guard against redundant updateAuth from ProxyProvider
+
+ void updateAuth(AuthProvider auth) {
+ final wasAuthenticated = _auth?.isAuthenticated ?? false;
+ final previousUserId = _auth?.userId;
+ _auth = auth;
+
+ if (auth.isAuthenticated) {
+ final isNewUser = previousUserId != null && previousUserId != auth.userId;
+ final isFreshLogin = !wasAuthenticated;
+
+ // Build a key to detect duplicate calls from ProxyProvider re-triggering
+ final authKey = '${auth.userId}@${auth.serverUrl}';
+ final isDuplicate = authKey == _lastAuthKey && !isNewUser && !isFreshLogin;
+ _lastAuthKey = authKey;
+
+ if (isDuplicate) return; // Skip redundant update
+
+ if (isNewUser || isFreshLogin) {
+ _libraries = [];
+ _personalizedSections = [];
+ _series = [];
+ _progressMap = {};
+ _localProgressOverrides.clear();
+ _resetItems.clear();
+ _manualAbsorbAdds.clear();
+ _manualAbsorbRemoves.clear();
+ _absorbingBookIds.clear();
+ _absorbingItemCache.clear();
+ _isLoading = true;
+ notifyListeners(); // Immediately clear old user's data from UI
+ }
+
+ // Restore manual offline preference and start connectivity monitoring
+ // Must complete before loading libraries so offline state is correct
+ AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
+
+ restoreOfflineMode().then((_) {
+ _startConnectivityMonitoring();
+ _loadManualAbsorbing();
+
+ // If server was unreachable on startup, force offline mode and ping
+ if (!auth.serverReachable) {
+ _networkOffline = true;
+ _buildOfflineSections();
+ _isLoading = false;
+ notifyListeners();
+ if (_deviceHasConnectivity) _startServerPingTimer();
+ return;
+ }
+
+ _buildProgressMap(auth);
+ if (_api != null && !isOffline) {
+ ProgressSyncService().flushPendingSync(api: _api!);
+ DownloadService().enrichMetadata(_api!);
+ }
+ loadLibraries();
+ });
+ } else {
+ _lastAuthKey = null;
+ AudioPlayerService.setOnBookFinishedCallback(null);
+ _libraries = [];
+ _personalizedSections = [];
+ _series = [];
+ _progressMap = {};
+ _localProgressOverrides.clear();
+ _selectedLibraryId = null;
+ _errorMessage = null;
+ _connectivitySub?.cancel();
+ _stopServerPingTimer();
+ notifyListeners();
+ }
+ }
+
+ void _startConnectivityMonitoring() {
+ _connectivitySub?.cancel();
+ // Check current state immediately
+ Connectivity().checkConnectivity().then((result) {
+ _deviceHasConnectivity = !result.contains(ConnectivityResult.none);
+ if (!_deviceHasConnectivity) {
+ _stopServerPingTimer();
+ setNetworkOffline(true);
+ } else if (_networkOffline && !_manualOffline) {
+ // Device has connectivity but we're still offline — server was unreachable
+ _startServerPingTimer();
+ }
+ });
+ // Then listen for changes
+ _connectivitySub = Connectivity().onConnectivityChanged.listen((result) {
+ final hasConnectivity = !result.contains(ConnectivityResult.none);
+ _deviceHasConnectivity = hasConnectivity;
+ if (!hasConnectivity) {
+ _stopServerPingTimer();
+ setNetworkOffline(true);
+ } else if (!_manualOffline) {
+ // Connectivity restored — optimistically go online; if server is still
+ // down the API call will fail and _goOfflineWithPing() will be called.
+ setNetworkOffline(false);
+ }
+ });
+ }
+
+ /// Start a periodic timer that pings the server until it responds.
+ /// Used when the device has network but the server was unreachable.
+ void _startServerPingTimer() {
+ _serverPingTimer?.cancel();
+ final serverUrl = _auth?.serverUrl;
+ if (serverUrl == null) return;
+ debugPrint('[Library] Starting server ping timer');
+ _serverPingTimer = Timer.periodic(const Duration(seconds: 20), (_) async {
+ if (!_networkOffline || _manualOffline) {
+ _stopServerPingTimer();
+ return;
+ }
+ final reachable = await ApiService.pingServer(
+ serverUrl,
+ customHeaders: _auth?.customHeaders ?? {},
+ );
+ if (reachable) {
+ debugPrint('[Library] Server ping succeeded — going online');
+ _stopServerPingTimer();
+ setNetworkOffline(false);
+ }
+ });
+ }
+
+ void _stopServerPingTimer() {
+ _serverPingTimer?.cancel();
+ _serverPingTimer = null;
+ }
+
+ void _buildProgressMap(AuthProvider auth) {
+ _progressMap = {};
+ final userJson = auth.userJson;
+ if (userJson == null) return;
+ final progressList = userJson['mediaProgress'] as List<dynamic>?;
+ if (progressList == null) return;
+ for (final mp in progressList) {
+ if (mp is Map<String, dynamic>) {
+ final itemId = mp['libraryItemId'] as String?;
+ final episodeId = mp['episodeId'] as String?;
+ if (itemId != null) {
+ // For podcast episodes, key is "itemId-episodeId"
+ // For books, key is just "itemId"
+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;
+ _progressMap[key] = mp;
+ }
+ }
+ }
+ }
+
+ /// Fetch all libraries and auto-select the default.
+ Future<void> loadLibraries() async {
+ if (_api == null) return;
+
+ if (isOffline) {
+ _buildOfflineSections();
+ return;
+ }
+
+ _isLoading = true;
+ _errorMessage = null;
+ notifyListeners();
+
+ try {
+ _libraries = await _api!.getLibraries();
+
+ if (_libraries.isNotEmpty) {
+ // Prefer last user-selected library, then server default, then first book library
+ final savedId = await ScopedPrefs.getString('last_selected_library');
+ final defaultId = _auth?.defaultLibraryId;
+ if (savedId != null && _libraries.any((l) => l['id'] == savedId)) {
+ _selectedLibraryId = savedId;
+ } else if (defaultId != null && _libraries.any((l) => l['id'] == defaultId)) {
+ _selectedLibraryId = defaultId;
+ } else {
+ // Prefer a book library as the fallback default
+ final bookLibraries = _libraries.where(
+ (l) => (l['mediaType'] as String? ?? 'book') != 'podcast').toList();
+ _selectedLibraryId = bookLibraries.isNotEmpty
+ ? bookLibraries.first['id']
+ : _libraries.first['id'];
+ }
+ await loadPersonalizedView();
+ }
+ } catch (e) {
+ // Network error — auto-switch to offline view
+ if (!_networkOffline) {
+ _networkOffline = true;
+ _buildOfflineSections();
+ if (_deviceHasConnectivity && !_manualOffline) _startServerPingTimer();
+ }
+ }
+
+ _isLoading = false;
+ notifyListeners();
+ }
+
+ /// Change the selected library and reload data.
+ Future<void> selectLibrary(String libraryId) async {
+ _selectedLibraryId = libraryId;
+ _series = [];
+ await ScopedPrefs.setString('last_selected_library', libraryId);
+ notifyListeners();
+ await loadPersonalizedView();
+ }
+
+ /// Fetch personalized home sections for the selected library.
+ Future<void> loadPersonalizedView() async {
+ if (_api == null || _selectedLibraryId == null) return;
+
+ if (isOffline) {
+ _buildOfflineSections();
+ return;
+ }
+
+ // Only show loading spinner if we have NO existing data.
+ // If we already have sections, do a silent background refresh.
+ final hadData = _personalizedSections.isNotEmpty;
+ if (!hadData) {
+ _isLoading = true;
+ notifyListeners();
+ }
+
+ try {
+ await _refreshProgress();
+ _personalizedSections =
+ await _api!.getPersonalizedView(_selectedLibraryId!);
+ await _updateAbsorbingCache();
+ } catch (e) {
+ // Network error — auto-switch to offline view
+ if (!_networkOffline) {
+ _networkOffline = true;
+ _buildOfflineSections();
+ if (_deviceHasConnectivity && !_manualOffline) _startServerPingTimer();
+ }
+ }
+
+ _isLoading = false;
+ notifyListeners();
+ }
+
+ Future<void> _refreshProgress() async {
+ if (_api == null) return;
+ try {
+ final me = await _api!.getMe();
+ if (me != null) {
+ final progressList = me['mediaProgress'] as List<dynamic>?;
+ if (progressList != null) {
+ _progressMap = {};
+ for (final mp in progressList) {
+ if (mp is Map<String, dynamic>) {
+ final itemId = mp['libraryItemId'] as String?;
+ final episodeId = mp['episodeId'] as String?;
+ if (itemId != null) {
+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;
+ _progressMap[key] = mp;
+ }
+ }
+ }
+ }
+ }
+ } catch (_) {}
+ }
+
+ /// Refresh data (pull-to-refresh).
+ Future<void> refresh() async {
+ if (isOffline) {
+ _buildOfflineSections();
+ notifyListeners();
+ return;
+ }
+ // Flush local progress to server first, then pull fresh data
+ if (_api != null) {
+ await ProgressSyncService().flushPendingSync(api: _api!);
+ }
+ await Future.wait([
+ loadPersonalizedView(),
+ _refreshProgress(),
+ ]);
+ // Clear stale local overrides — server data is now authoritative
+ _localProgressOverrides.clear();
+ // Update local SharedPreferences from fresh server data so they stay in sync
+ final sync = ProgressSyncService();
+ for (final entry in _progressMap.entries) {
+ final itemId = entry.key;
+ final mp = entry.value;
+ final currentTime = (mp['currentTime'] as num?)?.toDouble() ?? 0;
+ final duration = (mp['duration'] as num?)?.toDouble() ?? 0;
+ if (duration > 0 && currentTime > 0) {
+ await sync.saveLocal(
+ itemId: itemId,
+ currentTime: currentTime,
+ duration: duration,
+ speed: 1.0,
+ );
+ }
+ }
+ // Clear pending syncs since we just pulled fresh server data
+ await ScopedPrefs.setStringList('pending_syncs', []);
+ notifyListeners();
+ }
+
+ /// Fetch series for the selected library.
+ Future<void> loadSeries({String sort = 'addedAt', int desc = 1}) async {
+ if (_api == null || _selectedLibraryId == null) return;
+
+ _isLoadingSeries = true;
+ notifyListeners();
+
+ try {
+ final result = await _api!.getLibrarySeries(
+ _selectedLibraryId!,
+ sort: sort,
+ desc: desc,
+ );
+ if (result != null) {
+ _series = (result['results'] as List<dynamic>?) ?? [];
+ }
+ } catch (e) {
+ // ignore
+ }
+
+ _isLoadingSeries = false;
+ notifyListeners();
+ }
+
+ /// Build a cover URL for an item.
+ /// When offline, prefers the locally cached cover file.
+ /// For podcast episodes stored under composite keys (e.g. "showId-epId"),
+ /// also checks downloads matching the given itemId as a prefix.
+ String? getCoverUrl(String? itemId, {int width = 400}) {
+ if (itemId == null) return null;
+
+ // For podcast episodes stored under composite keys like "showId-ep_xxx",
+ // extract the show ID for API calls so the server returns the show cover.
+ final isCompositeKey = itemId.contains('-ep_');
+ final apiItemId = isCompositeKey
+ ? itemId.substring(0, itemId.indexOf('-ep_'))
+ : itemId;
+
+ // Try API first when online
+ if (_api != null && !isOffline) {
+ return _api!.getCoverUrl(apiItemId, width: width);
+ }
+
+ // Offline or no API: prefer local cover path
+ final dl = DownloadService().getInfo(itemId);
+ if (dl.localCoverPath != null) {
+ return dl.localCoverPath;
+ }
+
+ // For podcast shows, the cover may be stored under a composite episode key.
+ // Check if any downloaded episode matches this show ID as a prefix.
+ if (dl.status == DownloadStatus.none) {
+ final match = DownloadService().downloadedItems
+ .where((d) => d.itemId.startsWith('$itemId-') && d.localCoverPath != null)
+ .firstOrNull;
+ if (match?.localCoverPath != null) {
+ return match!.localCoverPath;
+ }
+ }
+
+ // Fall back to remote URL (may work if CachedNetworkImage has it cached)
+ if (_api != null) return _api!.getCoverUrl(apiItemId, width: width);
+ return dl.coverUrl;
+ }
+
+ /// Headers needed for authenticated media requests (covers, audio).
+ /// Returns empty map if no API is available.
+ Map<String, String> get mediaHeaders => _api?.mediaHeaders ?? {};
+
+ // ── Manual Absorbing List ──
+
+ Set<String> _manualAbsorbAdds = {};
+ Set<String> _manualAbsorbRemoves = {};
+ // Persisted set of all book IDs ever shown on the absorbing page
+ Set<String> _absorbingBookIds = {};
+ // Cached item data for books that may no longer be in server sections
+ Map<String, Map<String, dynamic>> _absorbingItemCache = {};
+
+ Set<String> get manualAbsorbAdds => _manualAbsorbAdds;
+ Set<String> get manualAbsorbRemoves => _manualAbsorbRemoves;
+ Set<String> get absorbingBookIds => _absorbingBookIds;
+ Map<String, Map<String, dynamic>> get absorbingItemCache => _absorbingItemCache;
+
+ Future<void> _loadManualAbsorbing() async {
+ _manualAbsorbAdds = (await ScopedPrefs.getStringList('absorbing_manual_adds')).toSet();
+ _manualAbsorbRemoves = (await ScopedPrefs.getStringList('absorbing_manual_removes')).toSet();
+ _absorbingBookIds = (await ScopedPrefs.getStringList('absorbing_seen_ids')).toSet();
+ final cacheList = await ScopedPrefs.getStringList('absorbing_item_cache_v2');
+ _absorbingItemCache = {};
+ for (final s in cacheList) {
+ try {
+ final m = jsonDecode(s) as Map<String, dynamic>;
+ // Use _absorbingKey if present (compound key for podcast episodes),
+ // otherwise fall back to item id (books / legacy entries)
+ final key = m['_absorbingKey'] as String? ?? m['id'] as String?;
+ if (key != null) _absorbingItemCache[key] = m;
+ } catch (_) {}
+ }
+ }
+
+ Future<void> _saveManualAbsorbing() async {
+ await ScopedPrefs.setStringList('absorbing_manual_adds', _manualAbsorbAdds.toList());
+ await ScopedPrefs.setStringList('absorbing_manual_removes', _manualAbsorbRemoves.toList());
+ await ScopedPrefs.setStringList('absorbing_seen_ids', _absorbingBookIds.toList());
+ await ScopedPrefs.setStringList('absorbing_item_cache_v2',
+ _absorbingItemCache.values.map((e) => jsonEncode(e)).toList());
+ }
+
+ /// Scans current sections and adds qualifying items to the persisted absorbing list.
+ /// Called after each section refresh so finished books stay visible even after
+ /// the server removes them from continue-listening.
+ ///
+ /// For podcasts, each in-progress episode gets its own entry keyed by
+ /// "itemId-episodeId" so multiple episodes from the same show appear as
+ /// separate cards on the Absorbing screen.
+ Future<void> _updateAbsorbingCache() async {
+ // Collect IDs currently present in the allowed in-progress sections
+ final allowedKeys = <String>{};
+ // Map showId -> show entity from sections (for cloning into episode entries)
+ final showEntities = <String, Map<String, dynamic>>{};
+
+ for (final section in _personalizedSections) {
+ final id = section['id'] as String? ?? '';
+ if (id == 'continue-listening' || id == 'continue-series' ||
+ id == 'downloaded-books') {
+ for (final e in (section['entities'] as List<dynamic>? ?? [])) {
+ if (e is Map<String, dynamic>) {
+ final itemId = e['id'] as String?;
+ if (itemId == null) continue;
+ final recentEpisode = e['recentEpisode'] as Map<String, dynamic>?;
+ if (recentEpisode != null) {
+ // Podcast episode — use compound key
+ final episodeId = recentEpisode['id'] as String?;
+ if (episodeId != null) {
+ final key = '$itemId-$episodeId';
+ allowedKeys.add(key);
+ showEntities[itemId] = e;
+ if (!_manualAbsorbRemoves.contains(key)) {
+ _absorbingBookIds.add(key);
+ _absorbingItemCache[key] = {...e, '_absorbingKey': key};
+ }
+ }
+ } else {
+ // Book — use plain itemId
+ allowedKeys.add(itemId);
+ if (!_manualAbsorbRemoves.contains(itemId)) {
+ _absorbingBookIds.add(itemId);
+ _absorbingItemCache[itemId] = e;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // For podcast libraries, scan _progressMap for additional in-progress
+ // episodes not already represented in continue-listening sections.
+ if (isPodcastLibrary) {
+ // Collect show IDs we know about (from sections or cache)
+ final knownShowIds = <String>{};
+ for (final key in _absorbingBookIds) {
+ if (key.contains('-')) {
+ knownShowIds.add(key.split('-').first);
+ }
+ }
+ // Also add show entities from sections
+ knownShowIds.addAll(showEntities.keys);
+
+ for (final entry in _progressMap.entries) {
+ final key = entry.key;
+ if (!key.contains('-')) continue; // not an episode entry
+ final mp = entry.value;
+ if (mp['isFinished'] == true) continue; // skip finished episodes
+ final progress = (mp['progress'] as num?)?.toDouble() ?? 0;
+ if (progress <= 0) continue; // never actually played
+
+ final parts = key.split('-');
+ final showId = parts[0];
+ final episodeId = parts.sublist(1).join('-');
+
+ if (_absorbingBookIds.contains(key)) continue; // already have it
+ if (_manualAbsorbRemoves.contains(key)) continue; // user removed it
+ if (!knownShowIds.contains(showId)) continue; // unknown show
+
+ // Find show data to clone
+ final showData = showEntities[showId] ?? _absorbingItemCache.values
+ .cast<Map<String, dynamic>?>()
+ .firstWhere(
+ (c) => c != null && (c['id'] as String?) == showId,
+ orElse: () => null,
+ );
+ if (showData == null) continue;
+
+ // Create synthetic entry with this episode as recentEpisode
+ final duration = (mp['duration'] as num?)?.toDouble() ?? 0;
+ final currentTime = (mp['currentTime'] as num?)?.toDouble() ?? 0;
+ final syntheticEntry = Map<String, dynamic>.from(showData);
+ syntheticEntry['recentEpisode'] = {
+ 'id': episodeId,
+ 'duration': duration,
+ 'currentTime': currentTime,
+ // Title will be filled in by _enrichEpisodeTitles
+ 'title': 'Episode',
+ };
+ syntheticEntry['_absorbingKey'] = key;
+ _absorbingBookIds.add(key);
+ _absorbingItemCache[key] = syntheticEntry;
+ allowedKeys.add(key);
+ }
+
+ // Fetch actual episode titles for synthetic entries (async, non-blocking)
+ _enrichEpisodeTitles();
+ }
+
+ // Prune stale entries: items that are no longer in the allowed sections,
+ // were not manually added, and have no progress recorded (never played).
+ final toRemove = <String>[];
+ for (final key in _absorbingBookIds) {
+ if (allowedKeys.contains(key)) continue; // still in a live section
+ if (_manualAbsorbAdds.contains(key)) continue; // user explicitly added it
+ // Keep if there is any recorded progress
+ final hasProgress = key.contains('-')
+ ? _progressMap.containsKey(key)
+ : _progressMap.keys.any((k) => k == key || k.startsWith('$key-'));
+ if (!hasProgress) toRemove.add(key);
+ }
+ for (final id in toRemove) {
+ _absorbingBookIds.remove(id);
+ _absorbingItemCache.remove(id);
+ }
+
+ // Migrate any old-style plain show IDs that should be compound keys
+ // (from before this change). If an entry has recentEpisode, re-key it.
+ final migrateRemove = <String>[];
+ final migrateAdd = <String, Map<String, dynamic>>{};
+ for (final key in _absorbingBookIds) {
+ if (key.contains('-')) continue; // already compound
+ final cached = _absorbingItemCache[key];
+ if (cached == null) continue;
+ final re = cached['recentEpisode'] as Map<String, dynamic>?;
+ if (re == null) continue; // book, not episode
+ final epId = re['id'] as String?;
+ if (epId == null) continue;
+ final newKey = '$key-$epId';
+ if (!_absorbingBookIds.contains(newKey)) {
+ migrateRemove.add(key);
+ migrateAdd[newKey] = {...cached, '_absorbingKey': newKey};
+ }
+ }
+ for (final old in migrateRemove) {
+ _absorbingBookIds.remove(old);
+ _absorbingItemCache.remove(old);
+ }
+ for (final entry in migrateAdd.entries) {
+ _absorbingBookIds.add(entry.key);
+ _absorbingItemCache[entry.key] = entry.value;
+ }
+
+ await _saveManualAbsorbing();
+ }
+
+ /// Fetch full show data to fill in episode titles for synthetic entries.
+ Future<void> _enrichEpisodeTitles() async {
+ if (_api == null) return;
+ // Collect show IDs that need episode title enrichment
+ final needsEnrich = <String, List<String>>{}; // showId -> [episodeId, ...]
+ for (final entry in _absorbingItemCache.entries) {
+ final ep = entry.value['recentEpisode'] as Map<String, dynamic>?;
+ if (ep == null) continue;
+ if ((ep['title'] as String?) != 'Episode') continue; // only enrich placeholders
+ final showId = entry.value['id'] as String?;
+ final epId = ep['id'] as String?;
+ if (showId == null || epId == null) continue;
+ needsEnrich.putIfAbsent(showId, () => []).add(epId);
+ }
+ for (final showId in needsEnrich.keys) {
+ try {
+ final fullItem = await _api!.getLibraryItem(showId);
+ if (fullItem == null) continue;
+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ for (final epId in needsEnrich[showId]!) {
+ final key = '$showId-$epId';
+ final cached = _absorbingItemCache[key];
+ if (cached == null) continue;
+ // Find matching episode
+ final ep = episodes.cast<Map<String, dynamic>?>().firstWhere(
+ (e) => e != null && (e['id'] as String?) == epId,
+ orElse: () => null,
+ );
+ if (ep != null) {
+ cached['recentEpisode'] = Map<String, dynamic>.from(ep);
+ _absorbingItemCache[key] = cached;
+ }
+ }
+ } catch (_) {}
+ }
+ if (needsEnrich.isNotEmpty) {
+ await _saveManualAbsorbing();
+ notifyListeners();
+ }
+ }
+
+ /// Add a book to the absorbing list manually.
+ Future<void> addToAbsorbing(String itemId) async {
+ _manualAbsorbAdds.add(itemId);
+ _manualAbsorbRemoves.remove(itemId);
+ _absorbingBookIds.add(itemId);
+ await _saveManualAbsorbing();
+ notifyListeners();
+ }
+
+ /// Re-allow an item that was previously removed, so it can reappear in Absorbing.
+ /// Called when the user explicitly plays an item that they had removed.
+ /// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).
+ void unblockFromAbsorbing(String key) {
+ bool changed = _manualAbsorbRemoves.remove(key);
+ if (!_absorbingBookIds.contains(key)) {
+ _absorbingBookIds.add(key);
+ changed = true;
+ // Populate the cache from current sections if available
+ final isCompound = key.contains('-');
+ final showId = isCompound ? key.split('-').first : key;
+ for (final section in _personalizedSections) {
+ for (final e in (section['entities'] as List<dynamic>? ?? [])) {
+ if (e is Map<String, dynamic> && (e['id'] as String?) == showId) {
+ if (isCompound) {
+ _absorbingItemCache[key] = {...e, '_absorbingKey': key};
+ } else {
+ _absorbingItemCache[key] = e;
+ }
+ break;
+ }
+ }
+ }
+ }
+ if (changed) _saveManualAbsorbing();
+ }
+
+ /// Remove a book/episode from the absorbing list manually.
+ /// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).
+ Future<void> removeFromAbsorbing(String key) async {
+ _manualAbsorbRemoves.add(key);
+ _manualAbsorbAdds.remove(key);
+ _absorbingBookIds.remove(key);
+ _absorbingItemCache.remove(key);
+ await _saveManualAbsorbing();
+ notifyListeners();
+ }
+
+ /// Mark an item as finished locally so the overlay appears immediately,
+ /// before the next server refresh confirms isFinished.
+ void markFinishedLocally(String itemId) {
+ if (_resetItems.contains(itemId)) return;
+ final existing = _progressMap[itemId] ?? {};
+ _progressMap[itemId] = {...existing, 'isFinished': true};
+ _localProgressOverrides[itemId] = 1.0;
+ notifyListeners();
+ }
+
+ /// Check if a book/episode is on the absorbing page (persisted local list, not removed).
+ /// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).
+ bool isOnAbsorbingList(String key) {
+ if (_manualAbsorbRemoves.contains(key)) return false;
+ return _absorbingBookIds.contains(key);
+ }
+}
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
new file mode 100644
index 00000000..cd5c548d
--- /dev/null
+++ b/lib/screens/absorbing_screen.dart
@@ -0,0 +1,530 @@
+import 'dart:async';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/download_service.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/absorbing_card.dart';
+
+class AbsorbingScreen extends StatefulWidget {
+ const AbsorbingScreen({super.key});
+
+ /// Global key for accessing the absorbing screen state
+ static final globalKey = GlobalKey<_AbsorbingScreenState>();
+
+ /// Scroll to the currently playing book card
+ static void scrollToActive() {
+ globalKey.currentState?._scrollToActiveCard();
+ }
+
+ @override
+ State<AbsorbingScreen> createState() => _AbsorbingScreenState();
+}
+
+class _AbsorbingScreenState extends State<AbsorbingScreen> {
+ final _player = AudioPlayerService();
+ final _pageController = PageController(viewportFraction: 0.92);
+
+ @override
+ void initState() {
+ super.initState();
+ _player.addListener(_rebuild);
+ }
+
+ @override
+ void dispose() {
+ _player.removeListener(_rebuild);
+ _pageController.dispose();
+ super.dispose();
+ }
+
+ String? _lastPlayingId;
+ String? _lastPlayingEpisodeId;
+ String? _lastFinishedId;
+ bool _isSyncing = false;
+ // When true, _getAbsorbingBooks keeps the original list order (no move-to-front).
+ // Used during the slide-to-front animation so the user sees their book smoothly
+ // slide to the beginning rather than the list instantly reordering underneath them.
+ bool _suppressReorder = false;
+
+ void _rebuild() {
+ if (!mounted) return;
+ // Detect item or episode change (same show, different episode counts as a change)
+ final itemChanged = _player.currentItemId != _lastPlayingId;
+ final episodeChanged = _player.currentEpisodeId != _lastPlayingEpisodeId;
+ if (itemChanged || episodeChanged) {
+ final wasPlayingId = _lastPlayingId;
+ final wasEpisodeId = _lastPlayingEpisodeId;
+ _lastPlayingId = _player.currentItemId;
+ _lastPlayingEpisodeId = _player.currentEpisodeId;
+ if (_player.hasBook) {
+ // If this item was previously removed from Absorbing, un-block it now
+ // that the user has explicitly played it again.
+ final lib = context.read<LibraryProvider>();
+ final playingKey = _player.currentEpisodeId != null
+ ? '${_player.currentItemId!}-${_player.currentEpisodeId!}'
+ : _player.currentItemId!;
+ lib.unblockFromAbsorbing(playingKey);
+ // Suppress the list reorder if we're not already at page 0, so the
+ // animation slides the current view to the front instead of jumping.
+ final currentPage = _pageController.hasClients
+ ? (_pageController.page ?? 0).round()
+ : 0;
+ _suppressReorder = currentPage > 0;
+ WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToActiveCard());
+ } else if (wasPlayingId != null && !_isSyncing) {
+ // Book/episode just stopped (natural completion or session end)
+ _suppressReorder = false;
+ // For podcast episodes, use compound key
+ final finishedKey = wasEpisodeId != null
+ ? '$wasPlayingId-$wasEpisodeId'
+ : wasPlayingId;
+ _lastFinishedId = finishedKey;
+ final lib = context.read<LibraryProvider>();
+ lib.markFinishedLocally(finishedKey);
+ }
+ }
+ setState(() {});
+ }
+
+ void _scrollToActiveCard({int retries = 2}) {
+ if (!_player.hasBook || !mounted) return;
+ final lib = context.read<LibraryProvider>();
+ final books = _getAbsorbingBooks(lib);
+ final playingKey = _player.currentEpisodeId != null
+ ? '${_player.currentItemId!}-${_player.currentEpisodeId!}'
+ : _player.currentItemId!;
+ final idx = books.indexWhere((b) => _absorbingKey(b) == playingKey);
+ if (idx >= 0 && _pageController.hasClients) {
+ if (_suppressReorder) {
+ // Animate from the current page to 0 while keeping the original list order.
+ // After the animation lands at 0, release suppression so the list properly
+ // reorders with the playing item at index 0.
+ _pageController
+ .animateToPage(0,
+ duration: const Duration(milliseconds: 400),
+ curve: Curves.easeInOutCubic)
+ .then((_) {
+ if (!mounted) return;
+ _suppressReorder = false;
+ setState(() {});
+ });
+ } else {
+ _pageController.animateToPage(idx,
+ duration: const Duration(milliseconds: 350),
+ curve: Curves.easeOutCubic);
+ }
+ } else if (retries > 0) {
+ // Book might not be in the list yet — retry after a rebuild
+ _suppressReorder = false;
+ Future.delayed(const Duration(milliseconds: 300), () {
+ if (mounted) _scrollToActiveCard(retries: retries - 1);
+ });
+ } else {
+ _suppressReorder = false;
+ }
+ }
+
+ Future<void> _stopAndRefresh(LibraryProvider lib) async {
+ if (_isSyncing) return;
+ setState(() => _isSyncing = true);
+ if (_player.hasBook) {
+ await _player.pause();
+ await _player.stop();
+ }
+ lib.refreshLocalProgress();
+ await lib.refresh();
+ if (mounted) setState(() => _isSyncing = false);
+ }
+
+ /// Pull-to-refresh: sync progress to/from server without stopping playback.
+ Future<void> _pullRefresh() async {
+ final lib = context.read<LibraryProvider>();
+ if (lib.isOffline) return;
+ await lib.refresh();
+ }
+
+ /// Derive the absorbing key for an item map: compound "itemId-episodeId" for
+ /// podcast episodes, plain "itemId" for books.
+ String _absorbingKey(Map<String, dynamic> item) {
+ // Explicit key stored by _updateAbsorbingCache
+ final explicit = item['_absorbingKey'] as String?;
+ if (explicit != null) return explicit;
+ final itemId = item['id'] as String? ?? '';
+ final re = item['recentEpisode'] as Map<String, dynamic>?;
+ final epId = re?['id'] as String?;
+ if (epId != null) return '$itemId-$epId';
+ return itemId;
+ }
+
+ List<Map<String, dynamic>> _getAbsorbingBooks(LibraryProvider lib) {
+ final removes = lib.manualAbsorbRemoves;
+ final cache = lib.absorbingItemCache;
+
+ // Quick lookup of fresh data — only from the in-progress sections.
+ // For podcast episodes, key by compound "itemId-episodeId".
+ const allowedSections = {'continue-listening', 'continue-series', 'downloaded-books'};
+ final sectionLookup = <String, Map<String, dynamic>>{};
+ for (final section in lib.personalizedSections) {
+ final sectionId = section['id'] as String? ?? '';
+ if (!allowedSections.contains(sectionId)) continue;
+ for (final e in (section['entities'] as List<dynamic>? ?? [])) {
+ if (e is Map<String, dynamic>) {
+ final itemId = e['id'] as String?;
+ if (itemId == null) continue;
+ final re = e['recentEpisode'] as Map<String, dynamic>?;
+ final epId = re?['id'] as String?;
+ final key = epId != null ? '$itemId-$epId' : itemId;
+ sectionLookup[key] = e;
+ }
+ }
+ }
+
+ // Build list from the persisted local absorbing set.
+ // Books stay here even after the server removes them from continue-listening.
+ // absorbingBookIds now contains compound keys for podcast episodes.
+ final selectedLibraryId = lib.selectedLibraryId;
+ final items = <Map<String, dynamic>>[];
+ for (final key in lib.absorbingBookIds) {
+ if (removes.contains(key)) continue;
+ // Prefer fresh data from current library's sections
+ final fromSection = sectionLookup[key];
+ if (fromSection != null) {
+ items.add(fromSection);
+ continue;
+ }
+ // Cache fallback — only include if it matches the current library
+ final cached = cache[key];
+ if (cached != null) {
+ final itemLibId = cached['libraryId'] as String?;
+ if (selectedLibraryId == null || itemLibId == null || itemLibId == selectedLibraryId) {
+ items.add(cached);
+ }
+ }
+ }
+
+ // If the currently playing item isn't in the list, add it at the front.
+ // For podcast episodes, match by compound key.
+ // Skip if the playing item belongs to a different library type.
+ final isPod = lib.isPodcastLibrary;
+ if (_player.hasBook && _player.currentItemId != null) {
+ final playingId = _player.currentItemId!;
+ final playingEpId = _player.currentEpisodeId;
+ final playingIsPodcast = playingEpId != null;
+ // Only show if the playing item matches the current library type
+ if (playingIsPodcast == isPod) {
+ final playingKey = playingEpId != null ? '$playingId-$playingEpId' : playingId;
+
+ final existingIdx = items.indexWhere((b) => _absorbingKey(b) == playingKey);
+ if (!_suppressReorder && existingIdx > 0) {
+ final item = items.removeAt(existingIdx);
+ items.insert(0, item);
+ } else if (existingIdx < 0) {
+ // Synthesize entry for the currently playing item
+ final entry = <String, dynamic>{
+ 'id': playingId,
+ 'media': {
+ 'metadata': {
+ 'title': _player.currentTitle,
+ 'authorName': _player.currentAuthor,
+ },
+ 'duration': _player.totalDuration,
+ 'chapters': _player.chapters,
+ },
+ };
+ if (playingEpId != null) {
+ entry['recentEpisode'] = {
+ 'id': playingEpId,
+ 'title': _player.currentEpisodeTitle ?? _player.currentTitle,
+ 'duration': _player.totalDuration,
+ };
+ entry['_absorbingKey'] = playingKey;
+ }
+ items.insert(0, entry);
+ }
+ }
+ }
+
+ // When nothing is playing, keep the last-finished item at the front
+ // Only if it matches the current library type
+ if (!_player.hasBook && _lastFinishedId != null && !removes.contains(_lastFinishedId)) {
+ final finishedIsPodcast = _lastFinishedId!.contains('-');
+ if (finishedIsPodcast == isPod) {
+ final finishedIdx = items.indexWhere((b) => _absorbingKey(b) == _lastFinishedId);
+ if (finishedIdx > 0) {
+ final item = items.removeAt(finishedIdx);
+ items.insert(0, item);
+ }
+ }
+ }
+
+ return items;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final dl = DownloadService();
+ var books = _getAbsorbingBooks(lib);
+
+ // Force offline mode when actually offline
+ final effectiveOffline = lib.isOffline;
+ if (effectiveOffline) {
+ books = books.where((b) => dl.isDownloaded(b['id'] as String? ?? '')).toList();
+ }
+
+ return Scaffold(
+ backgroundColor: Colors.black,
+ body: SafeArea(
+ child: Column(
+ children: [
+ // ── Header ──
+ AbsorbPageHeader(
+ title: 'Absorbing',
+ brandingColor: Colors.white38,
+ titleColor: Colors.white,
+ padding: const EdgeInsets.fromLTRB(20, 12, 12, 0),
+ actions: [
+ // Offline mode toggle
+ GestureDetector(
+ onTap: () {
+ final newVal = !lib.isManualOffline;
+ lib.setManualOffline(newVal);
+ if (newVal) _stopAndRefresh(lib);
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOutCubic,
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: effectiveOffline ? Colors.orange.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: effectiveOffline ? Colors.orange.withValues(alpha: 0.3) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ effectiveOffline ? Icons.airplanemode_active_rounded : Icons.airplanemode_inactive_rounded,
+ size: 14, color: effectiveOffline ? Colors.orange : Colors.white38,
+ ),
+ const SizedBox(width: 4),
+ Text(
+ effectiveOffline ? 'Offline' : 'Online',
+ style: TextStyle(
+ color: effectiveOffline ? Colors.orange : Colors.white38,
+ fontSize: 11, fontWeight: FontWeight.w500,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ // Unified button: "Sync" when idle, "Stop & Sync" when playing
+ if (!effectiveOffline)
+ GestureDetector(
+ onTap: _isSyncing ? null : () {
+ if (_player.hasBook) {
+ _stopAndRefresh(lib);
+ } else {
+ () async {
+ setState(() => _isSyncing = true);
+ await _pullRefresh();
+ if (mounted) setState(() => _isSyncing = false);
+ }();
+ }
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ if (_isSyncing) ...[
+ const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white38)),
+ const SizedBox(width: 6),
+ const Text('Syncing…', style: TextStyle(color: Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ ] else if (_player.hasBook) ...[
+ const Icon(Icons.stop_rounded, size: 14, color: Colors.white38),
+ const SizedBox(width: 4),
+ const Text('Stop & Sync', style: TextStyle(color: Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ ] else ...[
+ const Icon(Icons.sync_rounded, size: 14, color: Colors.white38),
+ const SizedBox(width: 4),
+ const Text('Sync', style: TextStyle(color: Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ ],
+ ],
+ ),
+ ),
+ )
+ else
+ // Offline: just stop button (no sync)
+ AnimatedOpacity(
+ opacity: _player.hasBook ? 1.0 : 0.0,
+ duration: const Duration(milliseconds: 300),
+ child: IgnorePointer(
+ ignoring: !_player.hasBook,
+ child: GestureDetector(
+ onTap: () => _stopAndRefresh(lib),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: const Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.stop_rounded, size: 14, color: Colors.white38),
+ SizedBox(width: 4),
+ Text('Stop', style: TextStyle(color: Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ // ── Page Dots ──
+ if (books.length > 1)
+ Padding(
+ padding: const EdgeInsets.only(top: 8, bottom: 4),
+ child: _PageDots(count: books.length, controller: _pageController),
+ ),
+ // ── Cards (refreshable) ──
+ Expanded(
+ child: lib.isLoading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))
+ : books.isEmpty
+ ? _emptyState(cs, tt, effectiveOffline)
+ : PageView.builder(
+ controller: _pageController,
+ scrollDirection: Axis.horizontal,
+ clipBehavior: Clip.none,
+ physics: const PageScrollPhysics(parent: ClampingScrollPhysics()),
+ itemCount: books.length,
+ itemBuilder: (_, i) => LayoutBuilder(
+ builder: (context, constraints) {
+ final cardWidth = constraints.maxWidth;
+ final vPad = (constraints.maxHeight * 0.04).clamp(12.0, 40.0);
+ return AnimatedBuilder(
+ animation: _pageController,
+ builder: (context, child) {
+ double distFromCenter = 0.0;
+ double rawDist = 0.0;
+ if (_pageController.position.haveDimensions) {
+ final page = _pageController.page ?? _pageController.initialPage.toDouble();
+ rawDist = page - i; // negative = card is to the right
+ distFromCenter = rawDist.abs();
+ }
+ final double scaleX;
+ if (distFromCenter >= 1.0) {
+ scaleX = 0.85;
+ } else {
+ // Use easeOut curve for smoother transition
+ final t = Curves.easeOut.transform(1.0 - distFromCenter);
+ scaleX = 0.85 + (t * 0.15); // 0.85 → 1.0
+ }
+ // Calculate how much space the squeeze frees up, then translate toward center
+ final squeezedWidth = cardWidth * scaleX;
+ final freedSpace = cardWidth - squeezedWidth;
+ // Pull card toward center by half the freed space
+ final direction = rawDist > 0 ? 1.0 : (rawDist < 0 ? -1.0 : 0.0);
+ final translateX = direction * freedSpace * 0.45;
+
+ return Transform(
+ alignment: Alignment.center,
+ transform: Matrix4.identity()
+ ..translate(translateX, 0.0, 0.0)
+ ..scale(scaleX, 1.0, 1.0),
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: 4, vertical: vPad),
+ child: child,
+ ),
+ );
+ },
+ child: RepaintBoundary(child: AbsorbingCard(key: ValueKey(_absorbingKey(books[i])), item: books[i], player: _player)),
+ );
+ },
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _emptyState(ColorScheme cs, TextTheme tt, bool isOffline) {
+ final lib = context.read<LibraryProvider>();
+ final isPod = lib.isPodcastLibrary;
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(isOffline ? Icons.cloud_off_rounded
+ : isPod ? Icons.podcasts_rounded : Icons.headphones_rounded,
+ size: 64, color: Colors.white.withValues(alpha: 0.15)),
+ const SizedBox(height: 16),
+ Text(isOffline
+ ? (isPod ? 'No downloaded episodes' : 'No downloaded books')
+ : (isPod ? 'Nothing playing yet' : 'Nothing absorbing yet'),
+ style: tt.titleMedium?.copyWith(color: Colors.white38)),
+ const SizedBox(height: 8),
+ Text(isOffline
+ ? (isPod ? 'Download episodes to listen offline' : 'Download books to listen offline')
+ : (isPod ? 'Start an episode from the Shows tab' : 'Start a book from the Library tab'),
+ style: tt.bodySmall?.copyWith(color: Colors.white24)),
+ ],
+ ),
+ );
+ }
+}
+
+// ─── PAGE DOTS ──────────────────────────────────────────────
+
+class _PageDots extends StatelessWidget {
+ final int count;
+ final PageController controller;
+ const _PageDots({required this.count, required this.controller});
+
+ @override
+ Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: controller,
+ builder: (_, __) {
+ final page = controller.hasClients ? (controller.page ?? 0).round() : 0;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: List.generate(count, (i) {
+ final active = i == page;
+ return AnimatedContainer(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOutCubic,
+ margin: const EdgeInsets.symmetric(horizontal: 3),
+ width: active ? 20 : 6,
+ height: 6,
+ decoration: BoxDecoration(
+ color: active ? Colors.white54 : Colors.white.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(3),
+ ),
+ );
+ }),
+ );
+ },
+ );
+ }
+}
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dart
new file mode 100644
index 00000000..1252d3d4
--- /dev/null
+++ b/lib/screens/admin_podcasts_screen.dart
@@ -0,0 +1,1338 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../services/api_service.dart';
+import '../widgets/absorb_page_header.dart';
+
+class AdminPodcastsScreen extends StatefulWidget {
+ final Map<String, dynamic> library;
+ const AdminPodcastsScreen({super.key, required this.library});
+ @override State<AdminPodcastsScreen> createState() => _AdminPodcastsScreenState();
+}
+
+class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {
+ bool _loading = true;
+ bool _checkingEpisodes = false;
+ List<dynamic> _shows = [];
+
+ String get _libraryId => widget.library['id'] as String? ?? '';
+ String get _folderId {
+ final folders = widget.library['folders'] as List?;
+ if (folders != null && folders.isNotEmpty) return folders[0]['id'] as String? ?? '';
+ return '';
+ }
+
+ @override
+ void initState() { super.initState(); _loadShows(); }
+
+ Future<void> _loadShows() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _loading = true);
+ try {
+ final r = await api.getLibraryItems(_libraryId, limit: 100);
+ if (r != null && r['results'] is List) {
+ _shows = (r['results'] as List).map((item) {
+ if (item is Map<String, dynamic>) return item['libraryItem'] ?? item;
+ return item;
+ }).toList();
+ }
+ } catch (_) {}
+ if (mounted) setState(() => _loading = false);
+ }
+
+ Future<void> _checkNewEpisodes() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _checkingEpisodes = true);
+ final ok = await api.checkNewEpisodes(_libraryId);
+ if (mounted) {
+ setState(() => _checkingEpisodes = false);
+ ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(
+ content: Text(ok ? 'Checking for new episodes…' : 'Failed to check episodes'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ if (ok) Future.delayed(const Duration(seconds: 3), _loadShows);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ floatingActionButton: FloatingActionButton.small(
+ backgroundColor: cs.primary,
+ onPressed: () => _showSearchSheet(),
+ child: Icon(Icons.add_rounded, color: cs.onPrimary),
+ ),
+ body: SafeArea(child: Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ const Expanded(child: AbsorbPageHeader(title: 'Podcasts', padding: EdgeInsets.zero)),
+ _checkingEpisodes
+ ? const Padding(padding: EdgeInsets.all(12),
+ child: SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white38)))
+ : IconButton(
+ icon: const Icon(Icons.refresh_rounded, color: Colors.white38, size: 22),
+ tooltip: 'Check for new episodes',
+ onPressed: _checkNewEpisodes),
+ IconButton(icon: const Icon(Icons.close_rounded, color: Colors.white38), onPressed: () => Navigator.pop(context)),
+ ]),
+ ),
+ const SizedBox(height: 12),
+ Expanded(
+ child: _loading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : RefreshIndicator(onRefresh: _loadShows, child: _buildShowList(cs, tt)),
+ ),
+ ])),
+ );
+ }
+
+ // ─── Show List ──────────────────────────────────────────────
+
+ Widget _buildShowList(ColorScheme cs, TextTheme tt) {
+ if (_shows.isEmpty) {
+ return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.podcasts_rounded, size: 48, color: Colors.white.withValues(alpha: 0.1)),
+ const SizedBox(height: 12),
+ Text('No podcasts yet', style: tt.bodyMedium?.copyWith(color: Colors.white.withValues(alpha: 0.3))),
+ const SizedBox(height: 4),
+ Text('Tap + to search and add shows', style: tt.bodySmall?.copyWith(color: Colors.white.withValues(alpha: 0.2))),
+ ]));
+ }
+
+ return ListView.builder(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 80),
+ itemCount: _shows.length,
+ itemBuilder: (_, i) {
+ final item = _shows[i] as Map<String, dynamic>;
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['author'] as String? ?? '';
+ final numEps = media['numEpisodes'] as int?
+ ?? (media['episodes'] as List?)?.length
+ ?? item['numEpisodes'] as int?
+ ?? 0;
+ final itemId = item['id'] as String? ?? '';
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: GestureDetector(
+ onTap: () => _openShowDetail(item),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(14)),
+ child: Row(children: [
+ ClipRRect(borderRadius: BorderRadius.circular(10), child: _coverImg(cs, itemId)),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
+ if (author.isNotEmpty) ...[const SizedBox(height: 2),
+ Text(author, style: tt.bodySmall?.copyWith(color: Colors.white38), maxLines: 1, overflow: TextOverflow.ellipsis)],
+ const SizedBox(height: 4),
+ Text('$numEps episodes', style: tt.labelSmall?.copyWith(color: cs.primary.withValues(alpha: 0.7), fontSize: 11)),
+ ])),
+ Icon(Icons.chevron_right_rounded, color: Colors.white.withValues(alpha: 0.15)),
+ ]),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _coverImg(ColorScheme cs, String itemId) {
+ final auth = context.read<AuthProvider>();
+ final url = '${auth.serverUrl}/api/items/$itemId/cover?token=${auth.token}';
+ return Image.network(url, width: 56, height: 56, fit: BoxFit.cover,
+ headers: auth.apiService?.mediaHeaders ?? {},
+ errorBuilder: (_, __, ___) => _coverPlaceholder(cs));
+ }
+
+ Widget _coverPlaceholder(ColorScheme cs) => Container(width: 56, height: 56,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(10)),
+ child: Icon(Icons.podcasts_rounded, color: cs.primary.withValues(alpha: 0.4)));
+
+ // ─── Search Sheet ───────────────────────────────────────────
+
+ void _showSearchSheet() {
+ showModalBottomSheet(
+ context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,
+ builder: (_) => _PodcastSearchSheet(libraryId: _libraryId, folderId: _folderId, onAdded: _loadShows));
+ }
+
+ // ─── Show Detail ────────────────────────────────────────────
+
+ void _openShowDetail(Map<String, dynamic> item) {
+ Navigator.push(context, MaterialPageRoute(
+ builder: (_) => _PodcastDetailScreen(item: item, libraryId: _libraryId, onChanged: _loadShows)));
+ }
+
+ void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+}
+
+
+// ═══════════════════════════════════════════════════════════════
+// Search & Add Podcast Sheet
+// ═══════════════════════════════════════════════════════════════
+
+class _PodcastSearchSheet extends StatefulWidget {
+ final String libraryId;
+ final String folderId;
+ final VoidCallback onAdded;
+ const _PodcastSearchSheet({required this.libraryId, required this.folderId, required this.onAdded});
+ @override State<_PodcastSearchSheet> createState() => _PodcastSearchSheetState();
+}
+
+class _PodcastSearchSheetState extends State<_PodcastSearchSheet> {
+ final _ctrl = TextEditingController();
+ bool _searching = false;
+ List<dynamic> _results = [];
+
+ @override
+ void dispose() { _ctrl.dispose(); super.dispose(); }
+
+ Future<void> _search() async {
+ final q = _ctrl.text.trim(); if (q.isEmpty) return;
+ FocusScope.of(context).unfocus();
+ setState(() => _searching = true);
+ final api = context.read<AuthProvider>().apiService;
+ if (api != null) _results = await api.searchPodcasts(q);
+ if (mounted) setState(() => _searching = false);
+ }
+
+ /// Extract the podcast map from a search result item
+ Map<String, dynamic> _extractPod(dynamic item) {
+ if (item is Map<String, dynamic>) {
+ if (item.containsKey('podcast')) return item['podcast'] as Map<String, dynamic>;
+ return item;
+ }
+ return {};
+ }
+
+ String _getImageUrl(Map<String, dynamic> pod) {
+ return pod['cover'] as String?
+ ?? pod['imageUrl'] as String?
+ ?? pod['artworkUrl600'] as String?
+ ?? pod['artworkUrl100'] as String?
+ ?? '';
+ }
+
+ void _openPreview(Map<String, dynamic> pod) {
+ Navigator.pop(context); // close search sheet
+ Navigator.push(
+ context,
+ MaterialPageRoute(
+ builder: (_) => _PodcastPreviewScreen(
+ podcast: pod,
+ libraryId: widget.libraryId,
+ folderId: widget.folderId,
+ onAdded: widget.onAdded,
+ ),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Container(
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHigh,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
+ ),
+ child: DraggableScrollableSheet(
+ initialChildSize: 0.85,
+ minChildSize: 0.5,
+ maxChildSize: 0.95,
+ expand: false,
+ builder: (ctx, sc) {
+ return Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 14, 8, 0),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text('Add Podcast', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: Colors.white)),
+ ),
+ IconButton(
+ icon: const Icon(Icons.close_rounded, color: Colors.white38, size: 20),
+ onPressed: () => Navigator.pop(context),
+ ),
+ ],
+ ),
+ ),
+ _buildSearchBar(cs, tt),
+ const Divider(height: 1, color: Colors.white10),
+ Expanded(
+ child: _searching
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : _results.isEmpty
+ ? Center(child: Text('Search iTunes to find podcasts', style: tt.bodySmall?.copyWith(color: Colors.white24)))
+ : _buildResultsList(cs, tt, sc),
+ ),
+ ],
+ );
+ },
+ ),
+ );
+ }
+
+ Widget _buildSearchBar(ColorScheme cs, TextTheme tt) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
+ child: TextField(
+ controller: _ctrl,
+ autofocus: true,
+ style: const TextStyle(color: Colors.white),
+ onSubmitted: (_) => _search(),
+ decoration: InputDecoration(
+ hintText: 'Search for podcasts…',
+ hintStyle: TextStyle(color: Colors.white.withValues(alpha: 0.25)),
+ prefixIcon: Icon(Icons.search_rounded, color: Colors.white.withValues(alpha: 0.3)),
+ suffixIcon: _searching
+ ? const Padding(
+ padding: EdgeInsets.all(12),
+ child: SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white38)),
+ )
+ : IconButton(icon: Icon(Icons.arrow_forward_rounded, color: cs.primary), onPressed: _search),
+ filled: true,
+ fillColor: Colors.white.withValues(alpha: 0.05),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildResultsList(ColorScheme cs, TextTheme tt, ScrollController sc) {
+ return ListView.builder(
+ controller: sc,
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
+ itemCount: _results.length,
+ itemBuilder: (_, i) {
+ final pod = _extractPod(_results[i]);
+ final title = pod['title'] as String? ?? pod['trackName'] as String? ?? pod['collectionName'] as String? ?? 'Unknown';
+ final author = pod['artistName'] as String? ?? pod['author'] as String? ?? '';
+ final imageUrl = _getImageUrl(pod);
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: GestureDetector(
+ onTap: () => _openPreview(pod),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Row(
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: imageUrl.isNotEmpty
+ ? Image.network(
+ imageUrl,
+ width: 50,
+ height: 50,
+ fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _ph(cs),
+ )
+ : _ph(cs),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
+ if (author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(author, style: tt.bodySmall?.copyWith(color: Colors.white38), maxLines: 1, overflow: TextOverflow.ellipsis),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ Icon(Icons.chevron_right_rounded, color: Colors.white.withValues(alpha: 0.15)),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _ph(ColorScheme cs) => Container(
+ width: 50, height: 50,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(10)),
+ child: Icon(Icons.podcasts_rounded, color: cs.primary.withValues(alpha: 0.4), size: 22),
+ );
+
+ void _snk(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+}
+
+
+// ═══════════════════════════════════════════════════════════════
+// Podcast Preview / Confirmation Screen
+// ═══════════════════════════════════════════════════════════════
+
+class _PodcastPreviewScreen extends StatefulWidget {
+ final Map<String, dynamic> podcast;
+ final String libraryId;
+ final String folderId;
+ final VoidCallback onAdded;
+ const _PodcastPreviewScreen({
+ required this.podcast,
+ required this.libraryId,
+ required this.folderId,
+ required this.onAdded,
+ });
+ @override State<_PodcastPreviewScreen> createState() => _PodcastPreviewScreenState();
+}
+
+class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {
+ bool _loadingFeed = false;
+ bool _adding = false;
+ Map<String, dynamic>? _feedData;
+ List<dynamic> _feedEpisodes = [];
+
+ Map<String, dynamic> get _pod => widget.podcast;
+ String get _title => _pod['title'] as String? ?? _pod['trackName'] as String? ?? _pod['collectionName'] as String? ?? 'Podcast';
+ String get _author => _pod['artistName'] as String? ?? _pod['author'] as String? ?? '';
+ String get _feedUrl => _pod['feedUrl'] as String? ?? '';
+ String get _imageUrl =>
+ _pod['cover'] as String? ??
+ _pod['imageUrl'] as String? ??
+ _pod['artworkUrl600'] as String? ?? '';
+ String get _description => _feedData?['metadata']?['description'] as String? ??
+ _pod['description'] as String? ?? '';
+ List<dynamic> get _genres => _pod['genres'] as List? ?? [];
+
+ @override
+ void initState() {
+ super.initState();
+ if (_feedUrl.isNotEmpty) _loadFeed();
+ }
+
+ Future<void> _loadFeed() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ setState(() => _loadingFeed = true);
+ final result = await api.getPodcastFeed(_feedUrl);
+ if (result != null && mounted) {
+ setState(() {
+ _feedData = result['podcast'] as Map<String, dynamic>? ?? result;
+ _feedEpisodes = _feedData?['episodes'] as List? ?? [];
+ _loadingFeed = false;
+ });
+ } else if (mounted) {
+ setState(() => _loadingFeed = false);
+ }
+ }
+
+ Future<void> _addPodcast() async {
+ if (_feedUrl.isEmpty) { _msg('No feed URL found'); return; }
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ setState(() => _adding = true);
+ final result = await api.createPodcast(
+ libraryId: widget.libraryId,
+ folderId: widget.folderId,
+ feedUrl: _feedUrl,
+ podcastData: _pod,
+ );
+ if (mounted) {
+ setState(() => _adding = false);
+ if (result != null) {
+ widget.onAdded();
+ Navigator.pop(context);
+ _msg('$_title added to library');
+ } else {
+ _msg('Failed to add $_title');
+ }
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ body: SafeArea(
+ child: Column(
+ children: [
+ // Header
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 4, 8, 0),
+ child: Row(
+ children: [
+ IconButton(icon: const Icon(Icons.arrow_back_rounded, color: Colors.white54), onPressed: () => Navigator.pop(context)),
+ const Spacer(),
+ ],
+ ),
+ ),
+
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 100),
+ children: [
+ // Cover + title
+ Center(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: _imageUrl.isNotEmpty
+ ? Image.network(_imageUrl, width: 160, height: 160, fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _coverPlaceholder(cs))
+ : _coverPlaceholder(cs),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ _title,
+ style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w700, color: Colors.white),
+ textAlign: TextAlign.center,
+ ),
+ if (_author.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(_author, style: tt.bodyMedium?.copyWith(color: Colors.white38), textAlign: TextAlign.center),
+ ],
+ const SizedBox(height: 12),
+
+ // Genres
+ if (_genres.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Wrap(
+ alignment: WrapAlignment.center,
+ spacing: 6,
+ runSpacing: 4,
+ children: _genres.map((g) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.1),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Text(g.toString(), style: tt.labelSmall?.copyWith(color: cs.primary, fontSize: 11)),
+ )).toList(),
+ ),
+ ),
+
+ // Feed info
+ if (_feedUrl.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.rss_feed_rounded, size: 14, color: Colors.white.withValues(alpha: 0.25)),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ _feedUrl,
+ style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.25), fontSize: 10),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ ),
+ ),
+
+ // Description
+ if (_description.isNotEmpty) ...[
+ Text(
+ _description,
+ style: tt.bodySmall?.copyWith(color: Colors.white.withValues(alpha: 0.5), height: 1.5),
+ maxLines: 6,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 16),
+ ],
+
+ // Episode preview
+ if (_loadingFeed)
+ const Padding(
+ padding: EdgeInsets.symmetric(vertical: 20),
+ child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ )
+ else if (_feedEpisodes.isNotEmpty) ...[
+ Text(
+ '${_feedEpisodes.length} episodes in feed',
+ style: tt.labelMedium?.copyWith(color: Colors.white38, fontWeight: FontWeight.w600),
+ ),
+ const SizedBox(height: 8),
+ // Show first 5 episodes as preview
+ ...(_feedEpisodes.take(5).map((ep) {
+ final epMap = ep as Map<String, dynamic>;
+ final epTitle = epMap['title'] as String? ?? 'Episode';
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(
+ epTitle,
+ style: tt.bodySmall?.copyWith(color: Colors.white54),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ );
+ })),
+ if (_feedEpisodes.length > 5)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text(
+ '+ ${_feedEpisodes.length - 5} more episodes',
+ style: tt.labelSmall?.copyWith(color: Colors.white24),
+ textAlign: TextAlign.center,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+
+ // Add button
+ Padding(
+ padding: EdgeInsets.fromLTRB(20, 8, 20, MediaQuery.of(context).padding.bottom + 12),
+ child: SizedBox(
+ width: double.infinity,
+ height: 48,
+ child: FilledButton.icon(
+ onPressed: _adding ? null : _addPodcast,
+ icon: _adding
+ ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
+ : const Icon(Icons.add_rounded),
+ label: Text(_adding ? 'Adding…' : 'Add to Library', style: const TextStyle(fontWeight: FontWeight.w700)),
+ style: FilledButton.styleFrom(
+ backgroundColor: cs.primary,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _coverPlaceholder(ColorScheme cs) => Container(
+ width: 160, height: 160,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(16)),
+ child: Icon(Icons.podcasts_rounded, color: cs.primary.withValues(alpha: 0.3), size: 48),
+ );
+
+ void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+}
+
+
+// ═══════════════════════════════════════════════════════════════
+// Podcast Detail — Episodes per show
+// ═══════════════════════════════════════════════════════════════
+
+class _PodcastDetailScreen extends StatefulWidget {
+ final Map<String, dynamic> item;
+ final String libraryId;
+ final VoidCallback onChanged;
+ const _PodcastDetailScreen({required this.item, required this.libraryId, required this.onChanged});
+ @override State<_PodcastDetailScreen> createState() => _PodcastDetailScreenState();
+}
+
+class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTickerProviderStateMixin {
+ late Map<String, dynamic> _item;
+ bool _loadingFeed = false;
+ List<dynamic> _feedEpisodes = [];
+ final Set<String> _downloading = {};
+ final Set<String> _deleting = {};
+ late TabController _tabCtrl;
+
+ // Download queue
+ Map<String, dynamic>? _currentDownload;
+ List<dynamic> _downloadQueue = [];
+ bool _pollingQueue = false;
+
+ String get _podcastId => _item['id'] as String? ?? '';
+ Map<String, dynamic> get _media => _item['media'] as Map<String, dynamic>? ?? {};
+ Map<String, dynamic> get _metadata => _media['metadata'] as Map<String, dynamic>? ?? {};
+ List<dynamic> get _episodes => _media['episodes'] as List? ?? [];
+ String get _title => _metadata['title'] as String? ?? 'Podcast';
+ String get _feedUrl => _metadata['feedUrl'] as String? ?? _media['feedUrl'] as String? ?? '';
+
+ @override
+ void initState() {
+ super.initState();
+ _item = Map<String, dynamic>.from(widget.item);
+ _tabCtrl = TabController(length: 2, vsync: this);
+ _reloadItem(); // Load full item with episodes
+ _loadFeed(); // Pre-load feed so it's ready when user switches tabs
+ _pollDownloadQueue(); // Check for any in-progress downloads
+ }
+
+ @override
+ void dispose() { _pollingQueue = false; _tabCtrl.dispose(); super.dispose(); }
+
+ Future<void> _reloadItem() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ try {
+ final found = await api.getLibraryItem(_podcastId);
+ if (found != null && mounted) setState(() => _item = Map<String, dynamic>.from(found));
+ } catch (_) {}
+ }
+
+ Future<void> _loadFeed() async {
+ if (_feedUrl.isEmpty) { _msg('No feed URL available'); return; }
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _loadingFeed = true);
+ final result = await api.getPodcastFeed(_feedUrl);
+ if (result != null) {
+ final podcast = result['podcast'] as Map<String, dynamic>? ?? result;
+ _feedEpisodes = podcast['episodes'] as List? ?? [];
+ }
+ if (mounted) setState(() => _loadingFeed = false);
+ }
+
+ Future<void> _pollDownloadQueue() async {
+ if (_pollingQueue) return;
+ _pollingQueue = true;
+ final api = context.read<AuthProvider>().apiService;
+ while (_pollingQueue && mounted && api != null) {
+ final data = await api.getEpisodeDownloads(widget.libraryId);
+ if (!mounted) break;
+ final current = data?['currentDownload'] as Map<String, dynamic>?;
+ final queue = data?['queue'] as List? ?? [];
+ // Filter to this podcast only
+ final myId = _podcastId;
+ final myCurrent = (current != null && current['libraryItemId'] == myId) ? current : null;
+ final myQueue = queue.where((q) => (q as Map?)?['libraryItemId'] == myId).toList();
+
+ setState(() {
+ _currentDownload = myCurrent;
+ _downloadQueue = myQueue;
+ });
+
+ // If nothing left downloading, refresh episodes and stop polling
+ if (myCurrent == null && myQueue.isEmpty) {
+ _pollingQueue = false;
+ _reloadItem();
+ break;
+ }
+ await Future.delayed(const Duration(seconds: 3));
+ }
+ _pollingQueue = false;
+ }
+
+ Future<void> _downloadEpisode(Map<String, dynamic> feedEp) async {
+ final epTitle = feedEp['title'] as String? ?? '';
+ final epKey = feedEp['enclosureUrl'] as String? ?? feedEp['title'] as String? ?? '';
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _downloading.add(epKey));
+ final ok = await api.downloadPodcastEpisodes(_podcastId, [feedEp]);
+ if (mounted) {
+ setState(() => _downloading.remove(epKey));
+ _msg(ok ? 'Downloading "$epTitle"' : 'Failed to download');
+ if (ok) _pollDownloadQueue();
+ }
+ widget.onChanged();
+ }
+
+ Future<void> _deleteEpisode(String episodeId, String epTitle) async {
+ final yes = await showDialog<bool>(context: context, builder: (ctx) => AlertDialog(
+ backgroundColor: const Color(0xFF2A2A2A),
+ title: const Text('Delete Episode?', style: TextStyle(color: Colors.white)),
+ content: Text('Delete "$epTitle"?', style: const TextStyle(color: Colors.white70)),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text('Delete', style: TextStyle(color: Colors.red.shade300)))],
+ ));
+ if (yes != true) return;
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _deleting.add(episodeId));
+ final ok = await api.deletePodcastEpisode(_podcastId, episodeId);
+ if (mounted) { setState(() => _deleting.remove(episodeId)); _msg(ok ? 'Deleted' : 'Failed');
+ if (ok) { _reloadItem(); widget.onChanged(); } }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final auth = context.read<AuthProvider>();
+ final coverUrl = '${auth.serverUrl}/api/items/$_podcastId/cover?token=${auth.token}';
+ final author = _metadata['author'] as String? ?? '';
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ body: SafeArea(child: Column(children: [
+ // Back button
+ Padding(padding: const EdgeInsets.fromLTRB(4, 4, 8, 0),
+ child: Row(children: [
+ IconButton(icon: const Icon(Icons.arrow_back_rounded, color: Colors.white54), onPressed: () => Navigator.pop(context)),
+ const Spacer(),
+ ])),
+
+ // Show info
+ Padding(padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ ClipRRect(borderRadius: BorderRadius.circular(12),
+ child: Image.network(coverUrl, width: 72, height: 72, fit: BoxFit.cover,
+ headers: auth.apiService?.mediaHeaders ?? {},
+ errorBuilder: (_, __, ___) => Container(width: 72, height: 72,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(12)),
+ child: Icon(Icons.podcasts_rounded, color: cs.primary.withValues(alpha: 0.4), size: 28)))),
+ const SizedBox(width: 14),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(_title, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
+ if (author.isNotEmpty) ...[const SizedBox(height: 2),
+ Text(author, style: tt.bodySmall?.copyWith(color: Colors.white38))],
+ const SizedBox(height: 6),
+ Text('${_episodes.length} downloaded', style: tt.labelSmall?.copyWith(color: cs.primary.withValues(alpha: 0.7), fontSize: 11)),
+ ])),
+ ])),
+
+ // Tabs
+ TabBar(
+ controller: _tabCtrl,
+ labelColor: cs.primary,
+ unselectedLabelColor: Colors.white.withValues(alpha: 0.3),
+ indicatorColor: cs.primary,
+ indicatorSize: TabBarIndicatorSize.label,
+ dividerColor: Colors.white.withValues(alpha: 0.06),
+ tabs: const [Tab(text: 'Downloaded'), Tab(text: 'Feed')],
+ onTap: (i) { if (i == 1 && _feedEpisodes.isEmpty && !_loadingFeed) _loadFeed(); },
+ ),
+
+ // Tab views
+ Expanded(child: TabBarView(controller: _tabCtrl, children: [
+ _buildDownloadedTab(cs, tt),
+ _buildFeedTab(cs, tt),
+ ])),
+ ])),
+ );
+ }
+
+ // ─── Downloaded Tab ─────────────────────────────────────────
+
+ Widget _buildDownloadedTab(ColorScheme cs, TextTheme tt) {
+ // Build list: active downloads first, then downloaded episodes
+ final queueItems = <Map<String, dynamic>>[];
+ if (_currentDownload != null) queueItems.add(_currentDownload!);
+ for (final q in _downloadQueue) {
+ if (q is Map<String, dynamic>) queueItems.add(q);
+ }
+
+ if (_episodes.isEmpty && queueItems.isEmpty) {
+ return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.download_done_rounded, size: 40, color: Colors.white.withValues(alpha: 0.1)),
+ const SizedBox(height: 8),
+ Text('No downloaded episodes', style: tt.bodyMedium?.copyWith(color: Colors.white.withValues(alpha: 0.3))),
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: () { _tabCtrl.animateTo(1); if (_feedEpisodes.isEmpty && !_loadingFeed) _loadFeed(); },
+ child: Text('Browse feed to download', style: tt.bodySmall?.copyWith(color: cs.primary))),
+ ]));
+ }
+
+ final sorted = List.from(_episodes)..sort((a, b) {
+ final aT = a['publishedAt'] as num? ?? 0; final bT = b['publishedAt'] as num? ?? 0;
+ return bT.compareTo(aT);
+ });
+
+ return RefreshIndicator(
+ onRefresh: _reloadItem,
+ child: ListView.builder(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 80),
+ itemCount: queueItems.length + sorted.length,
+ itemBuilder: (_, i) {
+ // Queue items first
+ if (i < queueItems.length) {
+ final q = queueItems[i];
+ final isActive = i == 0 && _currentDownload != null;
+ final title = q['episodeDisplayTitle'] as String? ?? 'Downloading...';
+ return Padding(padding: const EdgeInsets.only(bottom: 6), child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),
+ ),
+ child: Row(children: [
+ SizedBox(width: 18, height: 18, child: isActive
+ ? CircularProgressIndicator(strokeWidth: 1.5, color: cs.primary)
+ : Icon(Icons.hourglass_top_rounded, size: 16, color: cs.primary.withValues(alpha: 0.5))),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: tt.bodySmall?.copyWith(fontWeight: FontWeight.w600, color: Colors.white),
+ maxLines: 2, overflow: TextOverflow.ellipsis),
+ const SizedBox(height: 2),
+ Text(isActive ? 'Downloading...' : 'Queued',
+ style: tt.labelSmall?.copyWith(color: cs.primary.withValues(alpha: 0.7), fontSize: 10)),
+ ])),
+ ]),
+ ));
+ }
+
+ // Downloaded episodes
+ final idx = i - queueItems.length;
+ final ep = sorted[idx] as Map<String, dynamic>;
+ final epTitle = ep['title']?.toString() ?? 'Episode';
+ final pubAt = ep['publishedAt'] as num?;
+ final duration = ep['duration'];
+ final durStr = duration is num ? _fmtDur(duration.toDouble())
+ : (duration is String ? _fmtDurFromStr(duration) : '');
+
+ return Padding(padding: const EdgeInsets.only(bottom: 6), child: GestureDetector(
+ onTap: () => _showDownloadedEpisodeDetail(ep),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)),
+ child: Row(children: [
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(epTitle, style: tt.bodySmall?.copyWith(fontWeight: FontWeight.w600, color: Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
+ const SizedBox(height: 3),
+ Row(children: [
+ if (pubAt != null) Text(_fmtDate(pubAt.toInt()), style: tt.labelSmall?.copyWith(color: Colors.white24, fontSize: 10)),
+ if (pubAt != null && durStr.isNotEmpty) Text(' · ', style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.15))),
+ if (durStr.isNotEmpty) Text(durStr, style: tt.labelSmall?.copyWith(color: Colors.white24, fontSize: 10)),
+ ]),
+ ])),
+ const SizedBox(width: 8),
+ Icon(Icons.chevron_right_rounded, size: 18, color: Colors.white.withValues(alpha: 0.15)),
+ ]),
+ ),
+ ));
+ },
+ ),
+ );
+ }
+
+ // ─── Feed Tab ───────────────────────────────────────────────
+
+ Widget _buildFeedTab(ColorScheme cs, TextTheme tt) {
+ if (_loadingFeed) return const Center(child: CircularProgressIndicator(strokeWidth: 2));
+ if (_feedUrl.isEmpty) return Center(child: Text('No feed URL available', style: tt.bodyMedium?.copyWith(color: Colors.white.withValues(alpha: 0.3))));
+ if (_feedEpisodes.isEmpty) {
+ return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Text('No episodes found', style: tt.bodyMedium?.copyWith(color: Colors.white.withValues(alpha: 0.3))),
+ const SizedBox(height: 8),
+ GestureDetector(onTap: _loadFeed,
+ child: Text('Retry', style: tt.bodySmall?.copyWith(color: cs.primary))),
+ ]));
+ }
+
+ final dlTitles = _episodes.map((e) => (e['title'] as String? ?? '').toLowerCase()).toSet();
+
+ return RefreshIndicator(
+ onRefresh: _loadFeed,
+ child: ListView.builder(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 80),
+ itemCount: _feedEpisodes.length,
+ itemBuilder: (_, i) {
+ final ep = _feedEpisodes[i] as Map<String, dynamic>;
+ final epTitle = ep['title'] as String? ?? 'Episode';
+ final pubDate = ep['publishedAt'] as num? ?? ep['pubDate'] as num?;
+ final already = dlTitles.contains(epTitle.toLowerCase());
+
+ return Padding(padding: const EdgeInsets.only(bottom: 6), child: GestureDetector(
+ onTap: () => _showEpisodeDetail(ep, already),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)),
+ child: Row(children: [
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(epTitle, style: tt.bodySmall?.copyWith(fontWeight: FontWeight.w600,
+ color: already ? Colors.white38 : Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
+ if (pubDate != null) ...[const SizedBox(height: 3),
+ Text(_fmtDate(pubDate.toInt()), style: tt.labelSmall?.copyWith(color: Colors.white24, fontSize: 10))],
+ ])),
+ const SizedBox(width: 8),
+ if (already) Icon(Icons.check_circle_rounded, size: 18, color: Colors.green.withValues(alpha: 0.5))
+ else Icon(Icons.chevron_right_rounded, size: 18, color: Colors.white.withValues(alpha: 0.15)),
+ ]),
+ ),
+ ));
+ },
+ ),
+ );
+ }
+
+ void _showEpisodeDetail(Map<String, dynamic> ep, bool alreadyDownloaded) {
+ final isRoot = context.read<AuthProvider>().isRoot;
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => _EpisodeDetailSheet(
+ episode: ep,
+ alreadyDownloaded: alreadyDownloaded,
+ canDownload: isRoot,
+ onDownload: () {
+ Navigator.pop(context);
+ _downloadEpisode(ep);
+ },
+ ),
+ );
+ }
+
+ void _showDownloadedEpisodeDetail(Map<String, dynamic> ep) {
+ final epId = ep['id']?.toString() ?? '';
+ final epTitle = ep['title']?.toString() ?? 'Episode';
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => _DownloadedEpisodeDetailSheet(
+ episode: ep,
+ isDeleting: _deleting.contains(epId),
+ onDelete: () {
+ Navigator.pop(context);
+ _deleteEpisode(epId, epTitle);
+ },
+ ),
+ );
+ }
+
+ // ─── Helpers ────────────────────────────────────────────────
+
+ String _fmtDate(int ms) {
+ final dt = DateTime.fromMillisecondsSinceEpoch(ms);
+ const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
+ return '${m[dt.month - 1]} ${dt.day}, ${dt.year}';
+ }
+
+ String _fmtDur(double s) { final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();
+ return h > 0 ? '${h}h ${m}m' : '${m}m'; }
+
+ String _fmtDurFromStr(String s) {
+ if (s.contains(':')) return s;
+ final secs = double.tryParse(s) ?? 0;
+ if (secs <= 0) return '';
+ return _fmtDur(secs);
+ }
+
+ void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+}
+
+
+// ═══════════════════════════════════════════════════════════════
+// Episode Detail Sheet
+// ═══════════════════════════════════════════════════════════════
+
+class _EpisodeDetailSheet extends StatelessWidget {
+ final Map<String, dynamic> episode;
+ final bool alreadyDownloaded;
+ final bool canDownload;
+ final VoidCallback onDownload;
+ const _EpisodeDetailSheet({required this.episode, required this.alreadyDownloaded, this.canDownload = true, required this.onDownload});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final title = episode['title']?.toString() ?? 'Episode';
+ final description = _cleanHtml(episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '');
+ final pubDateRaw = episode['publishedAt'] ?? episode['pubDate'];
+ final pubDate = pubDateRaw is num ? pubDateRaw : (num.tryParse(pubDateRaw?.toString() ?? ''));
+ final duration = episode['duration']?.toString() ?? '';
+ final season = episode['season']?.toString() ?? '';
+ final episodeNum = episode['episode']?.toString() ?? '';
+ final episodeType = episode['episodeType']?.toString() ?? '';
+
+ // Size from enclosure
+ final enclosure = episode['enclosure'] is Map ? episode['enclosure'] as Map<String, dynamic> : null;
+ final sizeRaw = enclosure?['length'];
+ final sizeBytes = sizeRaw is num ? sizeRaw.toInt() : (int.tryParse(sizeRaw?.toString() ?? '') ?? 0);
+ final sizeStr = _fmtSize(sizeBytes);
+ final fileType = enclosure?['type']?.toString() ?? '';
+
+ // Build info chips
+ final chips = <String>[];
+ if (pubDate != null) chips.add(_fmtDate(pubDate.toInt()));
+ if (duration.isNotEmpty) chips.add(duration.contains(':') ? duration : _fmtDurStr(duration));
+ if (sizeStr.isNotEmpty) chips.add(sizeStr);
+ if (season.isNotEmpty) chips.add('Season $season');
+ if (episodeNum.isNotEmpty) chips.add('Ep. $episodeNum');
+ if (episodeType.isNotEmpty && episodeType != 'full') chips.add(episodeType);
+
+ return Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
+ decoration: const BoxDecoration(color: Color(0xFF1A1A1A), borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ // Handle
+ Center(child: Container(margin: const EdgeInsets.only(top: 12), width: 36, height: 4,
+ decoration: BoxDecoration(color: Colors.white12, borderRadius: BorderRadius.circular(2)))),
+
+ // Title
+ Padding(padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
+ child: Align(alignment: Alignment.centerLeft,
+ child: Text(title, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white),
+ maxLines: 3, overflow: TextOverflow.ellipsis))),
+
+ // Info chips
+ if (chips.isNotEmpty)
+ Padding(padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
+ child: Align(alignment: Alignment.centerLeft,
+ child: Wrap(spacing: 8, runSpacing: 6, children: chips.map((c) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(6)),
+ child: Text(c, style: tt.labelSmall?.copyWith(color: Colors.white54, fontSize: 11)),
+ )).toList()))),
+
+ // File type
+ if (fileType.isNotEmpty)
+ Padding(padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
+ child: Align(alignment: Alignment.centerLeft,
+ child: Text(fileType, style: tt.labelSmall?.copyWith(color: Colors.white24, fontSize: 10)))),
+
+ // Description
+ if (description.isNotEmpty)
+ Flexible(
+ child: Padding(padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
+ child: SingleChildScrollView(
+ child: SizedBox(width: double.infinity,
+ child: Text(description, style: tt.bodySmall?.copyWith(color: Colors.white54, height: 1.5))),
+ )),
+ ),
+
+ // Buttons
+ Padding(padding: EdgeInsets.fromLTRB(20, 16, 20, MediaQuery.of(context).padding.bottom + 16),
+ child: Row(children: [
+ Expanded(
+ child: OutlinedButton(
+ onPressed: () => Navigator.pop(context),
+ style: OutlinedButton.styleFrom(
+ side: BorderSide(color: Colors.white.withValues(alpha: 0.1)),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ ),
+ child: const Text('Back', style: TextStyle(color: Colors.white54, fontWeight: FontWeight.w600)),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(flex: 2,
+ child: FilledButton.icon(
+ onPressed: (alreadyDownloaded || !canDownload) ? null : onDownload,
+ icon: Icon(alreadyDownloaded ? Icons.check_circle_rounded : Icons.download_rounded, size: 18),
+ label: Text(alreadyDownloaded ? 'Downloaded' : !canDownload ? 'Root Only' : 'Download',
+ style: const TextStyle(fontWeight: FontWeight.w700)),
+ style: FilledButton.styleFrom(
+ backgroundColor: alreadyDownloaded ? Colors.green.withValues(alpha: 0.15) : cs.primary,
+ foregroundColor: alreadyDownloaded ? Colors.green : cs.onPrimary,
+ disabledBackgroundColor: alreadyDownloaded ? Colors.green.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.06),
+ disabledForegroundColor: alreadyDownloaded ? Colors.green : Colors.white38,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ ]),
+ );
+ }
+
+ String _cleanHtml(String html) {
+ return html
+ .replaceAll(RegExp(r'<br\s*/?>'), '\n')
+ .replaceAll(RegExp(r'<p\s*>'), '\n')
+ .replaceAll(RegExp(r'</p>'), '')
+ .replaceAll(RegExp(r'<[^>]+>'), '')
+ .replaceAll('&amp;', '&')
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&#39;', "'")
+ .replaceAll('&nbsp;', ' ')
+ .replaceAll(RegExp(r'\n{3,}'), '\n\n')
+ .trim();
+ }
+
+ String _fmtDate(int ms) {
+ final dt = DateTime.fromMillisecondsSinceEpoch(ms);
+ const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
+ return '${m[dt.month - 1]} ${dt.day}, ${dt.year}';
+ }
+
+ String _fmtSize(int bytes) {
+ if (bytes <= 0) return '';
+ if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(0)} KB';
+ if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
+ return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
+ }
+
+ String _fmtDurStr(String s) {
+ final secs = double.tryParse(s) ?? 0;
+ if (secs <= 0) return s;
+ final h = (secs / 3600).floor();
+ final m = ((secs % 3600) / 60).floor();
+ return h > 0 ? '${h}h ${m}m' : '${m}m';
+ }
+}
+
+
+// ═══════════════════════════════════════════════════════════════
+// Downloaded Episode Detail Sheet
+// ═══════════════════════════════════════════════════════════════
+
+class _DownloadedEpisodeDetailSheet extends StatelessWidget {
+ final Map<String, dynamic> episode;
+ final bool isDeleting;
+ final VoidCallback onDelete;
+ const _DownloadedEpisodeDetailSheet({required this.episode, required this.isDeleting, required this.onDelete});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final title = episode['title']?.toString() ?? 'Episode';
+ final description = _cleanHtml(episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '');
+ final pubAt = episode['publishedAt'];
+ final pubDate = pubAt is num ? pubAt : (num.tryParse(pubAt?.toString() ?? ''));
+ final durRaw = episode['duration'];
+ final durStr = durRaw is num ? _fmtDur(durRaw.toDouble())
+ : (durRaw is String && durRaw.isNotEmpty ? (durRaw.contains(':') ? durRaw : _fmtDurStr(durRaw)) : '');
+ final season = episode['season']?.toString() ?? '';
+ final episodeNum = episode['episode']?.toString() ?? '';
+
+ // Size from audioFile if available
+ final audioFile = episode['audioFile'] as Map<String, dynamic>?;
+ final sizeRaw = audioFile?['metadata']?['size'] ?? episode['size'];
+ final sizeBytes = sizeRaw is num ? sizeRaw.toInt() : (int.tryParse(sizeRaw?.toString() ?? '') ?? 0);
+ final sizeStr = _fmtSize(sizeBytes);
+
+ final chips = <String>[];
+ if (pubDate != null) chips.add(_fmtDate(pubDate.toInt()));
+ if (durStr.isNotEmpty) chips.add(durStr);
+ if (sizeStr.isNotEmpty) chips.add(sizeStr);
+ if (season.isNotEmpty) chips.add('Season $season');
+ if (episodeNum.isNotEmpty) chips.add('Ep. $episodeNum');
+
+ return Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
+ decoration: const BoxDecoration(color: Color(0xFF1A1A1A), borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Center(child: Container(margin: const EdgeInsets.only(top: 12), width: 36, height: 4,
+ decoration: BoxDecoration(color: Colors.white12, borderRadius: BorderRadius.circular(2)))),
+
+ Padding(padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
+ child: Align(alignment: Alignment.centerLeft,
+ child: Text(title, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white),
+ maxLines: 3, overflow: TextOverflow.ellipsis))),
+
+ if (chips.isNotEmpty)
+ Padding(padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
+ child: Align(alignment: Alignment.centerLeft,
+ child: Wrap(spacing: 8, runSpacing: 6, children: chips.map((c) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(6)),
+ child: Text(c, style: tt.labelSmall?.copyWith(color: Colors.white54, fontSize: 11)),
+ )).toList()))),
+
+ if (description.isNotEmpty)
+ Flexible(
+ child: Padding(padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
+ child: SingleChildScrollView(
+ child: SizedBox(width: double.infinity,
+ child: Text(description, style: tt.bodySmall?.copyWith(color: Colors.white54, height: 1.5))),
+ )),
+ ),
+
+ Padding(padding: EdgeInsets.fromLTRB(20, 16, 20, MediaQuery.of(context).padding.bottom + 16),
+ child: Row(children: [
+ Expanded(
+ child: OutlinedButton(
+ onPressed: () => Navigator.pop(context),
+ style: OutlinedButton.styleFrom(
+ side: BorderSide(color: Colors.white.withValues(alpha: 0.1)),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ ),
+ child: const Text('Back', style: TextStyle(color: Colors.white54, fontWeight: FontWeight.w600)),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(flex: 2,
+ child: FilledButton.icon(
+ onPressed: isDeleting ? null : onDelete,
+ icon: isDeleting
+ ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white54))
+ : const Icon(Icons.delete_outline_rounded, size: 18),
+ label: Text(isDeleting ? 'Deleting...' : 'Delete Episode',
+ style: const TextStyle(fontWeight: FontWeight.w700)),
+ style: FilledButton.styleFrom(
+ backgroundColor: Colors.red.withValues(alpha: 0.15),
+ foregroundColor: Colors.red.shade300,
+ disabledBackgroundColor: Colors.red.withValues(alpha: 0.08),
+ disabledForegroundColor: Colors.red.withValues(alpha: 0.4),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ ]),
+ );
+ }
+
+ String _cleanHtml(String html) {
+ return html
+ .replaceAll(RegExp(r'<br\s*/?>'), '\n')
+ .replaceAll(RegExp(r'<p\s*>'), '\n')
+ .replaceAll(RegExp(r'</p>'), '')
+ .replaceAll(RegExp(r'<[^>]+>'), '')
+ .replaceAll('&amp;', '&')
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&#39;', "'")
+ .replaceAll('&nbsp;', ' ')
+ .replaceAll(RegExp(r'\n{3,}'), '\n\n')
+ .trim();
+ }
+
+ String _fmtDate(int ms) {
+ final dt = DateTime.fromMillisecondsSinceEpoch(ms);
+ const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
+ return '${m[dt.month - 1]} ${dt.day}, ${dt.year}';
+ }
+
+ String _fmtSize(int bytes) {
+ if (bytes <= 0) return '';
+ if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(0)} KB';
+ if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
+ return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
+ }
+
+ String _fmtDur(double s) { final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();
+ return h > 0 ? '${h}h ${m}m' : '${m}m'; }
+
+ String _fmtDurStr(String s) {
+ if (s.contains(':')) return s;
+ final secs = double.tryParse(s) ?? 0;
+ if (secs <= 0) return s;
+ return _fmtDur(secs);
+ }
+}
diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dart
new file mode 100644
index 00000000..bce2e42a
--- /dev/null
+++ b/lib/screens/admin_screen.dart
@@ -0,0 +1,359 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../services/api_service.dart';
+import '../widgets/absorb_page_header.dart';
+import 'admin_users_screen.dart';
+import 'admin_podcasts_screen.dart';
+
+class AdminScreen extends StatefulWidget {
+ const AdminScreen({super.key});
+ @override State<AdminScreen> createState() => _AdminScreenState();
+}
+
+class _AdminScreenState extends State<AdminScreen> {
+ bool _loading = true;
+ List<dynamic> _users = [];
+ List<dynamic> _onlineUsers = [];
+ List<dynamic> _libraries = [];
+ List<dynamic> _backups = [];
+ List<dynamic> _sessions = [];
+ Map<String, Map<String, dynamic>> _libraryStats = {};
+ String? _serverVersion;
+
+ final Set<String> _scanningLibraries = {};
+ final Set<String> _matchingLibraries = {};
+ bool _creatingBackup = false;
+ bool _purgingCache = false;
+
+ @override
+ void initState() { super.initState(); _loadAll(); }
+
+ Future<void> _loadAll() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ setState(() => _loading = true);
+
+ final futures = await Future.wait([
+ api.getUsers(), api.getOnlineUsers(), api.getLibraries(), api.getBackups(), api.getAllSessions(limit: 10),
+ ]);
+ _users = futures[0] as List<dynamic>;
+ _onlineUsers = futures[1] as List<dynamic>;
+ _libraries = futures[2] as List<dynamic>;
+ _backups = futures[3] as List<dynamic>;
+ _sessions = futures[4] as List<dynamic>;
+ _serverVersion = context.read<AuthProvider>().serverVersion;
+
+ for (final lib in _libraries) {
+ final id = lib['id'] as String? ?? '';
+ if (id.isNotEmpty) {
+ final stats = await api.getLibraryStats(id);
+ if (stats != null) _libraryStats[id] = stats;
+ }
+ }
+ if (mounted) setState(() => _loading = false);
+ }
+
+ bool get _hasPodcastLibrary => _libraries.any((l) => l['mediaType'] == 'podcast');
+
+ List<dynamic> get _activeSessions => _sessions.where((s) {
+ final updatedAt = s['updatedAt'] as num? ?? 0;
+ final now = DateTime.now().millisecondsSinceEpoch;
+ return (now - updatedAt) < 300000;
+ }).toList();
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ body: SafeArea(
+ child: _loading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : RefreshIndicator(
+ onRefresh: _loadAll,
+ child: ListView(
+ padding: const EdgeInsets.only(bottom: 80),
+ children: [
+ // ── Header ──
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ const Expanded(child: AbsorbPageHeader(title: 'Server Admin', padding: EdgeInsets.zero)),
+ IconButton(icon: const Icon(Icons.close_rounded, color: Colors.white38), onPressed: () => Navigator.pop(context)),
+ ]),
+ ),
+ const SizedBox(height: 20),
+
+ // ── Server Overview ──
+ _section(tt, 'Server'),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: _cardDeco(cs),
+ child: Row(children: [
+ _stat(tt, cs, Icons.dns_rounded, _serverVersion ?? '–', 'Version'),
+ _stat(tt, cs, Icons.people_rounded, '${_users.length}', 'Users'),
+ _stat(tt, cs, Icons.wifi_rounded, '${_onlineUsers.length}', 'Online'),
+ _stat(tt, cs, Icons.backup_rounded, '${_backups.length}', 'Backups'),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Expanded(child: _actionBtn(cs, tt, Icons.backup_rounded, 'Backup', _creatingBackup, _createBackup)),
+ const SizedBox(width: 10),
+ Expanded(child: _actionBtn(cs, tt, Icons.cleaning_services_rounded, 'Purge Cache', _purgingCache, _purgeCache)),
+ ]),
+ ),
+ const SizedBox(height: 28),
+
+ // ── Manage Buttons ──
+ _section(tt, 'Manage'),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(children: [
+ _navButton(cs, tt,
+ icon: Icons.people_rounded,
+ label: 'Users',
+ subtitle: '${_users.length} accounts · ${_onlineUsers.length} online',
+ onTap: () async {
+ await Navigator.push(context, MaterialPageRoute(
+ builder: (_) => AdminUsersScreen(users: _users, onlineUsers: _onlineUsers, libraries: _libraries)));
+ _loadAll();
+ },
+ ),
+ const SizedBox(height: 10),
+ if (_hasPodcastLibrary)
+ _navButton(cs, tt,
+ icon: Icons.podcasts_rounded,
+ label: 'Podcasts',
+ subtitle: 'Search, add & manage shows',
+ onTap: () {
+ final podLib = _libraries.firstWhere((l) => l['mediaType'] == 'podcast', orElse: () => null);
+ if (podLib != null) {
+ Navigator.push(context, MaterialPageRoute(
+ builder: (_) => AdminPodcastsScreen(library: podLib)));
+ }
+ },
+ ),
+ ]),
+ ),
+ const SizedBox(height: 28),
+
+ // ── Active Sessions ──
+ if (_activeSessions.isNotEmpty) ...[
+ _section(tt, 'Listening Now'),
+ ..._activeSessions.map((s) => _sessionCard(cs, tt, s)),
+ const SizedBox(height: 18),
+ ],
+
+ // ── Libraries ──
+ _section(tt, 'Libraries'),
+ ..._libraries.map((lib) => _libraryCard(cs, tt, lib)),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ // ─── Shared Widgets ─────────────────────────────────────────
+
+ Widget _section(TextTheme tt, String t) => Padding(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
+ child: Text(t, style: tt.labelLarge?.copyWith(color: Colors.white38, fontWeight: FontWeight.w600, letterSpacing: 0.5)));
+
+ BoxDecoration _cardDeco(ColorScheme cs) => BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16));
+
+ Widget _stat(TextTheme tt, ColorScheme cs, IconData ic, String v, String l) => Expanded(child: Column(children: [
+ Icon(ic, size: 18, color: cs.primary.withValues(alpha: 0.6)), const SizedBox(height: 6),
+ Text(v, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: Colors.white)), const SizedBox(height: 2),
+ Text(l, style: tt.labelSmall?.copyWith(color: Colors.white38, fontSize: 10)),
+ ]));
+
+ Widget _actionBtn(ColorScheme cs, TextTheme tt, IconData ic, String l, bool loading, VoidCallback onTap) =>
+ GestureDetector(onTap: loading ? null : onTap, child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(14)),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ if (loading) const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white38))
+ else Icon(ic, size: 16, color: cs.primary),
+ const SizedBox(width: 8),
+ Text(l, style: tt.labelMedium?.copyWith(color: loading ? Colors.white24 : Colors.white70, fontWeight: FontWeight.w600)),
+ ])));
+
+ Widget _navButton(ColorScheme cs, TextTheme tt, {required IconData icon, required String label, required String subtitle, required VoidCallback onTap}) =>
+ GestureDetector(onTap: onTap, child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ decoration: _cardDeco(cs),
+ child: Row(children: [
+ Icon(icon, color: cs.primary, size: 22), const SizedBox(width: 14),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(label, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ Text(subtitle, style: tt.bodySmall?.copyWith(color: Colors.white38)),
+ ])),
+ Icon(Icons.chevron_right_rounded, color: Colors.white.withValues(alpha: 0.15)),
+ ])));
+
+ // ─── Library Card ───────────────────────────────────────────
+
+ Widget _libraryCard(ColorScheme cs, TextTheme tt, dynamic lib) {
+ final id = lib['id'] as String? ?? '';
+ final name = lib['name'] as String? ?? 'Library';
+ final mediaType = lib['mediaType'] as String? ?? 'book';
+ final folders = (lib['folders'] as List?)?.length ?? 0;
+ final stats = _libraryStats[id];
+ final totalItems = stats?['totalItems'] ?? 0;
+ final totalSize = stats?['totalSize'] as num?;
+ final totalDur = stats?['totalDuration'] as num?;
+ final isScanning = _scanningLibraries.contains(id);
+ final isMatching = _matchingLibraries.contains(id);
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 10),
+ child: Container(padding: const EdgeInsets.all(16), decoration: _cardDeco(cs),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Icon(mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 20, color: cs.primary),
+ const SizedBox(width: 10),
+ Expanded(child: Text(name, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white))),
+ Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(8)),
+ child: Text(mediaType, style: tt.labelSmall?.copyWith(color: cs.primary, fontSize: 10, fontWeight: FontWeight.w600))),
+ ]),
+ const SizedBox(height: 12),
+ Row(children: [
+ _mini(tt, '$totalItems', mediaType == 'podcast' ? 'shows' : 'books'),
+ if (folders > 0) _mini(tt, '$folders', 'folders'),
+ if (totalSize != null) _mini(tt, _fmtB(totalSize.toInt()), 'size'),
+ if (totalDur != null) _mini(tt, _fmtD(totalDur.toDouble()), 'duration'),
+ ]),
+ const SizedBox(height: 12),
+ Row(children: [
+ Expanded(child: _libAct(cs, tt, Icons.search_rounded, isScanning ? 'Scanning…' : 'Scan', isScanning, () => _scanLib(id, name))),
+ const SizedBox(width: 8),
+ Expanded(child: _libAct(cs, tt, Icons.auto_fix_high_rounded, isMatching ? 'Matching…' : 'Match All', isMatching, () => _matchLib(id, name))),
+ ]),
+ ])));
+ }
+
+ Widget _mini(TextTheme tt, String v, String l) => Padding(padding: const EdgeInsets.only(right: 20), child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(v, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w700, color: Colors.white, fontSize: 13)),
+ Text(l, style: tt.labelSmall?.copyWith(color: Colors.white30, fontSize: 10)),
+ ]));
+
+ Widget _libAct(ColorScheme cs, TextTheme tt, IconData ic, String l, bool loading, VoidCallback onTap) =>
+ GestureDetector(onTap: loading ? null : onTap, child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.04), borderRadius: BorderRadius.circular(10),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.06))),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ if (loading) const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 1.5, color: Colors.white38))
+ else Icon(ic, size: 14, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 6),
+ Text(l, style: tt.labelSmall?.copyWith(color: loading ? Colors.white24 : Colors.white54, fontWeight: FontWeight.w600, fontSize: 11)),
+ ])));
+
+ Widget _sessionCard(ColorScheme cs, TextTheme tt, dynamic session) {
+ final displayTitle = session['displayTitle'] as String? ?? 'Unknown';
+ final displayAuthor = session['displayAuthor'] as String? ?? '';
+ final userName = _userNameForSession(session);
+ final currentTime = session['currentTime'] as num? ?? 0;
+ final duration = session['duration'] as num? ?? 0;
+ final updatedAt = session['updatedAt'] as num? ?? 0;
+ final now = DateTime.now().millisecondsSinceEpoch;
+ final isActive = (now - updatedAt) < 300000;
+ final progress = duration > 0 ? (currentTime / duration).clamp(0.0, 1.0) : 0.0;
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Container(padding: const EdgeInsets.all(14), decoration: _cardDeco(cs),
+ child: Row(children: [
+ Container(width: 8, height: 8, decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: isActive ? const Color(0xFF4CAF50) : Colors.white24,
+ )),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(displayTitle, style: tt.bodySmall?.copyWith(color: Colors.white, fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ const SizedBox(height: 2),
+ Text(
+ [if (userName.isNotEmpty) userName, if (displayAuthor.isNotEmpty) displayAuthor].join(' · '),
+ style: tt.labelSmall?.copyWith(color: Colors.white38, fontSize: 10),
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 6),
+ ClipRRect(borderRadius: BorderRadius.circular(2),
+ child: LinearProgressIndicator(value: progress.toDouble(),
+ minHeight: 2, backgroundColor: Colors.white.withValues(alpha: 0.06),
+ valueColor: AlwaysStoppedAnimation(isActive ? cs.primary : Colors.white24))),
+ ])),
+ const SizedBox(width: 12),
+ Text('${_fmtD(currentTime.toDouble())} / ${_fmtD(duration.toDouble())}',
+ style: tt.labelSmall?.copyWith(color: Colors.white24, fontSize: 9)),
+ ])),
+ );
+ }
+
+ String _userNameForSession(dynamic session) {
+ final userId = session['userId'] as String? ?? '';
+ if (userId.isEmpty) return '';
+ final user = _users.cast<Map<String, dynamic>?>().firstWhere(
+ (u) => u?['id'] == userId, orElse: () => null);
+ return user?['username'] as String? ?? '';
+ }
+
+ // ─── Actions ────────────────────────────────────────────────
+
+ Future<void> _scanLib(String id, String name) async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _scanningLibraries.add(id));
+ final ok = await api.scanLibrary(id);
+ if (mounted) { setState(() => _scanningLibraries.remove(id)); _msg(ok ? 'Scan started for $name' : 'Failed to scan $name'); }
+ }
+
+ Future<void> _matchLib(String id, String name) async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ final yes = await showDialog<bool>(context: context, builder: (ctx) => AlertDialog(
+ backgroundColor: const Color(0xFF2A2A2A),
+ title: const Text('Match All Items?', style: TextStyle(color: Colors.white)),
+ content: Text('Match metadata for all items in $name? This can take a while.', style: const TextStyle(color: Colors.white70)),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Match'))],
+ ));
+ if (yes != true) return;
+ setState(() => _matchingLibraries.add(id));
+ final ok = await api.matchLibrary(id);
+ if (mounted) { setState(() => _matchingLibraries.remove(id)); _msg(ok ? 'Matching started for $name' : 'Failed'); }
+ }
+
+ Future<void> _createBackup() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _creatingBackup = true);
+ final ok = await api.createBackup();
+ if (mounted) { setState(() => _creatingBackup = false); _msg(ok ? 'Backup created' : 'Backup failed'); if (ok) _loadAll(); }
+ }
+
+ Future<void> _purgeCache() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _purgingCache = true);
+ final ok = await api.purgeCache();
+ if (mounted) { setState(() => _purgingCache = false); _msg(ok ? 'Cache purged' : 'Failed'); }
+ }
+
+ void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+
+ String _fmtB(int b) { if (b < 1024) return '$b B'; if (b < 1048576) return '${(b / 1024).toStringAsFixed(0)} KB';
+ if (b < 1073741824) return '${(b / 1048576).toStringAsFixed(1)} MB'; return '${(b / 1073741824).toStringAsFixed(1)} GB'; }
+ String _fmtD(double s) { final h = (s / 3600).floor(); if (h > 24) return '${(h / 24).floor()}d ${h % 24}h';
+ final m = ((s % 3600) / 60).floor(); return h > 0 ? '${h}h ${m}m' : '${m}m'; }
+}
diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dart
new file mode 100644
index 00000000..58fbd2be
--- /dev/null
+++ b/lib/screens/admin_users_screen.dart
@@ -0,0 +1,654 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../services/api_service.dart';
+import '../widgets/absorb_page_header.dart';
+
+class AdminUsersScreen extends StatefulWidget {
+ final List<dynamic> users;
+ final List<dynamic> onlineUsers;
+ final List<dynamic> libraries;
+ const AdminUsersScreen({super.key, required this.users, required this.onlineUsers, required this.libraries});
+ @override State<AdminUsersScreen> createState() => _AdminUsersScreenState();
+}
+
+class _AdminUsersScreenState extends State<AdminUsersScreen> {
+ late List<dynamic> _users;
+ late List<dynamic> _onlineUsers;
+
+ @override
+ void initState() { super.initState(); _users = List.from(widget.users); _onlineUsers = List.from(widget.onlineUsers); }
+
+ Future<void> _reload() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ final results = await Future.wait([api.getUsers(), api.getOnlineUsers()]);
+ if (mounted) setState(() { _users = results[0] as List<dynamic>; _onlineUsers = results[1] as List<dynamic>; });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ floatingActionButton: FloatingActionButton.small(
+ backgroundColor: cs.primary,
+ onPressed: () => _showEditor(null),
+ child: Icon(Icons.person_add_rounded, color: cs.onPrimary),
+ ),
+ body: SafeArea(
+ child: Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ const Expanded(child: AbsorbPageHeader(title: 'Users', padding: EdgeInsets.zero)),
+ IconButton(icon: const Icon(Icons.close_rounded, color: Colors.white38), onPressed: () => Navigator.pop(context)),
+ ]),
+ ),
+ const SizedBox(height: 16),
+ Expanded(
+ child: RefreshIndicator(
+ onRefresh: _reload,
+ child: ListView.builder(
+ padding: const EdgeInsets.only(bottom: 80),
+ itemCount: _users.length,
+ itemBuilder: (_, i) => _userTile(cs, tt, _users[i]),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+
+ Widget _userTile(ColorScheme cs, TextTheme tt, dynamic user) {
+ final username = user['username'] as String? ?? 'Unknown';
+ final userId = user['id'] as String? ?? '';
+ final type = user['type'] as String? ?? 'user';
+ final isActive = user['isActive'] as bool? ?? true;
+ final isLocked = user['isLocked'] as bool? ?? false;
+ final isOnline = _onlineUsers.any((o) {
+ if (o is! Map) return false;
+ final oId = o['id'] as String? ?? '';
+ if (oId.isNotEmpty && oId == userId) return true;
+ final oName = o['username'] as String? ?? '';
+ return oName.isNotEmpty && oName == username;
+ });
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: GestureDetector(
+ onTap: () => _showUserDetail(user as Map<String, dynamic>),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16)),
+ child: Row(children: [
+ if (isOnline) ...[
+ Container(width: 8, height: 8, decoration: const BoxDecoration(shape: BoxShape.circle, color: Color(0xFF4CAF50))),
+ const SizedBox(width: 10),
+ ],
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Flexible(child: Text(username, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white), overflow: TextOverflow.ellipsis)),
+ const SizedBox(width: 6),
+ if (type == 'root') Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
+ decoration: BoxDecoration(color: Colors.amber.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(4)),
+ child: Text('root', style: tt.labelSmall?.copyWith(color: Colors.amber, fontSize: 9, fontWeight: FontWeight.w600)))
+ else if (type == 'admin') Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(4)),
+ child: Text('admin', style: tt.labelSmall?.copyWith(color: cs.primary, fontSize: 9, fontWeight: FontWeight.w600))),
+ if (isLocked) ...[const SizedBox(width: 4), Icon(Icons.lock_rounded, size: 12, color: Colors.red.withValues(alpha: 0.6))],
+ if (!isActive) ...[const SizedBox(width: 4), Container(
+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
+ decoration: BoxDecoration(color: Colors.red.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(4)),
+ child: Text('disabled', style: tt.labelSmall?.copyWith(color: Colors.red.withValues(alpha: 0.7), fontSize: 9)))],
+ ]),
+ if (!isActive) ...[
+ const SizedBox(height: 2),
+ Text('Disabled', style: tt.labelSmall?.copyWith(color: Colors.red.withValues(alpha: 0.5), fontSize: 10)),
+ ],
+ ])),
+ Icon(Icons.chevron_right_rounded, size: 18, color: Colors.white.withValues(alpha: 0.15)),
+ ]),
+ ),
+ ),
+ );
+ }
+
+ void _showUserDetail(Map<String, dynamic> user) {
+ Navigator.push(context, MaterialPageRoute(
+ builder: (_) => _UserDetailScreen(user: user, libraries: widget.libraries, onChanged: _reload),
+ ));
+ }
+
+ void _showEditor(Map<String, dynamic>? user) {
+ showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,
+ builder: (_) => _UserEditorSheet(user: user, libraries: widget.libraries, onSaved: _reload));
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// User Detail Screen
+// ═══════════════════════════════════════════════════════════════
+
+class _UserDetailScreen extends StatefulWidget {
+ final Map<String, dynamic> user;
+ final List<dynamic> libraries;
+ final VoidCallback onChanged;
+ const _UserDetailScreen({required this.user, required this.libraries, required this.onChanged});
+ @override State<_UserDetailScreen> createState() => _UserDetailScreenState();
+}
+
+class _UserDetailScreenState extends State<_UserDetailScreen> {
+ bool _loading = true;
+ Map<String, dynamic>? _fullUser;
+ List<Map<String, dynamic>> _progressItems = [];
+ final Map<String, Map<String, dynamic>> _itemCache = {};
+
+ @override
+ void initState() { super.initState(); _load(); }
+
+ Future<void> _load() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _loading = true);
+
+ final userId = widget.user['id'] as String? ?? '';
+ final userData = await api.getUser(userId);
+
+ if (userData != null) {
+ _fullUser = userData;
+ final progress = (userData['mediaProgress'] as List<dynamic>?) ?? [];
+
+ final items = <Map<String, dynamic>>[];
+ final fetchFutures = <Future>[];
+
+ for (final p in progress) {
+ if (p is Map<String, dynamic>) {
+ items.add(p);
+ final itemId = p['libraryItemId'] as String? ?? '';
+ if (itemId.isNotEmpty && !_itemCache.containsKey(itemId)) {
+ fetchFutures.add(
+ api.getLibraryItem(itemId).then((item) {
+ if (item != null) _itemCache[itemId] = item;
+ }),
+ );
+ }
+ }
+ }
+
+ // Fetch items in batches of 15
+ for (var i = 0; i < fetchFutures.length; i += 15) {
+ await Future.wait(fetchFutures.skip(i).take(15));
+ }
+
+ // Sort: in-progress first (by last update), then finished
+ items.sort((a, b) {
+ final aFinished = a['isFinished'] as bool? ?? false;
+ final bFinished = b['isFinished'] as bool? ?? false;
+ if (aFinished != bFinished) return aFinished ? 1 : -1;
+ final aTime = a['lastUpdate'] as num? ?? 0;
+ final bTime = b['lastUpdate'] as num? ?? 0;
+ return bTime.compareTo(aTime);
+ });
+
+ _progressItems = items;
+ }
+
+ if (mounted) setState(() => _loading = false);
+ }
+
+ String get _username => widget.user['username'] as String? ?? 'User';
+ String get _userType => widget.user['type'] as String? ?? 'user';
+ bool get _isRoot => _userType == 'root';
+
+ bool get _isOnline {
+ if (_progressItems.isEmpty) return false;
+ final now = DateTime.now().millisecondsSinceEpoch;
+ for (final p in _progressItems) {
+ final lastUpdate = p['lastUpdate'] as num? ?? 0;
+ if ((now - lastUpdate) < 120000) return true; // 2 minutes
+ }
+ return false;
+ }
+
+ String get _lastSeenStr {
+ num? mostRecent;
+ for (final p in _progressItems) {
+ final lu = p['lastUpdate'] as num? ?? 0;
+ if (mostRecent == null || lu > mostRecent) mostRecent = lu;
+ }
+ // Fall back to user's lastSeen if no progress data
+ final userLastSeen = (_fullUser ?? widget.user)['lastSeen'] as num?;
+ final best = (mostRecent != null && (userLastSeen == null || mostRecent > userLastSeen))
+ ? mostRecent : userLastSeen;
+ if (best == null) return 'Never';
+ return _timeAgo(DateTime.fromMillisecondsSinceEpoch(best.toInt()));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final finished = _progressItems.where((p) => p['isFinished'] == true).length;
+ final inProgress = _progressItems.where((p) => (p['isFinished'] != true) && (p['progress'] as num? ?? 0) > 0).length;
+
+ return Scaffold(
+ backgroundColor: const Color(0xFF0E0E0E),
+ body: SafeArea(
+ child: Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ Expanded(child: AbsorbPageHeader(title: _username, padding: EdgeInsets.zero)),
+ if (!_isRoot)
+ IconButton(
+ icon: Icon(Icons.edit_rounded, color: cs.primary.withValues(alpha: 0.7), size: 20),
+ tooltip: 'Edit user',
+ onPressed: _showEditor,
+ ),
+ IconButton(icon: const Icon(Icons.close_rounded, color: Colors.white38), onPressed: () => Navigator.pop(context)),
+ ]),
+ ),
+ // Online / last seen
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 2, 20, 0),
+ child: Row(children: [
+ Container(width: 8, height: 8, decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: _isOnline ? const Color(0xFF4CAF50) : Colors.white24,
+ )),
+ const SizedBox(width: 8),
+ Text(
+ _isOnline ? 'Online now' : 'Last seen $_lastSeenStr',
+ style: tt.labelSmall?.copyWith(
+ color: _isOnline ? const Color(0xFF4CAF50).withValues(alpha: 0.8) : Colors.white.withValues(alpha: 0.3),
+ fontSize: 11,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
+ decoration: BoxDecoration(
+ color: _isRoot ? Colors.amber.withValues(alpha: 0.12) : cs.primary.withValues(alpha: 0.1),
+ borderRadius: BorderRadius.circular(4)),
+ child: Text(_userType, style: tt.labelSmall?.copyWith(
+ color: _isRoot ? Colors.amber : cs.primary, fontSize: 9, fontWeight: FontWeight.w600)),
+ ),
+ ]),
+ ),
+ if (!_loading)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 12),
+ child: Row(children: [
+ _summaryChip(tt, '$inProgress', 'In Progress', cs.primary),
+ const SizedBox(width: 10),
+ _summaryChip(tt, '$finished', 'Finished', Colors.green),
+ const SizedBox(width: 10),
+ _summaryChip(tt, '${_progressItems.length}', 'Total', Colors.white38),
+ ]),
+ ),
+ Expanded(
+ child: _loading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : RefreshIndicator(
+ onRefresh: _load,
+ child: _progressItems.isEmpty
+ ? ListView(children: [
+ const SizedBox(height: 80),
+ Center(child: Icon(Icons.menu_book_rounded, size: 48, color: Colors.white.withValues(alpha: 0.08))),
+ const SizedBox(height: 12),
+ Center(child: Text('No reading activity', style: tt.bodyMedium?.copyWith(color: Colors.white24))),
+ ])
+ : ListView.builder(
+ padding: const EdgeInsets.only(bottom: 40),
+ itemCount: _progressItems.length,
+ itemBuilder: (_, i) => _progressTile(cs, tt, _progressItems[i]),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+
+ Widget _summaryChip(TextTheme tt, String value, String label, Color color) {
+ return Expanded(
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 10),
+ decoration: BoxDecoration(color: color.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(12)),
+ child: Column(children: [
+ Text(value, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: color == Colors.white38 ? Colors.white54 : color)),
+ const SizedBox(height: 2),
+ Text(label, style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.3), fontSize: 10)),
+ ]),
+ ),
+ );
+ }
+
+ Widget _progressTile(ColorScheme cs, TextTheme tt, Map<String, dynamic> progress) {
+ final itemId = progress['libraryItemId'] as String? ?? '';
+ final episodeId = progress['episodeId'] as String?;
+ final isFinished = progress['isFinished'] as bool? ?? false;
+ final progressVal = (progress['progress'] as num? ?? 0).toDouble();
+ final percent = (progressVal * 100).round();
+ final currentTime = progress['currentTime'] as num? ?? 0;
+ final duration = progress['duration'] as num? ?? 0;
+ final lastUpdate = progress['lastUpdate'] as num?;
+
+ final item = _itemCache[itemId];
+ final media = item?['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>?;
+ final title = metadata?['title'] as String? ?? itemId;
+ final author = metadata?['authorName'] as String? ?? metadata?['author'] as String? ?? '';
+
+ String? episodeTitle;
+ if (episodeId != null && media != null) {
+ final episodes = media['episodes'] as List?;
+ if (episodes != null) {
+ final ep = episodes.cast<Map<String, dynamic>?>().firstWhere(
+ (e) => e?['id'] == episodeId, orElse: () => null);
+ episodeTitle = ep?['title'] as String?;
+ }
+ }
+
+ final displayTitle = episodeTitle ?? title;
+ final subtitle = episodeTitle != null ? title : author;
+
+ final auth = context.read<AuthProvider>();
+ final coverUrl = item != null ? '${auth.serverUrl}/api/items/$itemId/cover?token=${auth.token}' : null;
+
+ final lastUpdateStr = lastUpdate != null
+ ? _timeAgo(DateTime.fromMillisecondsSinceEpoch(lastUpdate.toInt()))
+ : '';
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(14)),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: coverUrl != null
+ ? Image.network(coverUrl, width: 44, height: 44, fit: BoxFit.cover,
+ headers: auth.apiService?.mediaHeaders ?? {},
+ errorBuilder: (_, __, ___) => _coverFallback(cs))
+ : _coverFallback(cs),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(displayTitle, style: tt.bodySmall?.copyWith(color: Colors.white, fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ if (subtitle.isNotEmpty) ...[
+ const SizedBox(height: 1),
+ Text(subtitle, style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.3), fontSize: 10),
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ ],
+ const SizedBox(height: 6),
+ Row(children: [
+ Expanded(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(2),
+ child: LinearProgressIndicator(
+ value: progressVal.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.white.withValues(alpha: 0.06),
+ valueColor: AlwaysStoppedAnimation(
+ isFinished ? Colors.green : cs.primary.withValues(alpha: 0.8)),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Text(isFinished ? 'Finished' : '$percent%',
+ style: tt.labelSmall?.copyWith(
+ color: isFinished ? Colors.green.withValues(alpha: 0.8) : Colors.white38,
+ fontWeight: FontWeight.w600, fontSize: 10)),
+ ]),
+ const SizedBox(height: 3),
+ Row(children: [
+ Text('${_fmtDur(currentTime.toDouble())} / ${_fmtDur(duration.toDouble())}',
+ style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.2), fontSize: 9)),
+ if (lastUpdateStr.isNotEmpty) ...[
+ const Spacer(),
+ Text(lastUpdateStr, style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.2), fontSize: 9)),
+ ],
+ ]),
+ ])),
+ ]),
+ ),
+ );
+ }
+
+ Widget _coverFallback(ColorScheme cs) => Container(
+ width: 44, height: 44,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(8)),
+ child: Icon(Icons.auto_stories_rounded, size: 18, color: cs.primary.withValues(alpha: 0.3)),
+ );
+
+ void _showEditor() {
+ showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,
+ builder: (_) => _UserEditorSheet(user: widget.user, libraries: widget.libraries, onSaved: () {
+ widget.onChanged();
+ _load();
+ }));
+ }
+
+ String _timeAgo(DateTime dt) { final d = DateTime.now().difference(dt);
+ if (d.inSeconds < 60) return 'just now'; if (d.inMinutes < 60) return '${d.inMinutes}m ago';
+ if (d.inHours < 24) return '${d.inHours}h ago'; if (d.inDays < 30) return '${d.inDays}d ago';
+ return '${(d.inDays / 30).floor()}mo ago'; }
+
+ String _fmtDur(double s) {
+ final h = (s / 3600).floor();
+ final m = ((s % 3600) / 60).floor();
+ if (h > 0) return '${h}h ${m}m';
+ return '${m}m';
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// User Editor Sheet
+// ═══════════════════════════════════════════════════════════════
+
+class _UserEditorSheet extends StatefulWidget {
+ final Map<String, dynamic>? user;
+ final List<dynamic> libraries;
+ final VoidCallback onSaved;
+ const _UserEditorSheet({this.user, required this.libraries, required this.onSaved});
+ @override State<_UserEditorSheet> createState() => _UserEditorSheetState();
+}
+
+class _UserEditorSheetState extends State<_UserEditorSheet> {
+ final _usernameCtrl = TextEditingController();
+ final _passwordCtrl = TextEditingController();
+ late String _type;
+ late bool _isActive, _isLocked;
+ late bool _canDownload, _canUpdate, _canDelete, _canUpload, _accessExplicit, _accessAllLibraries;
+ final Set<String> _selectedLibraries = {};
+ bool _saving = false;
+ bool _deleting = false;
+
+ bool get _isNew => widget.user == null;
+
+ @override
+ void initState() {
+ super.initState();
+ final u = widget.user;
+ _usernameCtrl.text = u?['username'] as String? ?? '';
+ _type = u?['type'] as String? ?? 'user';
+ _isActive = u?['isActive'] as bool? ?? true;
+ _isLocked = u?['isLocked'] as bool? ?? false;
+ final p = u?['permissions'] as Map<String, dynamic>? ?? {};
+ _canDownload = p['download'] as bool? ?? true;
+ _canUpdate = p['update'] as bool? ?? false;
+ _canDelete = p['delete'] as bool? ?? false;
+ _canUpload = p['upload'] as bool? ?? false;
+ _accessExplicit = p['accessExplicitContent'] as bool? ?? true;
+ _accessAllLibraries = p['accessAllLibraries'] as bool? ?? true;
+ final accessible = (u?['librariesAccessible'] as List?)?.cast<String>() ?? [];
+ _selectedLibraries.addAll(accessible);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Container(
+ decoration: const BoxDecoration(color: Color(0xFF1A1A1A), borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Center(child: Container(margin: const EdgeInsets.only(top: 12), width: 36, height: 4,
+ decoration: BoxDecoration(color: Colors.white12, borderRadius: BorderRadius.circular(2)))),
+ Padding(padding: const EdgeInsets.fromLTRB(20, 16, 12, 0),
+ child: Row(children: [
+ Expanded(child: Text(_isNew ? 'New User' : 'Edit User', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: Colors.white))),
+ if (!_isNew) IconButton(
+ icon: Icon(Icons.delete_outline_rounded, color: Colors.red.shade300, size: 20),
+ onPressed: _deleting ? null : _deleteUser),
+ ])),
+ Flexible(child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ _lbl(tt, 'Username'), const SizedBox(height: 6),
+ TextField(controller: _usernameCtrl, enabled: _isNew, style: const TextStyle(color: Colors.white),
+ decoration: _deco(cs, 'Enter username')),
+ const SizedBox(height: 16),
+ _lbl(tt, _isNew ? 'Password' : 'New Password'), const SizedBox(height: 6),
+ TextField(controller: _passwordCtrl, obscureText: true, style: const TextStyle(color: Colors.white),
+ decoration: _deco(cs, _isNew ? 'Enter password' : 'Leave blank to keep current')),
+ const SizedBox(height: 20),
+ _lbl(tt, 'Account Type'), const SizedBox(height: 8),
+ Row(children: [
+ _chip(cs, tt, 'guest', Icons.person_outline_rounded), const SizedBox(width: 8),
+ _chip(cs, tt, 'user', Icons.person_rounded), const SizedBox(width: 8),
+ _chip(cs, tt, 'admin', Icons.admin_panel_settings_rounded),
+ ]),
+ const SizedBox(height: 20),
+ _lbl(tt, 'Status'), const SizedBox(height: 4),
+ _sw('Account Active', _isActive, (v) => setState(() => _isActive = v), sub: 'Disabled accounts cannot log in'),
+ _sw('Locked', _isLocked, (v) => setState(() => _isLocked = v), sub: 'Prevents password changes'),
+ const SizedBox(height: 12),
+ _lbl(tt, 'Permissions'), const SizedBox(height: 4),
+ _sw('Download', _canDownload, (v) => setState(() => _canDownload = v)),
+ _sw('Update', _canUpdate, (v) => setState(() => _canUpdate = v), sub: 'Edit metadata and library items'),
+ _sw('Delete', _canDelete, (v) => setState(() => _canDelete = v)),
+ _sw('Upload', _canUpload, (v) => setState(() => _canUpload = v)),
+ _sw('Explicit Content', _accessExplicit, (v) => setState(() => _accessExplicit = v)),
+ const SizedBox(height: 12),
+ _lbl(tt, 'Library Access'), const SizedBox(height: 4),
+ _sw('Access All Libraries', _accessAllLibraries, (v) => setState(() => _accessAllLibraries = v)),
+ if (!_accessAllLibraries) ...[
+ const SizedBox(height: 8),
+ ...widget.libraries.map((lib) {
+ final id = lib['id'] as String? ?? '';
+ final name = lib['name'] as String? ?? 'Library';
+ final sel = _selectedLibraries.contains(id);
+ return Padding(padding: const EdgeInsets.only(bottom: 4), child: GestureDetector(
+ onTap: () => setState(() { if (sel) _selectedLibraries.remove(id); else _selectedLibraries.add(id); }),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: sel ? cs.primary.withValues(alpha: 0.1) : Colors.white.withValues(alpha: 0.03),
+ borderRadius: BorderRadius.circular(10),
+ border: Border.all(color: sel ? cs.primary.withValues(alpha: 0.3) : Colors.white.withValues(alpha: 0.06))),
+ child: Row(children: [
+ Icon(sel ? Icons.check_circle_rounded : Icons.circle_outlined, size: 18, color: sel ? cs.primary : Colors.white24),
+ const SizedBox(width: 10),
+ Text(name, style: TextStyle(color: sel ? Colors.white : Colors.white54, fontWeight: sel ? FontWeight.w600 : FontWeight.w400)),
+ ]),
+ ),
+ ));
+ }),
+ ],
+ ]))),
+ Padding(padding: EdgeInsets.fromLTRB(20, 8, 20, MediaQuery.of(context).padding.bottom + 12),
+ child: SizedBox(width: double.infinity, height: 48, child: FilledButton(
+ onPressed: _saving ? null : _save,
+ style: FilledButton.styleFrom(backgroundColor: cs.primary, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14))),
+ child: _saving
+ ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
+ : Text(_isNew ? 'Create User' : 'Save Changes', style: TextStyle(fontWeight: FontWeight.w700, color: cs.onPrimary)),
+ ))),
+ ]));
+ }
+
+ Widget _lbl(TextTheme tt, String t) => Text(t, style: tt.labelMedium?.copyWith(color: Colors.white54, fontWeight: FontWeight.w600));
+
+ InputDecoration _deco(ColorScheme cs, String hint) => InputDecoration(
+ hintText: hint, hintStyle: TextStyle(color: Colors.white.withValues(alpha: 0.2)),
+ filled: true, fillColor: Colors.white.withValues(alpha: 0.04),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),
+ enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),
+ focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.5))),
+ disabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.04))),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12));
+
+ Widget _chip(ColorScheme cs, TextTheme tt, String type, IconData ic) {
+ final on = _type == type;
+ return Expanded(child: GestureDetector(onTap: () => setState(() => _type = type),
+ child: AnimatedContainer(duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(vertical: 10),
+ decoration: BoxDecoration(
+ color: on ? cs.primary.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.03),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: on ? cs.primary.withValues(alpha: 0.4) : Colors.white.withValues(alpha: 0.06))),
+ child: Column(children: [
+ Icon(ic, size: 20, color: on ? cs.primary : Colors.white.withValues(alpha: 0.3)), const SizedBox(height: 4),
+ Text(type[0].toUpperCase() + type.substring(1),
+ style: tt.labelSmall?.copyWith(color: on ? cs.primary : Colors.white38, fontWeight: on ? FontWeight.w700 : FontWeight.w500, fontSize: 11)),
+ ]))));
+ }
+
+ Widget _sw(String l, bool v, ValueChanged<bool> cb, {String? sub}) => SwitchListTile(dense: true, contentPadding: EdgeInsets.zero,
+ title: Text(l, style: const TextStyle(color: Colors.white, fontSize: 14)),
+ subtitle: sub != null ? Text(sub, style: TextStyle(color: Colors.white.withValues(alpha: 0.3), fontSize: 11)) : null,
+ value: v, onChanged: cb);
+
+ Future<void> _save() async {
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ final username = _usernameCtrl.text.trim();
+ if (username.isEmpty) { _snk('Username is required'); return; }
+ if (_isNew && _passwordCtrl.text.isEmpty) { _snk('Password is required'); return; }
+ setState(() => _saving = true);
+ final perms = {'download': _canDownload, 'update': _canUpdate, 'delete': _canDelete, 'upload': _canUpload,
+ 'accessExplicitContent': _accessExplicit, 'accessAllLibraries': _accessAllLibraries, 'accessAllTags': true};
+ bool ok;
+ if (_isNew) {
+ final r = await api.createUser(username: username, password: _passwordCtrl.text, type: _type,
+ permissions: perms, librariesAccessible: _accessAllLibraries ? [] : _selectedLibraries.toList());
+ ok = r != null;
+ } else {
+ final up = <String, dynamic>{'type': _type, 'isActive': _isActive, 'isLocked': _isLocked,
+ 'permissions': perms, 'librariesAccessible': _accessAllLibraries ? [] : _selectedLibraries.toList()};
+ if (_passwordCtrl.text.isNotEmpty) up['password'] = _passwordCtrl.text;
+ ok = await api.updateUser(widget.user!['id'] as String, up);
+ }
+ if (mounted) { setState(() => _saving = false);
+ if (ok) { widget.onSaved(); Navigator.pop(context); _snk(_isNew ? 'User created' : 'User updated'); }
+ else { _snk(_isNew ? 'Failed to create user' : 'Failed to update user'); } }
+ }
+
+ Future<void> _deleteUser() async {
+ final name = widget.user?['username'] ?? 'this user';
+ final yes = await showDialog<bool>(context: context, builder: (ctx) => AlertDialog(
+ backgroundColor: const Color(0xFF2A2A2A),
+ title: const Text('Delete User?', style: TextStyle(color: Colors.white)),
+ content: Text('Permanently delete $name?', style: const TextStyle(color: Colors.white70)),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text('Delete', style: TextStyle(color: Colors.red.shade300)))],
+ ));
+ if (yes != true) return;
+ final api = context.read<AuthProvider>().apiService; if (api == null) return;
+ setState(() => _deleting = true);
+ final ok = await api.deleteUser(widget.user!['id'] as String);
+ if (mounted) { setState(() => _deleting = false);
+ if (ok) { widget.onSaved(); Navigator.pop(context); _snk('$name deleted'); }
+ else { _snk('Failed to delete user'); } }
+ }
+
+ void _snk(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(
+ SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+}
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
new file mode 100644
index 00000000..32e54310
--- /dev/null
+++ b/lib/screens/app_shell.dart
@@ -0,0 +1,327 @@
+import 'dart:math' as math;
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import 'package:url_launcher/url_launcher.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/sleep_timer_service.dart';
+import '../services/android_auto_service.dart';
+import '../services/update_checker_service.dart';
+import 'absorbing_screen.dart';
+import 'home_screen.dart';
+import 'library_screen.dart';
+import 'stats_screen.dart';
+import 'settings_screen.dart';
+
+class AppShell extends StatefulWidget {
+ const AppShell({super.key});
+
+ /// Navigate to the Absorbing tab using BuildContext (ancestor lookup).
+ static void goToAbsorbing(BuildContext context) {
+ final state = context.findAncestorStateOfType<_AppShellState>();
+ state?._switchToAbsorbing();
+ }
+
+ /// Navigate to the Absorbing tab without needing a context.
+ static void goToAbsorbingGlobal() {
+ _AppShellState._instance?._switchToAbsorbing();
+ }
+
+ @override
+ State<AppShell> createState() => _AppShellState();
+}
+
+class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
+ static _AppShellState? _instance;
+
+ // Tabs: 0=Home, 1=Library, 2=Absorbing (default), 3=Stats, 4=Settings
+ int _currentIndex = 2;
+ final _libraryKey = GlobalKey<LibraryScreenState>();
+
+ void _switchToAbsorbing() {
+ if (mounted) {
+ _navigateTo(2);
+ // Scroll to the currently playing book after the tab switch
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ AbsorbingScreen.scrollToActive();
+ });
+ }
+ }
+
+ void _navigateTo(int index) {
+ if (index == _currentIndex) return;
+ setState(() {
+ _currentIndex = index;
+ });
+ }
+
+ late final _pages = [
+ const HomeScreen(),
+ LibraryScreen(key: _libraryKey),
+ AbsorbingScreen(key: AbsorbingScreen.globalKey),
+ const StatsScreen(),
+ const SettingsScreen(),
+ ];
+
+ @override
+ void initState() {
+ super.initState();
+ _instance = this;
+ WidgetsBinding.instance.addObserver(this);
+ AudioPlayerService.setOnEpisodePlayStartedCallback(AppShell.goToAbsorbingGlobal);
+ _checkForUpdate();
+ }
+
+ Future<void> _checkForUpdate() async {
+ final update = await UpdateCheckerService.check();
+ if (update != null && mounted) {
+ _showUpdateBanner(update);
+ }
+ }
+
+ void _showUpdateBanner(UpdateInfo update) {
+ ScaffoldMessenger.of(context).showMaterialBanner(
+ MaterialBanner(
+ padding: const EdgeInsets.fromLTRB(16, 12, 8, 12),
+ leading: Icon(Icons.system_update_rounded, color: Theme.of(context).colorScheme.primary),
+ content: Text('Absorb ${update.latestVersion} is available',
+ style: TextStyle(fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface)),
+ actions: [
+ TextButton(
+ onPressed: () {
+ ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
+ UpdateCheckerService.dismiss(update.latestVersion);
+ },
+ child: const Text('Later'),
+ ),
+ FilledButton(
+ onPressed: () {
+ ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
+ launchUrl(Uri.parse(update.downloadUrl), mode: LaunchMode.externalApplication);
+ },
+ child: const Text('Update'),
+ ),
+ ],
+ ),
+ );
+ }
+
+ @override
+ void dispose() {
+ if (_instance == this) _instance = null;
+ WidgetsBinding.instance.removeObserver(this);
+ super.dispose();
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state == AppLifecycleState.resumed) {
+ _refreshData();
+ // Check auto sleep in case we resumed into the window
+ SleepTimerService().checkAutoSleep();
+ }
+ }
+
+ DateTime? _lastRefresh;
+ static const _refreshCooldown = Duration(minutes: 1);
+
+ void _refreshData() {
+ final now = DateTime.now();
+ final lib = context.read<LibraryProvider>();
+
+ // Always sync local progress (cheap, no network)
+ lib.refreshLocalProgress();
+
+ // Only do a full server refresh if enough time has passed
+ if (_lastRefresh == null || now.difference(_lastRefresh!) > _refreshCooldown) {
+ _lastRefresh = now;
+ lib.refresh();
+ // Keep Android Auto browse tree in sync
+ AndroidAutoService().refresh();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return PopScope(
+ canPop: false,
+ onPopInvokedWithResult: (didPop, _) {
+ if (didPop) return;
+
+ // If on Library tab with active search, clear search first
+ if (_currentIndex == 1 &&
+ _libraryKey.currentState?.isSearchActive == true) {
+ _libraryKey.currentState?.clearSearch();
+ return;
+ }
+
+ // If already on Absorbing tab, move app to background (keep playback alive)
+ if (_currentIndex == 2) {
+ SystemChannels.platform.invokeMethod('SystemNavigator.pop', true);
+ return;
+ }
+
+ // From any other tab, go to Absorbing
+ _switchToAbsorbing();
+ },
+ child: Scaffold(
+ body: IndexedStack(
+ index: _currentIndex,
+ children: _pages,
+ ),
+ bottomNavigationBar: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ NavigationBar(
+ selectedIndex: _currentIndex,
+ onDestinationSelected: (i) {
+ // If tapping Library while already on Library, clear search
+ if (i == 1 && _currentIndex == 1 &&
+ _libraryKey.currentState?.isSearchActive == true) {
+ _libraryKey.currentState?.clearSearch();
+ return;
+ }
+ _navigateTo(i);
+ // Refresh data on switching to Library, Home, Absorbing, or Stats
+ if (i == 0 || i == 1 || i == 2 || i == 3) _refreshData();
+ },
+ destinations: _buildDestinations(context),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ List<NavigationDestination> _buildDestinations(BuildContext context) {
+ final lib = context.watch<LibraryProvider>();
+ final isPodcast = lib.isPodcastLibrary;
+
+ return [
+ NavigationDestination(
+ icon: Icon(isPodcast ? Icons.explore_outlined : Icons.home_outlined),
+ selectedIcon: Icon(isPodcast ? Icons.explore_rounded : Icons.home_rounded),
+ label: isPodcast ? 'Discover' : 'Home',
+ ),
+ NavigationDestination(
+ icon: Icon(isPodcast ? Icons.podcasts_outlined : Icons.library_books_outlined),
+ selectedIcon: Icon(isPodcast ? Icons.podcasts_rounded : Icons.library_books_rounded),
+ label: isPodcast ? 'Shows' : 'Library',
+ ),
+ NavigationDestination(
+ icon: const _AnimatedWaveIcon(size: 24, active: false),
+ selectedIcon: const _AnimatedWaveIcon(size: 24, active: true),
+ label: 'Absorbing',
+ ),
+ const NavigationDestination(
+ icon: Icon(Icons.bar_chart_rounded),
+ selectedIcon: Icon(Icons.bar_chart_rounded),
+ label: 'Stats',
+ ),
+ const NavigationDestination(
+ icon: Icon(Icons.settings_outlined),
+ selectedIcon: Icon(Icons.settings_rounded),
+ label: 'Settings',
+ ),
+ ];
+ }
+}
+
+// ─── Animated wave icon for nav bar matching notification icon ────
+class _AnimatedWaveIcon extends StatefulWidget {
+ final double size;
+ final bool active;
+
+ const _AnimatedWaveIcon({required this.size, required this.active});
+
+ @override
+ State<_AnimatedWaveIcon> createState() => _AnimatedWaveIconState();
+}
+
+class _AnimatedWaveIconState extends State<_AnimatedWaveIcon>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _ctrl;
+ final _player = AudioPlayerService();
+
+ @override
+ void initState() {
+ super.initState();
+ _ctrl = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1400),
+ )..repeat();
+ _player.addListener(_rebuild);
+ }
+
+ @override
+ void dispose() {
+ _ctrl.dispose();
+ _player.removeListener(_rebuild);
+ super.dispose();
+ }
+
+ void _rebuild() { if (mounted) setState(() {}); }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final playing = _player.isPlaying;
+
+ return AnimatedBuilder(
+ animation: _ctrl,
+ builder: (_, __) => CustomPaint(
+ size: Size(widget.size, widget.size),
+ painter: _NavWavePainter(
+ phase: _ctrl.value,
+ color: widget.active ? cs.primary : cs.onSurfaceVariant,
+ playing: playing,
+ ),
+ ),
+ );
+ }
+}
+
+class _NavWavePainter extends CustomPainter {
+ final double phase;
+ final Color color;
+ final bool playing;
+
+ _NavWavePainter({required this.phase, required this.color, required this.playing});
+
+ 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 paint = Paint()
+ ..color = color
+ ..strokeWidth = 2.5
+ ..strokeCap = StrokeCap.round;
+
+ final totalWidth = size.width * 0.6;
+ final startX = (size.width - totalWidth) / 2;
+ final spacing = totalWidth / (_barCount - 1);
+ final midY = size.height / 2;
+ final maxHalf = size.height * 0.38;
+
+ for (int i = 0; i < _barCount; i++) {
+ final x = startX + spacing * i;
+ final baseRatio = _barHeights[i];
+
+ if (playing) {
+ final barPhase = phase * 2 * math.pi + i * 1.2;
+ final ratio = (baseRatio * (0.5 + 0.5 * math.sin(barPhase))).clamp(0.2, 1.0);
+ final half = maxHalf * ratio;
+ canvas.drawLine(Offset(x, midY - half), Offset(x, midY + half), paint);
+ } else {
+ final half = maxHalf * baseRatio;
+ canvas.drawLine(Offset(x, midY - half), Offset(x, midY + half), paint);
+ }
+ }
+ }
+
+ @override
+ bool shouldRepaint(_NavWavePainter old) =>
+ old.phase != phase || old.playing != playing || old.color != color;
+}
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
new file mode 100644
index 00000000..c1095875
--- /dev/null
+++ b/lib/screens/home_screen.dart
@@ -0,0 +1,644 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../widgets/home_section.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/shimmer.dart';
+import '../widgets/book_detail_sheet.dart';
+import '../widgets/episode_list_sheet.dart';
+import 'app_shell.dart';
+
+class HomeScreen extends StatefulWidget {
+ const HomeScreen({super.key});
+
+ @override
+ State<HomeScreen> createState() => _HomeScreenState();
+}
+
+class _HomeScreenState extends State<HomeScreen> {
+ final _player = AudioPlayerService();
+ bool _hideEbookOnly = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _player.addListener(_onPlayerChanged);
+ _loadSettings();
+ Future.microtask(() {
+ final lib = context.read<LibraryProvider>();
+ if (lib.libraries.isEmpty) lib.loadLibraries();
+ lib.refreshLocalProgress();
+ });
+ }
+
+ Future<void> _loadSettings() async {
+ final hide = await PlayerSettings.getHideEbookOnly();
+ if (mounted) setState(() => _hideEbookOnly = hide);
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ // Refresh setting when returning to screen
+ _loadSettings();
+ }
+
+ List<dynamic> _filterEbookOnly(List<dynamic> items) {
+ if (!_hideEbookOnly) return items;
+ return items.where((e) {
+ if (e is! Map<String, dynamic>) return true;
+ // Personalized view entities may nest the item under 'libraryItem'
+ final item = e.containsKey('libraryItem')
+ ? e['libraryItem'] as Map<String, dynamic>? ?? e
+ : e;
+ return !PlayerSettings.isEbookOnly(item);
+ }).toList();
+ }
+
+ @override
+ void dispose() {
+ _player.removeListener(_onPlayerChanged);
+ super.dispose();
+ }
+
+ void _onPlayerChanged() {
+ if (mounted) {
+ context.read<LibraryProvider>().refreshLocalProgress();
+ setState(() {});
+ }
+ }
+
+ void _showLibraryPicker(BuildContext context, ColorScheme cs, TextTheme tt, List<dynamic> allLibraries, LibraryProvider lib) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) {
+ final bottomPad = MediaQuery.of(ctx).viewPadding.bottom;
+ return Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(ctx).size.height * 0.6),
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox(height: 12),
+ Center(child: Container(width: 40, height: 4,
+ decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)))),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Text('Select Library', style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
+ ),
+ const SizedBox(height: 12),
+ Flexible(
+ child: ListView.builder(
+ shrinkWrap: true,
+ padding: EdgeInsets.only(bottom: bottomPad + 16),
+ itemCount: allLibraries.length,
+ itemBuilder: (_, i) {
+ final library = allLibraries[i] as Map<String, dynamic>;
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? 'Library';
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+ return ListTile(
+ leading: Icon(mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded,
+ color: isSelected ? cs.primary : cs.onSurfaceVariant),
+ title: Text(name),
+ trailing: isSelected
+ ? Icon(Icons.check_circle_rounded, color: cs.primary)
+ : null,
+ selected: isSelected,
+ onTap: () {
+ Navigator.pop(ctx);
+ if (!isSelected) lib.selectLibrary(id);
+ },
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ static const _prioritySections = [
+ 'continue-listening',
+ 'continue-series',
+ 'episodes-recently-added',
+ 'recently-added',
+ 'listen-again',
+ 'discover',
+ ];
+
+ static const _hiddenSections = {'newest-authors', 'recent-series'};
+
+ static const _sectionLabels = {
+ 'continue-listening': 'Continue Listening',
+ 'continue-series': 'Continue Series',
+ 'recently-added': 'Recently Added',
+ 'listen-again': 'Listen Again',
+ 'discover': 'Discover',
+ 'episodes-recently-added': 'New Episodes',
+ 'downloaded-books': 'Downloads',
+ };
+
+ static const _sectionIcons = {
+ 'continue-listening': Icons.play_circle_outline_rounded,
+ 'continue-series': Icons.auto_stories_rounded,
+ 'recently-added': Icons.new_releases_outlined,
+ 'listen-again': Icons.replay_rounded,
+ 'discover': Icons.explore_outlined,
+ 'episodes-recently-added': Icons.podcasts_rounded,
+ 'downloaded-books': Icons.download_done_rounded,
+ };
+
+ List<dynamic> _sortSections(List<dynamic> sections) {
+ final sorted = List<dynamic>.from(sections);
+ sorted.sort((a, b) {
+ final aIdx = _prioritySections.indexOf(a['id'] ?? '');
+ final bIdx = _prioritySections.indexOf(b['id'] ?? '');
+ return (aIdx == -1 ? 999 : aIdx).compareTo(bIdx == -1 ? 999 : bIdx);
+ });
+ return sorted;
+ }
+
+ String _titleCase(String s) {
+ return s.replaceAll('-', ' ').split(' ')
+ .map((w) => w.isEmpty ? w : '${w[0].toUpperCase()}${w.substring(1)}')
+ .join(' ');
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final allLibraries = lib.libraries;
+ final libraryName = lib.selectedLibrary?['name'] as String? ?? 'Library';
+
+ return Scaffold(
+ body: Container(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.3, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.06),
+ cs.surface,
+ cs.surface,
+ ],
+ ),
+ ),
+ child: SafeArea(
+ child: RefreshIndicator(
+ onRefresh: () async {
+ await lib.refresh();
+ },
+ child: CustomScrollView(
+ slivers: [
+ // ── Top bar: ABSORB title + page name ──
+ SliverToBoxAdapter(
+ child: AbsorbPageHeader(
+ title: 'Home',
+ actions: [
+ if (!lib.isOffline && allLibraries.length > 1)
+ GestureDetector(
+ onTap: () => _showLibraryPicker(context, cs, tt, allLibraries, lib),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(lib.isPodcastLibrary ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 14, color: cs.onSurfaceVariant),
+ const SizedBox(width: 6),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 140),
+ child: Text(libraryName, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant),
+ overflow: TextOverflow.ellipsis, maxLines: 1),
+ ),
+ const SizedBox(width: 4),
+ Icon(Icons.unfold_more_rounded, size: 14, color: cs.onSurfaceVariant),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+
+ // ── Currently Absorbing section ──
+ if (!lib.isLoading)
+ ...() {
+ // Find continue-listening entities
+ List<dynamic> clItems = [];
+ for (final section in lib.personalizedSections) {
+ if (section['id'] == 'continue-listening') {
+ clItems = _filterEbookOnly((section['entities'] as List<dynamic>?) ?? []);
+ break;
+ }
+ }
+
+ // For podcast libraries, deduplicate by show ID — ABS returns
+ // one entity per in-progress episode, all with the same show id.
+ // Keep the first occurrence (most recently updated) per show.
+ if (lib.isPodcastLibrary && clItems.isNotEmpty) {
+ final seen = <String>{};
+ clItems = clItems.where((item) {
+ final id = (item as Map<String, dynamic>)['id'] as String? ?? '';
+ return seen.add(id);
+ }).toList();
+ }
+
+ if (clItems.isEmpty) return <Widget>[];
+ return <Widget>[
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
+ child: Row(
+ children: [
+ Icon(Icons.play_circle_outline_rounded, size: 16,
+ color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Text('Continue Listening',
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface.withValues(alpha: 0.8),
+ letterSpacing: 0.3,
+ )),
+ const SizedBox(width: 12),
+ Expanded(child: Container(height: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.2))),
+ ],
+ ),
+ ),
+ ),
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: SizedBox(
+ height: 72,
+ child: ListView.separated(
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ physics: const BouncingScrollPhysics(),
+ itemCount: clItems.length,
+ separatorBuilder: (_, __) => const SizedBox(width: 10),
+ itemBuilder: (context, i) {
+ final item = clItems[i] as Map<String, dynamic>;
+ return _ContinueListeningCard(
+ item: item,
+ lib: lib,
+ player: _player,
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ ];
+ }(),
+
+ // ── Loading shimmer ──
+ if (lib.isLoading)
+ ...[
+ const SliverToBoxAdapter(child: SizedBox(height: 16)),
+ const SliverToBoxAdapter(child: ShimmerHeroCard()),
+ const SliverToBoxAdapter(child: SizedBox(height: 20)),
+ const SliverToBoxAdapter(child: ShimmerBookRow()),
+ const SliverToBoxAdapter(child: SizedBox(height: 8)),
+ const SliverToBoxAdapter(child: ShimmerBookRow()),
+ ],
+
+ // ── Error ──
+ if (!lib.isLoading && lib.errorMessage != null &&
+ lib.personalizedSections.isEmpty)
+ SliverFillRemaining(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.cloud_off_rounded, size: 48, color: cs.error),
+ const SizedBox(height: 12),
+ Text(lib.errorMessage!,
+ style: tt.bodyLarge?.copyWith(color: cs.error)),
+ const SizedBox(height: 16),
+ FilledButton.tonal(
+ onPressed: lib.refresh,
+ child: const Text('Retry')),
+ ],
+ ),
+ ),
+ ),
+
+ // ── Empty ──
+ if (!lib.isLoading && lib.errorMessage == null &&
+ lib.personalizedSections.isEmpty && (lib.libraries.isNotEmpty || lib.isOffline))
+ SliverFillRemaining(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ lib.isOffline
+ ? Icons.download_for_offline_outlined
+ : Icons.library_music_outlined,
+ size: 48,
+ color: cs.onSurfaceVariant,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ lib.isOffline
+ ? 'No downloaded books'
+ : 'Your library is empty',
+ style: tt.bodyLarge?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ if (lib.isOffline) ...[
+ const SizedBox(height: 4),
+ Text(
+ 'Download books while online to listen offline',
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+
+ // ── Other sections ──
+ if (!lib.isLoading)
+ ..._sortSections(lib.personalizedSections).map((section) {
+ final id = section['id'] ?? '';
+ if (id == 'continue-listening' ||
+ _hiddenSections.contains(id)) {
+ return const SliverToBoxAdapter();
+ }
+ final label = section['label'] ??
+ _sectionLabels[id] ?? _titleCase(id);
+ final entities =
+ _filterEbookOnly((section['entities'] as List<dynamic>?) ?? []);
+ final type = section['type'] ?? 'book';
+ if (entities.isEmpty) return const SliverToBoxAdapter();
+
+ return SliverToBoxAdapter(
+ child: HomeSection(
+ title: label,
+ icon: _sectionIcons[id] ?? Icons.album_outlined,
+ entities: entities,
+ sectionType: type,
+ sectionId: id,
+ ),
+ );
+ }),
+
+ const SliverPadding(padding: EdgeInsets.only(bottom: 100)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+// ══════════════════════════════════════════════════════════════
+// Continue Listening Card — compact card with play button
+// ══════════════════════════════════════════════════════════════
+
+class _ContinueListeningCard extends StatefulWidget {
+ final Map<String, dynamic> item;
+ final LibraryProvider lib;
+ final AudioPlayerService player;
+
+ const _ContinueListeningCard({
+ required this.item,
+ required this.lib,
+ required this.player,
+ });
+
+ @override
+ State<_ContinueListeningCard> createState() => _ContinueListeningCardState();
+}
+
+class _ContinueListeningCardState extends State<_ContinueListeningCard> {
+ bool _isLoading = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final item = widget.item;
+ final lib = widget.lib;
+ final player = widget.player;
+
+ final itemId = item['id'] as String? ?? '';
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final recentEpisode = item['recentEpisode'] as Map<String, dynamic>?;
+
+ // For podcasts with recentEpisode, show episode title + show name
+ final title = recentEpisode != null
+ ? (recentEpisode['title'] as String? ?? 'Episode')
+ : (metadata['title'] as String? ?? 'Unknown');
+ final author = recentEpisode != null
+ ? (metadata['title'] as String? ?? '')
+ : (metadata['authorName'] as String? ?? '');
+
+ final coverUrl = lib.getCoverUrl(itemId);
+
+ // For podcast episodes, use compound key for progress
+ final episodeId = recentEpisode?['id'] as String?;
+ final progress = episodeId != null
+ ? lib.getEpisodeProgress(itemId, episodeId)
+ : lib.getProgress(itemId);
+ final isCurrentItem = player.currentItemId == itemId;
+
+ return GestureDetector(
+ onTap: () {
+ if (lib.isPodcastLibrary) {
+ EpisodeListSheet.show(context, item);
+ } else {
+ showBookDetailSheet(context, itemId);
+ }
+ },
+ child: Container(
+ width: 280,
+ padding: const EdgeInsets.all(10),
+ decoration: BoxDecoration(
+ color: isCurrentItem
+ ? cs.primary.withValues(alpha: 0.08)
+ : cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ border: isCurrentItem
+ ? Border.all(color: cs.primary.withValues(alpha: 0.2))
+ : null,
+ ),
+ child: Row(
+ children: [
+ // Cover
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: SizedBox(
+ width: 48, height: 48,
+ child: coverUrl != null
+ ? coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.headphones_rounded, size: 18, color: cs.onSurfaceVariant)))
+ : CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ errorWidget: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.headphones_rounded, size: 18, color: cs.onSurfaceVariant)))
+ : Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.headphones_rounded, size: 18, color: cs.onSurfaceVariant)),
+ ),
+ ),
+ const SizedBox(width: 10),
+ // Title + author + progress
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface)),
+ if (author.isNotEmpty)
+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant, fontSize: 11)),
+ const SizedBox(height: 4),
+ // Thin progress bar
+ ClipRRect(
+ borderRadius: BorderRadius.circular(2),
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: cs.outlineVariant.withValues(alpha: 0.2),
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ // Play button
+ GestureDetector(
+ onTap: _isLoading ? null : () {
+ if (isCurrentItem) {
+ player.togglePlayPause();
+ } else {
+ _startBook(context, itemId);
+ }
+ },
+ child: Container(
+ width: 34, height: 34,
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: isCurrentItem ? 1.0 : 0.15),
+ shape: BoxShape.circle,
+ ),
+ child: _isLoading
+ ? Padding(
+ padding: const EdgeInsets.all(9),
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: isCurrentItem ? cs.onPrimary : cs.primary,
+ ),
+ )
+ : Icon(
+ isCurrentItem && player.isPlaying
+ ? Icons.pause_rounded
+ : Icons.play_arrow_rounded,
+ size: 18,
+ color: isCurrentItem ? cs.onPrimary : cs.primary,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Future<void> _startBook(BuildContext context, String itemId) async {
+ setState(() => _isLoading = true);
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) { setState(() => _isLoading = false); return; }
+
+ // Check if this is a podcast with a recentEpisode
+ final recentEpisode = widget.item['recentEpisode'] as Map<String, dynamic>?;
+
+ if (recentEpisode != null) {
+ // Podcast episode — play the recent episode directly
+ final episodeId = recentEpisode['id'] as String? ?? '';
+ final episodeTitle = recentEpisode['title'] as String? ?? 'Episode';
+ final media = widget.item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final showTitle = metadata['title'] as String? ?? '';
+ final epDuration = (recentEpisode['duration'] as num?)?.toDouble() ?? 0;
+ final coverUrl = widget.lib.getCoverUrl(itemId);
+
+ await widget.player.playItem(
+ api: api, itemId: itemId, title: episodeTitle, author: showTitle,
+ coverUrl: coverUrl, totalDuration: epDuration, chapters: [],
+ episodeId: episodeId,
+ episodeTitle: episodeTitle,
+ );
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+
+ // Fetch full item data to get chapters
+ final fullItem = await api.getLibraryItem(itemId);
+ if (fullItem == null) { if (mounted) setState(() => _isLoading = false); 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 = widget.lib.getCoverUrl(itemId);
+ final duration = (media['duration'] is num)
+ ? (media['duration'] as num).toDouble() : 0.0;
+ final chapters = (media['chapters'] as List<dynamic>?) ?? [];
+
+ // Start playback
+ await widget.player.playItem(
+ api: api, itemId: itemId, title: title, author: author,
+ coverUrl: coverUrl, totalDuration: duration, chapters: chapters,
+ );
+
+ // Ensure this book is on the absorbing list (clear any manual remove)
+ if (context.mounted) {
+ context.read<LibraryProvider>().addToAbsorbing(itemId);
+ }
+
+ if (mounted) setState(() => _isLoading = false);
+ // Navigate to absorbing screen
+ if (context.mounted) AppShell.goToAbsorbing(context);
+ }
+}
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
new file mode 100644
index 00000000..e3950de5
--- /dev/null
+++ b/lib/screens/library_screen.dart
@@ -0,0 +1,2288 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+import 'dart:ui' as ui;
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:http/http.dart' as http;
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/download_service.dart';
+import '../services/audio_player_service.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/book_detail_sheet.dart';
+import '../widgets/episode_list_sheet.dart';
+
+// ─── Sort modes ──────────────────────────────────────────────
+enum LibrarySort { recentlyAdded, alphabetical, authorName, publishedYear, duration, random }
+
+// ─── Filter modes ────────────────────────────────────────────
+enum LibraryFilter { none, inProgress, finished, notStarted, downloaded, hasEbook, genre }
+
+/// Show a bottom sheet with all books in a series, sorted by sequence.
+/// Can be called from any screen.
+void showSeriesBooksSheet(BuildContext context, {
+ required String seriesName,
+ String? seriesId,
+ List<dynamic> books = const [],
+ String? serverUrl,
+ String? token,
+}) {
+ FocusManager.instance.primaryFocus?.unfocus();
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ showDragHandle: true,
+ builder: (_) => DraggableScrollableSheet(
+ initialChildSize: 0.7,
+ minChildSize: 0.4,
+ maxChildSize: 0.9,
+ expand: false,
+ builder: (ctx, scrollController) => _SeriesBooksSheet(
+ seriesName: seriesName,
+ seriesId: seriesId,
+ books: books,
+ serverUrl: serverUrl,
+ token: token,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+}
+
+class LibraryScreen extends StatefulWidget {
+ const LibraryScreen({super.key});
+
+ @override
+ State<LibraryScreen> createState() => LibraryScreenState();
+}
+
+class LibraryScreenState extends State<LibraryScreen> {
+ // ── Search state ──
+ final _searchController = TextEditingController();
+ final _focusNode = FocusNode();
+ Timer? _debounce;
+
+ /// Whether the search bar has active text.
+ bool get isSearchActive => _searchController.text.trim().isNotEmpty;
+
+ /// Clear the search and return to the browse grid.
+ void clearSearch() {
+ _searchController.clear();
+ _onSearchChanged('');
+ _focusNode.unfocus();
+ }
+ List<dynamic> _searchBookResults = [];
+ List<dynamic> _searchSeriesResults = [];
+ List<dynamic> _searchAuthorResults = [];
+ bool _isSearching = false;
+ bool _hasSearched = false;
+ bool get _isInSearchMode => _searchController.text.trim().isNotEmpty;
+
+ // ── Browse state ──
+ LibrarySort _sort = LibrarySort.recentlyAdded;
+ bool _sortAsc = false; // false = desc (newest/longest first), true = asc
+ LibraryFilter _filter = LibraryFilter.none;
+ String? _genreFilter;
+ List<String> _availableGenres = [];
+ bool _hideEbookOnly = false;
+ final List<Map<String, dynamic>> _items = [];
+ bool _isLoadingPage = false;
+ bool _hasMore = true;
+ int _page = 0;
+ int _totalItems = 0;
+ int? _randomSeed;
+ int _loadGeneration = 0; // prevents stale async loads from corrupting state
+ static const _pageSize = 20;
+
+ final _scrollController = ScrollController();
+
+ /// Called externally (e.g. from AppShell) to focus the search field.
+ void requestSearchFocus() {
+ _focusNode.requestFocus();
+ }
+
+ String? _lastLibraryId;
+
+ @override
+ void initState() {
+ super.initState();
+ _scrollController.addListener(_onScroll);
+ // Load initial page once the library is ready
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _tryInitialLoad();
+ final lib = context.read<LibraryProvider>();
+ _lastLibraryId = lib.selectedLibraryId;
+ lib.addListener(_onLibraryProviderChanged);
+ });
+ }
+
+ void _onLibraryProviderChanged() {
+ final lib = context.read<LibraryProvider>();
+ if (lib.selectedLibraryId != _lastLibraryId && lib.selectedLibraryId != null) {
+ _lastLibraryId = lib.selectedLibraryId;
+ _loadGeneration++;
+ setState(() {
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ _availableGenres = [];
+ // Reset all filters on library switch — filters don't carry across libraries
+ _filter = LibraryFilter.none;
+ _genreFilter = null;
+ });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ _loadGenres();
+ }
+ }
+
+ void _tryInitialLoad() {
+ final lib = context.read<LibraryProvider>();
+ PlayerSettings.getHideEbookOnly().then((v) {
+ if (mounted) setState(() => _hideEbookOnly = v);
+ });
+ PlayerSettings.settingsChanged.addListener(_onSettingsChanged);
+ if (lib.selectedLibraryId != null) {
+ _loadPage();
+ _loadGenres();
+ } else {
+ lib.addListener(_onLibraryChanged);
+ }
+ }
+
+ void _onSettingsChanged() {
+ PlayerSettings.getHideEbookOnly().then((v) {
+ if (mounted && v != _hideEbookOnly) {
+ _loadGeneration++;
+ setState(() {
+ _hideEbookOnly = v;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ }
+ });
+ }
+
+ void _onLibraryChanged() {
+ final lib = context.read<LibraryProvider>();
+ if (lib.selectedLibraryId != null && _items.isEmpty && !_isLoadingPage) {
+ lib.removeListener(_onLibraryChanged);
+ _loadPage();
+ _loadGenres();
+ }
+ }
+
+ Future<void> _loadGenres() async {
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) return;
+ final filterData = await api.getLibraryFilterData(lib.selectedLibraryId!);
+ if (filterData != null && mounted) {
+ final genres = filterData['genres'] as List<dynamic>? ?? [];
+ setState(() {
+ _availableGenres = genres.map((g) => g is Map ? (g['name'] as String? ?? '') : g.toString()).where((g) => g.isNotEmpty).toList()..sort();
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ _debounce?.cancel();
+ _searchController.dispose();
+ _focusNode.dispose();
+ _scrollController.dispose();
+ PlayerSettings.settingsChanged.removeListener(_onSettingsChanged);
+ try {
+ final lib = context.read<LibraryProvider>();
+ lib.removeListener(_onLibraryChanged);
+ lib.removeListener(_onLibraryProviderChanged);
+ } catch (_) {}
+ super.dispose();
+ }
+
+ // ── Scroll-based pagination ──
+ void _onScroll() {
+ if (_isInSearchMode) return;
+ if (_scrollController.position.pixels >=
+ _scrollController.position.maxScrollExtent - 400) {
+ _loadPage();
+ }
+ }
+
+ // ── Load a page of items ──
+ Future<void> _loadPage() async {
+ if (_isLoadingPage || !_hasMore) return;
+ setState(() => _isLoadingPage = true);
+ final gen = ++_loadGeneration;
+
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) {
+ setState(() => _isLoadingPage = false);
+ return;
+ }
+
+ String sort;
+ int desc;
+ switch (_sort) {
+ case LibrarySort.recentlyAdded:
+ sort = 'addedAt'; desc = _sortAsc ? 0 : 1; break;
+ case LibrarySort.alphabetical:
+ sort = 'media.metadata.title'; desc = _sortAsc ? 0 : 1; break;
+ case LibrarySort.authorName:
+ sort = 'media.metadata.authorNameLF'; desc = _sortAsc ? 0 : 1; break;
+ case LibrarySort.publishedYear:
+ sort = 'media.metadata.publishedYear'; desc = _sortAsc ? 0 : 1; break;
+ case LibrarySort.duration:
+ sort = 'media.duration'; desc = _sortAsc ? 0 : 1; break;
+ case LibrarySort.random:
+ sort = 'addedAt'; desc = 1; break;
+ }
+
+ String? filter;
+ if (_filter == LibraryFilter.inProgress) {
+ filter = 'progress.${base64Encode(utf8.encode('in-progress'))}';
+ } else if (_filter == LibraryFilter.finished) {
+ filter = 'progress.${base64Encode(utf8.encode('finished'))}';
+ } else if (_filter == LibraryFilter.notStarted) {
+ filter = 'progress.${base64Encode(utf8.encode('not-started'))}';
+ } else if (_filter == LibraryFilter.hasEbook) {
+ filter = 'ebooks.${base64Encode(utf8.encode('ebook'))}';
+ } else if (_filter == LibraryFilter.genre && _genreFilter != null) {
+ filter = 'genres.${base64Encode(utf8.encode(_genreFilter!))}';
+ }
+ // Downloaded filter is client-side — handled after loading
+
+ final useClientFilter = _filter == LibraryFilter.downloaded;
+ final limit = (_sort == LibrarySort.random || useClientFilter) ? 1000 : _pageSize;
+
+ final result = await api.getLibraryItems(
+ lib.selectedLibraryId!,
+ page: (_sort == LibrarySort.random || useClientFilter) ? 0 : _page,
+ limit: limit,
+ sort: sort,
+ desc: desc,
+ filter: filter,
+ );
+
+ if (result != null && mounted && gen == _loadGeneration) {
+ final results = (result['results'] as List<dynamic>?) ?? [];
+ final total = (result['total'] as int?) ?? 0;
+ setState(() {
+ _totalItems = total;
+ for (final r in results) {
+ if (r is Map<String, dynamic>) {
+ // Client-side downloaded filter
+ if (_filter == LibraryFilter.downloaded) {
+ final id = r['id'] as String? ?? '';
+ if (!DownloadService().isDownloaded(id)) continue;
+ }
+ if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;
+ _items.add(r);
+ }
+ }
+ if (_sort == LibrarySort.random) {
+ _items.shuffle(Random(_randomSeed));
+ _hasMore = false;
+ } else if (useClientFilter) {
+ _hasMore = false; // All loaded and filtered at once
+ } else {
+ _page++;
+ _hasMore = _items.length < total;
+ }
+ _isLoadingPage = false;
+ });
+ } else if (mounted && gen == _loadGeneration) {
+ setState(() => _isLoadingPage = false);
+ }
+ }
+
+ // ── Change sort and reload ──
+ void _changeSort(LibrarySort newSort) {
+ if (newSort == _sort) {
+ // Tapping the same sort toggles direction (except Random)
+ if (newSort == LibrarySort.random) return;
+ setState(() {
+ _sortAsc = !_sortAsc;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ return;
+ }
+ setState(() {
+ _sort = newSort;
+ // Smart defaults: A-Z and Length start ascending, others start descending
+ _sortAsc = newSort == LibrarySort.alphabetical || newSort == LibrarySort.authorName || newSort == LibrarySort.duration;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ if (newSort == LibrarySort.random) {
+ _randomSeed = Random().nextInt(100000);
+ }
+ });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ }
+
+ // ── Change filter and reload ──
+ void _changeFilter(LibraryFilter newFilter, {String? genre}) {
+ final effective = (newFilter == _filter && genre == _genreFilter) ? LibraryFilter.none : newFilter;
+ if (effective == _filter && genre == _genreFilter) return;
+ _loadGeneration++;
+ setState(() {
+ _filter = effective;
+ _genreFilter = effective == LibraryFilter.genre ? genre : null;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ }
+
+ // ── Search ──
+ void _onSearchChanged(String query) {
+ _debounce?.cancel();
+ if (query.trim().isEmpty) {
+ setState(() {
+ _searchBookResults = [];
+ _searchSeriesResults = [];
+ _searchAuthorResults = [];
+ _hasSearched = false;
+ _isSearching = false;
+ });
+ return;
+ }
+ _debounce = Timer(const Duration(milliseconds: 400), () {
+ _performSearch(query.trim());
+ });
+ }
+
+ Future<void> _performSearch(String query) async {
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) return;
+
+ setState(() => _isSearching = true);
+
+ final result = await api.searchLibrary(lib.selectedLibraryId!, query);
+ if (result != null && mounted) {
+ setState(() {
+ _searchBookResults = (result['book'] as List<dynamic>?) ?? [];
+ if (_hideEbookOnly) {
+ _searchBookResults = _searchBookResults.where((r) {
+ final item = r['libraryItem'] as Map<String, dynamic>? ?? r as Map<String, dynamic>;
+ return !PlayerSettings.isEbookOnly(item);
+ }).toList();
+ }
+ _searchSeriesResults = (result['series'] as List<dynamic>?) ?? [];
+ _searchAuthorResults = (result['authors'] as List<dynamic>?) ?? [];
+ _isSearching = false;
+ _hasSearched = true;
+ });
+ } else if (mounted) {
+ setState(() {
+ _isSearching = false;
+ _hasSearched = true;
+ });
+ }
+ }
+
+ void _showLibraryPicker(BuildContext context, ColorScheme cs, TextTheme tt, List<dynamic> allLibraries, LibraryProvider lib) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) {
+ final bottomPad = MediaQuery.of(ctx).viewPadding.bottom;
+ return Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(ctx).size.height * 0.6),
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox(height: 12),
+ Center(child: Container(width: 40, height: 4,
+ decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)))),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Text('Select Library', style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
+ ),
+ const SizedBox(height: 12),
+ Flexible(
+ child: ListView.builder(
+ shrinkWrap: true,
+ padding: EdgeInsets.only(bottom: bottomPad + 16),
+ itemCount: allLibraries.length,
+ itemBuilder: (_, i) {
+ final library = allLibraries[i] as Map<String, dynamic>;
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? 'Library';
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+ return ListTile(
+ leading: Icon(mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded,
+ color: isSelected ? cs.primary : cs.onSurfaceVariant),
+ title: Text(name),
+ trailing: isSelected
+ ? Icon(Icons.check_circle_rounded, color: cs.primary)
+ : null,
+ selected: isSelected,
+ onTap: () {
+ Navigator.pop(ctx);
+ if (!isSelected) lib.selectLibrary(id);
+ },
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ String get _sortLabel => switch (_sort) {
+ LibrarySort.recentlyAdded => 'Date Added',
+ LibrarySort.alphabetical => 'Title',
+ LibrarySort.authorName => 'Author',
+ LibrarySort.publishedYear => 'Year',
+ LibrarySort.duration => 'Duration',
+ LibrarySort.random => 'Random',
+ };
+
+ String get _filterLabel => switch (_filter) {
+ LibraryFilter.inProgress => 'In Progress',
+ LibraryFilter.finished => 'Finished',
+ LibraryFilter.notStarted => 'Not Started',
+ LibraryFilter.downloaded => 'Downloaded',
+ LibraryFilter.hasEbook => 'eBooks',
+ LibraryFilter.genre => _genreFilter ?? 'Genre',
+ LibraryFilter.none => '',
+ };
+
+ void _showSortFilterSheet(BuildContext context, ColorScheme cs, TextTheme tt, {int initialTab = 0}) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => _SortFilterSheet(
+ currentSort: _sort,
+ sortAsc: _sortAsc,
+ currentFilter: _filter,
+ genreFilter: _genreFilter,
+ availableGenres: _availableGenres,
+ initialTab: initialTab,
+ cs: cs, tt: tt,
+ onSortChanged: (sort) { Navigator.pop(ctx); _changeSort(sort); },
+ onSortDirectionToggled: () {
+ setState(() { _sortAsc = !_sortAsc; _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ Navigator.pop(ctx);
+ },
+ onFilterChanged: (filter, {String? genre}) { Navigator.pop(ctx); _changeFilter(filter, genre: genre); },
+ onClearFilter: () { Navigator.pop(ctx); _changeFilter(LibraryFilter.none); },
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final allLibraries = lib.libraries;
+ final hasMultipleLibraries = allLibraries.length > 1;
+ final libraryName = lib.selectedLibrary?['name'] as String? ?? 'Library';
+
+ return Scaffold(
+ floatingActionButton: _isInSearchMode ? null : ClipRRect(
+ borderRadius: BorderRadius.circular(24),
+ child: BackdropFilter(
+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
+ child: GestureDetector(
+ onTap: () => _showSortFilterSheet(context, cs, tt),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.surface.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(_filter != LibraryFilter.none ? Icons.filter_list_rounded : Icons.tune_rounded, size: 16, color: cs.primary),
+ const SizedBox(width: 6),
+ Text(
+ _filter != LibraryFilter.none ? 'Sort & Filter ●' : 'Sort & Filter',
+ style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.primary),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
+ body: SafeArea(
+ child: Column(
+ children: [
+ AbsorbPageHeader(
+ title: 'Library',
+ actions: hasMultipleLibraries ? [
+ GestureDetector(
+ onTap: () => _showLibraryPicker(context, cs, tt, allLibraries, lib),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(lib.isPodcastLibrary ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 14, color: cs.onSurfaceVariant),
+ const SizedBox(width: 6),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 140),
+ child: Text(libraryName, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant),
+ overflow: TextOverflow.ellipsis, maxLines: 1),
+ ),
+ const SizedBox(width: 4),
+ Icon(Icons.unfold_more_rounded, size: 14, color: cs.onSurfaceVariant),
+ ],
+ ),
+ ),
+ ),
+ ] : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: SearchBar(
+ controller: _searchController,
+ focusNode: _focusNode,
+ hintText: 'Search books, series, and authors...',
+ leading: const Padding(
+ padding: EdgeInsets.only(left: 8),
+ child: Icon(Icons.search_rounded),
+ ),
+ trailing: [
+ if (_searchController.text.isNotEmpty)
+ IconButton(
+ icon: const Icon(Icons.clear_rounded),
+ onPressed: () {
+ _searchController.clear();
+ _onSearchChanged('');
+ _focusNode.unfocus();
+ },
+ ),
+ ],
+ onChanged: _onSearchChanged,
+ padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 8)),
+ ),
+ ),
+
+ if (!_isInSearchMode)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
+ child: Row(
+ children: [
+ GestureDetector(
+ onTap: () => _showSortFilterSheet(context, cs, tt, initialTab: 0),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),
+ const SizedBox(width: 4),
+ Text(_sortLabel, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.primary)),
+ const SizedBox(width: 2),
+ if (_sort != LibrarySort.random)
+ Icon(_sortAsc ? Icons.arrow_upward_rounded : Icons.arrow_downward_rounded, size: 12, color: cs.primary),
+ ],
+ ),
+ ),
+ ),
+ if (_filter != LibraryFilter.none) ...[
+ const SizedBox(width: 8),
+ Flexible(
+ child: GestureDetector(
+ onTap: () => _showSortFilterSheet(context, cs, tt, initialTab: 1),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.tertiary.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.filter_list_rounded, size: 14, color: cs.tertiary),
+ const SizedBox(width: 4),
+ Flexible(
+ child: Text(_filterLabel, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.tertiary), overflow: TextOverflow.ellipsis, maxLines: 1),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: () => _changeFilter(LibraryFilter.none),
+ child: Icon(Icons.close_rounded, size: 14, color: cs.tertiary),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ const Spacer(),
+ Text('${_items.length}${_totalItems > 0 ? '/$_totalItems' : ''} books',
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ ],
+ ),
+ ),
+
+ Expanded(
+ child: _isInSearchMode
+ ? _buildSearchResults(cs, tt)
+ : _buildGrid(cs, tt),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ // ── Pull-to-refresh ──
+ Future<void> _refreshAll() async {
+ final lib = context.read<LibraryProvider>();
+ await lib.refresh();
+ setState(() {
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ if (_sort == LibrarySort.random) {
+ _randomSeed = Random(_randomSeed).nextInt(100000);
+ }
+ });
+ await _loadPage();
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // BROWSE GRID
+ // ═══════════════════════════════════════════════════════════════
+ Widget _buildGrid(ColorScheme cs, TextTheme tt) {
+ if (_items.isEmpty && _isLoadingPage) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (_items.isEmpty && !_isLoadingPage) {
+ final filterMsg = switch (_filter) {
+ LibraryFilter.inProgress => 'No books in progress',
+ LibraryFilter.finished => 'No finished books',
+ LibraryFilter.notStarted => 'All books have been started',
+ LibraryFilter.downloaded => 'No downloaded books',
+ LibraryFilter.hasEbook => 'No books with eBooks',
+ LibraryFilter.genre => 'No books in "${_genreFilter ?? 'genre'}"',
+ LibraryFilter.none => 'No books found',
+ };
+ return RefreshIndicator(
+ onRefresh: _refreshAll,
+ child: CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ SliverFillRemaining(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.library_books_outlined,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(filterMsg,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ if (_filter != LibraryFilter.none) ...[
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: () => _changeFilter(LibraryFilter.none),
+ child: Text('Clear filter',
+ style: tt.bodySmall?.copyWith(color: cs.primary)),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ return RefreshIndicator(
+ onRefresh: _refreshAll,
+ child: GridView.builder(
+ controller: _scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ childAspectRatio: 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ ),
+ itemCount: _items.length + (_hasMore ? 1 : 0),
+ itemBuilder: (context, index) {
+ if (index >= _items.length) {
+ // Loading indicator at the end
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ return _GridBookTile(item: _items[index]);
+ },
+ ),
+ );
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // SEARCH RESULTS
+ // ═══════════════════════════════════════════════════════════════
+ Widget _buildSearchResults(ColorScheme cs, TextTheme tt) {
+ if (_isSearching) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (!_hasSearched) {
+ return const SizedBox.shrink();
+ }
+ if (_searchBookResults.isEmpty && _searchSeriesResults.isEmpty && _searchAuthorResults.isEmpty) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.search_off_rounded, size: 48, color: cs.onSurfaceVariant),
+ const SizedBox(height: 12),
+ Text('No results found',
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ );
+ }
+
+ final auth = context.read<AuthProvider>();
+
+ return ListView(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
+ children: [
+ // ─── BOOKS (only title matches) ───
+ if (_searchBookResults.isNotEmpty) ...[
+ ...() {
+ final query = _searchController.text.trim().toLowerCase();
+ final titleMatches = _searchBookResults.where((result) {
+ final item = result['libraryItem'] as Map<String, dynamic>? ?? {};
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = (metadata['title'] as String? ?? '').toLowerCase();
+ return title.contains(query);
+ }).toList();
+ if (titleMatches.isEmpty) return <Widget>[];
+ return <Widget>[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
+ child: Text('Books',
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ),
+ ...titleMatches.map((result) {
+ final item =
+ result['libraryItem'] as Map<String, dynamic>? ?? {};
+ return _BookResultTile(
+ item: item,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ];
+ }(),
+ ],
+
+ // ─── SERIES ───
+ if (_searchSeriesResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4, _searchBookResults.isNotEmpty ? 20 : 8, 4, 8),
+ child: Text('Series',
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ),
+ ..._searchSeriesResults.map((result) {
+ final seriesData =
+ result['series'] as Map<String, dynamic>? ?? {};
+ final books = result['books'] as List<dynamic>? ?? [];
+ return _SeriesResultCard(
+ series: seriesData,
+ books: books,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ],
+
+ // ─── AUTHORS ───
+ if (_searchAuthorResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4, (_searchBookResults.isNotEmpty || _searchSeriesResults.isNotEmpty) ? 20 : 8, 4, 8),
+ child: Text('Authors',
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ),
+ ..._searchAuthorResults.map((result) {
+ final authorData =
+ result['author'] as Map<String, dynamic>? ?? result as Map<String, dynamic>;
+ return _AuthorResultTile(
+ author: authorData,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ],
+ ],
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Sort & Filter bottom sheet with tabs
+// ═══════════════════════════════════════════════════════════════
+class _SortFilterSheet extends StatefulWidget {
+ final LibrarySort currentSort;
+ final bool sortAsc;
+ final LibraryFilter currentFilter;
+ final String? genreFilter;
+ final List<String> availableGenres;
+ final int initialTab;
+ final ColorScheme cs;
+ final TextTheme tt;
+ final void Function(LibrarySort) onSortChanged;
+ final VoidCallback onSortDirectionToggled;
+ final void Function(LibraryFilter, {String? genre}) onFilterChanged;
+ final VoidCallback onClearFilter;
+
+ const _SortFilterSheet({
+ required this.currentSort, required this.sortAsc,
+ required this.currentFilter, this.genreFilter,
+ required this.availableGenres, required this.initialTab,
+ required this.cs, required this.tt,
+ required this.onSortChanged, required this.onSortDirectionToggled,
+ required this.onFilterChanged, required this.onClearFilter,
+ });
+
+ @override
+ State<_SortFilterSheet> createState() => _SortFilterSheetState();
+}
+
+class _SortFilterSheetState extends State<_SortFilterSheet> with SingleTickerProviderStateMixin {
+ late TabController _tabCtrl;
+ bool _genreExpanded = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _tabCtrl = TabController(length: 2, vsync: this, initialIndex: widget.initialTab);
+ if (widget.currentFilter == LibraryFilter.genre) _genreExpanded = true;
+ }
+
+ @override
+ void dispose() { _tabCtrl.dispose(); super.dispose(); }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = widget.cs;
+ return Container(
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox(height: 12),
+ Center(child: Container(width: 40, height: 4,
+ decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)))),
+ const SizedBox(height: 16),
+ TabBar(
+ controller: _tabCtrl,
+ labelColor: cs.primary, unselectedLabelColor: cs.onSurfaceVariant,
+ indicatorColor: cs.primary, indicatorSize: TabBarIndicatorSize.label,
+ dividerColor: Colors.transparent,
+ tabs: [
+ Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.sort_rounded, size: 18), const SizedBox(width: 6), const Text('Sort')])),
+ Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.filter_list_rounded, size: 18), const SizedBox(width: 6),
+ Text(widget.currentFilter != LibraryFilter.none ? 'Filter ●' : 'Filter')])),
+ ],
+ ),
+ SizedBox(
+ height: _genreExpanded ? 420 : 320,
+ child: TabBarView(controller: _tabCtrl, children: [
+ _buildSortTab(cs), _buildFilterTab(cs)]),
+ ),
+ SizedBox(height: MediaQuery.of(context).viewPadding.bottom + 8),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildSortTab(ColorScheme cs) {
+ final sorts = <(LibrarySort, String, IconData)>[
+ (LibrarySort.recentlyAdded, 'Date Added', Icons.schedule_rounded),
+ (LibrarySort.alphabetical, 'Title', Icons.sort_by_alpha_rounded),
+ (LibrarySort.authorName, 'Author', Icons.person_rounded),
+ (LibrarySort.publishedYear, 'Published Year', Icons.calendar_today_rounded),
+ (LibrarySort.duration, 'Duration', Icons.timelapse_rounded),
+ (LibrarySort.random, 'Random', Icons.shuffle_rounded),
+ ];
+ return ListView(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ children: sorts.map((s) {
+ final (sort, label, icon) = s;
+ final selected = sort == widget.currentSort;
+ return _SheetOption(
+ icon: icon, label: label, selected: selected, selectedColor: cs.primary,
+ trailing: selected && sort != LibrarySort.random
+ ? GestureDetector(
+ onTap: widget.onSortDirectionToggled,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(12)),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(widget.sortAsc ? Icons.arrow_upward_rounded : Icons.arrow_downward_rounded, size: 14, color: cs.primary),
+ const SizedBox(width: 4),
+ Text(widget.sortAsc ? 'ASC' : 'DESC', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: cs.primary)),
+ ]),
+ ),
+ ) : null,
+ onTap: () => widget.onSortChanged(sort),
+ );
+ }).toList(),
+ );
+ }
+
+ Widget _buildFilterTab(ColorScheme cs) {
+ final filters = <(LibraryFilter, String, IconData)>[
+ (LibraryFilter.inProgress, 'In Progress', Icons.play_circle_outline_rounded),
+ (LibraryFilter.finished, 'Finished', Icons.check_circle_outline_rounded),
+ (LibraryFilter.notStarted, 'Not Started', Icons.circle_outlined),
+ (LibraryFilter.downloaded, 'Downloaded', Icons.download_done_rounded),
+ (LibraryFilter.hasEbook, 'eBooks', Icons.menu_book_rounded),
+ ];
+ return ListView(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ children: [
+ if (widget.currentFilter != LibraryFilter.none)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: GestureDetector(
+ onTap: widget.onClearFilter,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(color: cs.errorContainer.withValues(alpha: 0.4), borderRadius: BorderRadius.circular(14)),
+ child: Row(children: [
+ Icon(Icons.clear_rounded, size: 18, color: cs.error),
+ const SizedBox(width: 10),
+ Text('Clear Filter', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: cs.error)),
+ ]),
+ ),
+ ),
+ ),
+ ...filters.map((f) {
+ final (filter, label, icon) = f;
+ return _SheetOption(
+ icon: icon, label: label,
+ selected: filter == widget.currentFilter, selectedColor: cs.tertiary,
+ onTap: () => widget.onFilterChanged(filter),
+ );
+ }),
+ _SheetOption(
+ icon: Icons.category_rounded,
+ label: 'Genre',
+ selected: widget.currentFilter == LibraryFilter.genre,
+ selectedColor: cs.tertiary,
+ trailing: Icon(_genreExpanded ? Icons.expand_less_rounded : Icons.expand_more_rounded, size: 20, color: cs.onSurfaceVariant),
+ onTap: () => setState(() => _genreExpanded = !_genreExpanded),
+ ),
+ if (_genreExpanded)
+ Padding(
+ padding: const EdgeInsets.only(left: 16),
+ child: widget.availableGenres.isEmpty
+ ? Padding(padding: const EdgeInsets.all(12),
+ child: Text('No genres found', style: TextStyle(fontSize: 12, color: cs.onSurfaceVariant)))
+ : Column(children: widget.availableGenres.map((genre) {
+ final selected = widget.currentFilter == LibraryFilter.genre && widget.genreFilter == genre;
+ return _SheetOption(
+ icon: Icons.label_outline_rounded, label: genre,
+ selected: selected, selectedColor: cs.tertiary,
+ compact: true, marquee: true,
+ onTap: () => widget.onFilterChanged(LibraryFilter.genre, genre: genre),
+ );
+ }).toList()),
+ ),
+ ],
+ );
+ }
+}
+
+class _SheetOption extends StatelessWidget {
+ final IconData icon;
+ final String label;
+ final bool selected;
+ final Color selectedColor;
+ final Widget? trailing;
+ final VoidCallback onTap;
+ final bool compact;
+ final bool marquee;
+
+ const _SheetOption({
+ required this.icon, required this.label, required this.selected,
+ required this.selectedColor, this.trailing, required this.onTap,
+ this.compact = false, this.marquee = false,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final vPad = compact ? 8.0 : 10.0;
+ final fontSize = compact ? 13.0 : 14.0;
+ final iconSize = compact ? 18.0 : 20.0;
+
+ return GestureDetector(
+ onTap: onTap,
+ child: Container(
+ padding: EdgeInsets.symmetric(horizontal: 14, vertical: vPad),
+ margin: EdgeInsets.only(bottom: compact ? 2 : 4),
+ decoration: BoxDecoration(
+ color: selected ? selectedColor.withValues(alpha: 0.12) : Colors.transparent,
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Row(children: [
+ Icon(icon, size: iconSize, color: selected ? selectedColor : cs.onSurfaceVariant),
+ const SizedBox(width: 12),
+ Expanded(
+ child: marquee
+ ? _MarqueeText(text: label, style: TextStyle(
+ fontSize: fontSize,
+ fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
+ color: selected ? selectedColor : cs.onSurface))
+ : Text(label, style: TextStyle(
+ fontSize: fontSize,
+ fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
+ color: selected ? selectedColor : cs.onSurface)),
+ ),
+ if (trailing != null) trailing!,
+ if (selected && trailing == null)
+ Icon(Icons.check_rounded, size: 18, color: selectedColor),
+ ]),
+ ),
+ );
+ }
+}
+
+class _MarqueeText extends StatefulWidget {
+ final String text;
+ final TextStyle style;
+ const _MarqueeText({required this.text, required this.style});
+ @override
+ State<_MarqueeText> createState() => _MarqueeTextState();
+}
+
+class _MarqueeTextState extends State<_MarqueeText> {
+ late final ScrollController _sc;
+ Timer? _timer;
+
+ @override
+ void initState() {
+ super.initState();
+ _sc = ScrollController();
+ WidgetsBinding.instance.addPostFrameCallback((_) => _checkAndScroll());
+ }
+
+ void _checkAndScroll() {
+ if (!_sc.hasClients || _sc.position.maxScrollExtent <= 0) return;
+ _timer?.cancel();
+ _timer = Timer(const Duration(seconds: 1), () {
+ if (!mounted || !_sc.hasClients) return;
+ final max = _sc.position.maxScrollExtent;
+ _sc.animateTo(max, duration: Duration(milliseconds: (max * 30).round().clamp(1000, 5000)), curve: Curves.linear).then((_) {
+ if (!mounted) return;
+ Future.delayed(const Duration(seconds: 1), () {
+ if (!mounted || !_sc.hasClients) return;
+ _sc.animateTo(0, duration: const Duration(milliseconds: 500), curve: Curves.easeOut).then((_) {
+ if (mounted) _checkAndScroll();
+ });
+ });
+ });
+ });
+ }
+
+ @override
+ void dispose() { _timer?.cancel(); _sc.dispose(); super.dispose(); }
+
+ @override
+ Widget build(BuildContext context) {
+ return SingleChildScrollView(
+ controller: _sc, scrollDirection: Axis.horizontal,
+ physics: const NeverScrollableScrollPhysics(),
+ child: Text(widget.text, style: widget.style, maxLines: 1),
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Grid book tile (cover + title + author)
+// ═══════════════════════════════════════════════════════════════
+class _GridBookTile extends StatefulWidget {
+ final Map<String, dynamic> item;
+
+ const _GridBookTile({required this.item});
+
+ @override
+ State<_GridBookTile> createState() => _GridBookTileState();
+}
+
+class _GridBookTileState extends State<_GridBookTile> {
+ final _dl = DownloadService();
+
+ @override
+ void initState() {
+ super.initState();
+ _dl.addListener(_rebuild);
+ }
+
+ @override
+ void dispose() {
+ _dl.removeListener(_rebuild);
+ super.dispose();
+ }
+
+ void _rebuild() {
+ if (mounted) setState(() {});
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ final itemId = widget.item['id'] as String? ?? '';
+ final media = widget.item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+ final progress = lib.getProgress(itemId);
+ final isDownloaded = _dl.isDownloaded(itemId);
+ final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
+
+ return GestureDetector(
+ onTap: () {
+ if (itemId.isNotEmpty) {
+ if (lib.isPodcastLibrary) {
+ EpisodeListSheet.show(context, widget.item);
+ } else {
+ showBookDetailSheet(context, itemId);
+ }
+ }
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Cover — 1:1 square
+ AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ // Cover image
+ coverUrl != null
+ ? coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : CachedNetworkImage(
+ imageUrl: coverUrl,
+ fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ )
+ : _placeholder(cs),
+
+ // Progress bar at bottom of cover
+ if (progress > 0 && !isFinished)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+
+ // ── Banners ──
+ if (isFinished || isDownloaded)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6, vertical: 3),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.85),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (isFinished) ...[
+ Icon(Icons.check_circle_rounded,
+ size: 10, color: Colors.greenAccent[400]),
+ const SizedBox(width: 3),
+ Text('Done',
+ style: TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ color: Colors.greenAccent[400])),
+ ],
+ if (isFinished && isDownloaded)
+ const SizedBox(width: 6),
+ if (isDownloaded) ...[
+ Icon(Icons.download_done_rounded,
+ size: 10, color: cs.primary),
+ const SizedBox(width: 3),
+ Text('Saved',
+ style: TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ color: cs.primary)),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 5),
+ // Title
+ Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ fontSize: 11,
+ ),
+ ),
+ // Author
+ if (author.isNotEmpty)
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontSize: 10,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.headphones_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ),
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Author result tile
+// ═══════════════════════════════════════════════════════════════
+class _AuthorResultTile extends StatelessWidget {
+ final Map<String, dynamic> author;
+ final String? serverUrl;
+ final String? token;
+
+ const _AuthorResultTile({
+ required this.author,
+ required this.serverUrl,
+ required this.token,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final name = author['name'] as String? ?? 'Unknown';
+ final authorId = author['id'] as String? ?? '';
+ final numBooks = author['numBooks'] as int?;
+
+ String? imageUrl;
+ if (authorId.isNotEmpty && serverUrl != null && token != null) {
+ final cleanUrl = serverUrl!.endsWith('/')
+ ? serverUrl!.substring(0, serverUrl!.length - 1)
+ : serverUrl!;
+ imageUrl =
+ '$cleanUrl/api/authors/$authorId/image?width=200&token=$token';
+ }
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _showAuthorBooks(context, authorId, name),
+ borderRadius: BorderRadius.circular(12),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ child: Row(
+ children: [
+ // Author avatar
+ Container(
+ width: 44,
+ height: 44,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: cs.secondaryContainer,
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: imageUrl != null
+ ? CachedNetworkImage(
+ imageUrl: imageUrl,
+ fit: BoxFit.cover,
+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,
+ placeholder: (_, __) => _ph(cs),
+ errorWidget: (_, __, ___) => _ph(cs),
+ )
+ : _ph(cs),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ if (numBooks != null)
+ Text(
+ '$numBooks book${numBooks != 1 ? 's' : ''}',
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _ph(ColorScheme cs) {
+ return Center(
+ child: Icon(Icons.person_rounded,
+ size: 22, color: cs.onSecondaryContainer.withValues(alpha: 0.5)),
+ );
+ }
+
+ void _showAuthorBooks(
+ BuildContext context, String authorId, String authorName) {
+ FocusManager.instance.primaryFocus?.unfocus();
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) return;
+
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ showDragHandle: true,
+ builder: (_) => DraggableScrollableSheet(
+ initialChildSize: 0.7,
+ minChildSize: 0.4,
+ maxChildSize: 0.9,
+ expand: false,
+ builder: (ctx, scrollController) => _AuthorBooksSheet(
+ libraryId: lib.selectedLibraryId!,
+ authorId: authorId,
+ authorName: authorName,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Author books bottom sheet
+// ═══════════════════════════════════════════════════════════════
+class _AuthorBooksSheet extends StatefulWidget {
+ final String libraryId;
+ final String authorId;
+ final String authorName;
+ final String? serverUrl;
+ final String? token;
+ final ScrollController scrollController;
+
+ const _AuthorBooksSheet({
+ required this.libraryId,
+ required this.authorId,
+ required this.authorName,
+ required this.serverUrl,
+ required this.token,
+ required this.scrollController,
+ });
+
+ @override
+ State<_AuthorBooksSheet> createState() => _AuthorBooksSheetState();
+}
+
+class _AuthorBooksSheetState extends State<_AuthorBooksSheet> {
+ List<Map<String, dynamic>> _books = [];
+ bool _isLoading = true;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadBooks();
+ }
+
+ Future<void> _loadBooks() async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+
+ try {
+ // Use audiobookshelf filter: authors.<base64(authorId)>
+ final filterValue = base64Encode(utf8.encode(widget.authorId));
+ final cleanUrl = (auth.serverUrl ?? '').endsWith('/')
+ ? auth.serverUrl!.substring(0, auth.serverUrl!.length - 1)
+ : auth.serverUrl!;
+ final url =
+ '$cleanUrl/api/libraries/${widget.libraryId}/items'
+ '?filter=authors.$filterValue&sort=media.metadata.title&limit=200&collapseseries=0';
+
+ final response = await http.get(
+ Uri.parse(url),
+ headers: {
+ 'Authorization': 'Bearer ${auth.token}',
+ },
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200 && mounted) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final results = (data['results'] as List<dynamic>?) ?? [];
+ setState(() {
+ _books = results.whereType<Map<String, dynamic>>().toList();
+ _isLoading = false;
+ });
+ } else if (mounted) {
+ setState(() => _isLoading = false);
+ }
+ } catch (_) {
+ if (mounted) setState(() => _isLoading = false);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
+ child: Row(
+ children: [
+ Icon(Icons.person_rounded, size: 20, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(widget.authorName,
+ style: tt.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w600)),
+ ),
+ ],
+ ),
+ ),
+ if (_isLoading)
+ const Expanded(
+ child: Center(child: CircularProgressIndicator()))
+ else if (_books.isEmpty)
+ Expanded(
+ child: Center(
+ child: Text('No books found',
+ style: tt.bodyLarge
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ )
+ else
+ Expanded(
+ child: ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: _books.length,
+ itemBuilder: (context, index) {
+ return _BookResultTile(
+ item: _books[index],
+ serverUrl: widget.serverUrl,
+ token: widget.token,
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Search result tiles (carried over from old search_screen)
+// ═══════════════════════════════════════════════════════════════
+class _BookResultTile extends StatelessWidget {
+ final Map<String, dynamic> item;
+ final String? serverUrl;
+ final String? token;
+
+ const _BookResultTile({
+ required this.item,
+ required this.serverUrl,
+ required this.token,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final itemId = item['id'] as String?;
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final authorName = metadata['authorName'] as String? ?? '';
+
+ String? coverUrl;
+ if (itemId != null && serverUrl != null && token != null) {
+ final cleanUrl = serverUrl!.endsWith('/')
+ ? serverUrl!.substring(0, serverUrl!.length - 1)
+ : serverUrl!;
+ coverUrl = '$cleanUrl/api/items/$itemId/cover?width=200&token=$token';
+ }
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () {
+ FocusManager.instance.primaryFocus?.unfocus();
+ if (itemId != null) {
+ final lib = context.read<LibraryProvider>();
+ if (lib.isPodcastLibrary) {
+ EpisodeListSheet.show(context, item);
+ } else {
+ showBookDetailSheet(context, itemId);
+ }
+ }
+ },
+ borderRadius: BorderRadius.circular(12),
+ child: Row(
+ children: [
+ SizedBox(
+ width: 56,
+ height: 56,
+ child: coverUrl != null
+ ? CachedNetworkImage(
+ imageUrl: coverUrl,
+ fit: BoxFit.cover,
+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,
+ placeholder: (_, __) => _ph(cs),
+ errorWidget: (_, __, ___) => _ph(cs),
+ )
+ : _ph(cs),
+ ),
+ Expanded(
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ if (authorName.isNotEmpty)
+ Text(authorName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _ph(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.headphones_rounded,
+ size: 20, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ );
+ }
+}
+
+class _SeriesResultCard extends StatelessWidget {
+ final Map<String, dynamic> series;
+ final List<dynamic> books;
+ final String? serverUrl;
+ final String? token;
+
+ const _SeriesResultCard({
+ required this.series,
+ required this.books,
+ required this.serverUrl,
+ required this.token,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final seriesName = series['name'] as String? ?? 'Unknown Series';
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _showSeriesBooks(context, seriesName),
+ borderRadius: BorderRadius.circular(12),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ child: Row(
+ children: [
+ Container(
+ width: 44,
+ height: 44,
+ decoration: BoxDecoration(
+ color: cs.secondaryContainer,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Center(
+ child: Icon(Icons.auto_stories_rounded,
+ size: 22, color: cs.onSecondaryContainer.withValues(alpha: 0.7)),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(seriesName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ Text(
+ '${books.length} book${books.length != 1 ? 's' : ''}',
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ void _showSeriesBooks(BuildContext context, String seriesName) {
+ showSeriesBooksSheet(
+ context,
+ seriesName: seriesName,
+ seriesId: series['id'] as String?,
+ books: books,
+ serverUrl: serverUrl,
+ token: token,
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Series books bottom sheet
+// ═══════════════════════════════════════════════════════════════
+class _SeriesBooksSheet extends StatefulWidget {
+ final String seriesName;
+ final String? seriesId;
+ final List<dynamic> books;
+ final String? serverUrl;
+ final String? token;
+ final ScrollController scrollController;
+
+ const _SeriesBooksSheet({
+ required this.seriesName,
+ this.seriesId,
+ required this.books,
+ required this.serverUrl,
+ required this.token,
+ required this.scrollController,
+ });
+
+ @override
+ State<_SeriesBooksSheet> createState() => _SeriesBooksSheetState();
+}
+
+class _SeriesBooksSheetState extends State<_SeriesBooksSheet> {
+ List<Map<String, dynamic>> _books = [];
+ bool _isLoading = true;
+
+ @override
+ void initState() {
+ super.initState();
+ // Use passed books as initial data
+ _books = _unwrapBooks(widget.books);
+ _sortBooks();
+ if (_books.isNotEmpty) _isLoading = false;
+ // Fetch full data from API for proper sequence info
+ _fetchFromApi();
+ }
+
+ /// Unwrap ABS format: { libraryItem: {...}, sequence: "1" }
+ /// Move sequence to top level of the item for consistent access.
+ List<Map<String, dynamic>> _unwrapBooks(List<dynamic> raw) {
+ final result = <Map<String, dynamic>>[];
+ for (final b in raw) {
+ if (b is! Map<String, dynamic>) continue;
+ if (b.containsKey('libraryItem') && b['libraryItem'] is Map<String, dynamic>) {
+ final item = Map<String, dynamic>.from(b['libraryItem'] as Map<String, dynamic>);
+ if (b['sequence'] != null) item['sequence'] = b['sequence'];
+ result.add(item);
+ } else {
+ result.add(Map<String, dynamic>.from(b));
+ }
+ }
+ return result;
+ }
+
+ void _sortBooks() {
+ _books.sort((a, b) {
+ final seqA = _getSequence(a);
+ final seqB = _getSequence(b);
+ if (seqA == null && seqB == null) return 0;
+ if (seqA == null) return 1;
+ if (seqB == null) return -1;
+ return seqA.compareTo(seqB);
+ });
+ }
+
+ double? _getSequence(Map<String, dynamic> book) {
+ // Top-level sequence (from unwrapping)
+ final seq = book['sequence'];
+ if (seq != null) {
+ final v = double.tryParse(seq.toString());
+ if (v != null) return v;
+ }
+ // Nested in metadata.series
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final seriesRaw = metadata['series'];
+ if (seriesRaw is List) {
+ for (final s in seriesRaw) {
+ if (s is Map<String, dynamic>) {
+ final v = s['sequence'];
+ if (v != null) {
+ final d = double.tryParse(v.toString());
+ if (d != null) return d;
+ }
+ }
+ }
+ } else if (seriesRaw is Map<String, dynamic>) {
+ final v = seriesRaw['sequence'];
+ if (v != null) {
+ final d = double.tryParse(v.toString());
+ if (d != null) return d;
+ }
+ }
+ final fallback = metadata['seriesSequence'];
+ if (fallback != null) return double.tryParse(fallback.toString());
+ return null;
+ }
+
+ String? _getSequenceString(Map<String, dynamic> book) {
+ final v = _getSequence(book);
+ if (v == null) return null;
+ // Show as int if whole number, otherwise decimal
+ return v == v.roundToDouble() ? v.toInt().toString() : v.toString();
+ }
+
+ Future<void> _fetchFromApi() async {
+ final seriesId = widget.seriesId;
+ if (seriesId == null || seriesId.isEmpty) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+ final lib = context.read<LibraryProvider>();
+ final data = await api.getSeries(seriesId, libraryId: lib.selectedLibraryId);
+ if (data != null && mounted) {
+ final rawBooks = data['books'] ?? data['libraryItems'] ?? [];
+ if (rawBooks is List && rawBooks.isNotEmpty) {
+ final fetched = _unwrapBooks(rawBooks);
+ setState(() {
+ _books = fetched;
+ _sortBooks();
+ _isLoading = false;
+ });
+ return;
+ }
+ }
+ if (mounted) setState(() => _isLoading = false);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ // Calculate time-weighted series progress across all books
+ double totalDuration = 0;
+ double listenedDuration = 0;
+ for (final book in _books) {
+ final bookId = book['id'] as String? ?? '';
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final dur = (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0;
+ final prog = lib.getProgress(bookId);
+ totalDuration += dur;
+ listenedDuration += dur * prog;
+ }
+ final seriesProgress = totalDuration > 0 ? (listenedDuration / totalDuration).clamp(0.0, 1.0) : 0.0;
+ final seriesPercent = (seriesProgress * 100).round();
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 4),
+ child: Row(
+ children: [
+ Icon(Icons.auto_stories_rounded, size: 20, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(widget.seriesName,
+ style: tt.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w600)),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: EdgeInsets.fromLTRB(24, 0, 24, seriesProgress > 0 ? 4 : 12),
+ child: Text(
+ '${_books.length} book${_books.length != 1 ? 's' : ''} in this series',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ if (seriesProgress > 0)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(2),
+ child: LinearProgressIndicator(
+ value: seriesProgress,
+ minHeight: 4,
+ backgroundColor: cs.surfaceContainerHighest,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Text(
+ '$seriesPercent% complete',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (_isLoading && _books.isEmpty)
+ const Expanded(
+ child: Center(child: CircularProgressIndicator()))
+ else if (_books.isEmpty)
+ Expanded(
+ child: Center(
+ child: Text('No books found',
+ style: tt.bodyLarge
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ )
+ else
+ Expanded(
+ child: ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: _books.length,
+ itemBuilder: (context, index) {
+ final book = _books[index];
+ final bookId = book['id'] as String? ?? '';
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata =
+ media['metadata'] as Map<String, dynamic>? ?? {};
+ final bookTitle = metadata['title'] as String? ?? 'Unknown';
+ final authorName = metadata['authorName'] as String? ?? '';
+ final sequence = _getSequenceString(book);
+ final duration = (media['duration'] is num)
+ ? (media['duration'] as num).toDouble()
+ : 0.0;
+
+ final progress = lib.getProgress(bookId);
+ final isFinished = lib.getProgressData(bookId)?['isFinished'] == true;
+ final isDownloaded = DownloadService().isDownloaded(bookId);
+
+ String? coverUrl;
+ if (bookId.isNotEmpty &&
+ widget.serverUrl != null &&
+ widget.token != null) {
+ final cleanUrl = widget.serverUrl!.endsWith('/')
+ ? widget.serverUrl!
+ .substring(0, widget.serverUrl!.length - 1)
+ : widget.serverUrl!;
+ coverUrl =
+ '$cleanUrl/api/items/$bookId/cover?width=400&token=${widget.token}';
+ }
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () {
+ if (bookId.isNotEmpty) {
+ if (lib.isPodcastLibrary) {
+ EpisodeListSheet.show(context, book);
+ } else {
+ showBookDetailSheet(context, bookId);
+ }
+ }
+ },
+ borderRadius: BorderRadius.circular(14),
+ child: Row(
+ children: [
+ // Square cover with sequence badge + status badges
+ SizedBox(
+ width: 80,
+ height: 80,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: coverUrl != null
+ ? CachedNetworkImage(
+ imageUrl: coverUrl,
+ fit: BoxFit.cover,
+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,
+ placeholder: (_, __) =>
+ _placeholder(cs),
+ errorWidget: (_, __, ___) =>
+ _placeholder(cs),
+ )
+ : _placeholder(cs),
+ ),
+ if (sequence != null && sequence.isNotEmpty)
+ Positioned(
+ top: 4,
+ left: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primary,
+ borderRadius:
+ BorderRadius.circular(8),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black
+ .withValues(alpha: 0.3),
+ blurRadius: 4)
+ ],
+ ),
+ child: Text('#$sequence',
+ style: TextStyle(
+ color: cs.onPrimary,
+ fontSize: 10,
+ fontWeight: FontWeight.w800)),
+ ),
+ ),
+ // Downloaded badge (top-right)
+ if (isDownloaded)
+ Positioned(
+ top: 4,
+ right: 4,
+ child: Container(
+ padding: const EdgeInsets.all(3),
+ decoration: BoxDecoration(
+ color: Colors.black54,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Icon(Icons.download_done_rounded,
+ size: 12, color: cs.primary),
+ ),
+ ),
+ // Progress bar at bottom
+ if (progress > 0 && !isFinished)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ // Finished overlay
+ if (isFinished)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 4, vertical: 2),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.85),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.check_circle_rounded,
+ size: 10, color: Colors.greenAccent[400]),
+ const SizedBox(width: 3),
+ Text('Done',
+ style: TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ color: Colors.greenAccent[400])),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ // Info
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 14, vertical: 10),
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ mainAxisAlignment:
+ MainAxisAlignment.center,
+ children: [
+ if (sequence != null &&
+ sequence.isNotEmpty)
+ Text('Book $sequence',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w600)),
+ Text(bookTitle,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ if (authorName.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(authorName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant)),
+ ],
+ if (duration > 0) ...[
+ const SizedBox(height: 2),
+ Row(
+ children: [
+ Text(_formatDuration(duration),
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant)),
+ if (progress > 0 && !isFinished) ...[
+ const SizedBox(width: 8),
+ Text('${(progress * 100).round()}%',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w600)),
+ ],
+ ],
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.only(right: 12),
+ child: Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.headphones_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ );
+ }
+
+ String _formatDuration(double seconds) {
+ final h = (seconds / 3600).floor();
+ final m = ((seconds % 3600) / 60).floor();
+ if (h > 0) return '${h}h ${m}m';
+ return '${m}m';
+ }
+}
diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dart
new file mode 100644
index 00000000..8d0e7fd8
--- /dev/null
+++ b/lib/screens/login_screen.dart
@@ -0,0 +1,972 @@
+import 'dart:async';
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+import 'package:provider/provider.dart';
+import 'package:app_links/app_links.dart';
+import '../providers/auth_provider.dart';
+import '../services/api_service.dart';
+import '../services/oidc_service.dart';
+import '../services/user_account_service.dart';
+import '../widgets/absorb_wave_icon.dart';
+
+class LoginScreen extends StatefulWidget {
+ const LoginScreen({super.key});
+
+ @override
+ State<LoginScreen> createState() => _LoginScreenState();
+}
+
+class _LoginScreenState extends State<LoginScreen>
+ with SingleTickerProviderStateMixin {
+ final _formKey = GlobalKey<FormState>();
+ final _serverController = TextEditingController();
+ final _usernameController = TextEditingController();
+ final _passwordController = TextEditingController();
+ final _usernameFocus = FocusNode();
+
+ bool _obscurePassword = true;
+ bool _isConnecting = false;
+ String _protocol = 'https://';
+
+ // Server validation state
+ bool _serverValid = false;
+ bool _serverChecking = false;
+ String? _serverError;
+ Timer? _debounce;
+
+ // Login error
+ String? _loginError;
+
+ // OIDC state
+ OidcConfig? _oidcConfig;
+ bool _isOidcLoading = false;
+ StreamSubscription? _linkSub;
+
+ // Custom headers (advanced)
+ bool _showAdvanced = false;
+ final List<(TextEditingController, TextEditingController)> _headerControllers = [];
+
+ // App version
+ String _appVersion = '';
+
+ late AnimationController _animController;
+ late Animation<double> _fadeAnim;
+ late Animation<double> _slideAnim;
+
+ @override
+ void initState() {
+ super.initState();
+ _animController = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1200),
+ );
+ _fadeAnim = CurvedAnimation(
+ parent: _animController,
+ curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
+ );
+ _slideAnim = CurvedAnimation(
+ parent: _animController,
+ curve: const Interval(0.3, 1.0, curve: Curves.easeOutCubic),
+ );
+ _animController.forward();
+ _serverController.addListener(_onServerChanged);
+ _loadVersion();
+ _initDeepLinkListener();
+ }
+
+ /// Listen for deep links (audiobookshelf://oauth callback).
+ void _initDeepLinkListener() {
+ final appLinks = AppLinks();
+ _linkSub = appLinks.uriLinkStream.listen((uri) {
+ debugPrint('[Login] Deep link received: $uri');
+ if (uri.scheme == 'audiobookshelf' && uri.host == 'oauth') {
+ _handleOidcCallback(uri);
+ }
+ });
+ }
+
+ /// Handle the OIDC callback URI from deep link.
+ Future<void> _handleOidcCallback(Uri uri) async {
+ final oidc = OidcService();
+ if (!oidc.isWaitingForCallback) {
+ debugPrint('[Login] No OIDC flow in progress, ignoring callback');
+ return;
+ }
+
+ setState(() {
+ _isOidcLoading = true;
+ _loginError = null;
+ });
+
+ final result = await oidc.handleCallback(uri);
+ if (result != null && mounted) {
+ final serverText = _serverController.text.trim();
+ final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');
+ final fullUrl = '$_protocol$cleanUrl';
+
+ final auth = context.read<AuthProvider>();
+ final success = await auth.loginWithOidc(
+ serverUrl: fullUrl,
+ result: result,
+ );
+
+ if (mounted) {
+ setState(() => _isOidcLoading = false);
+ if (!success) {
+ setState(() => _loginError = auth.errorMessage ?? 'SSO login failed');
+ } else if (Navigator.of(context).canPop()) {
+ Navigator.of(context).pop();
+ }
+ }
+ } else if (mounted) {
+ setState(() {
+ _isOidcLoading = false;
+ _loginError = 'SSO authentication failed. Please try again.';
+ });
+ }
+ }
+
+ Future<void> _loadVersion() async {
+ try {
+ final info = await PackageInfo.fromPlatform();
+ if (mounted) setState(() => _appVersion = 'v${info.version}');
+ } catch (_) {}
+ }
+
+ @override
+ void dispose() {
+ _debounce?.cancel();
+ _linkSub?.cancel();
+ _animController.dispose();
+ _serverController.dispose();
+ _usernameController.dispose();
+ _passwordController.dispose();
+ _usernameFocus.dispose();
+ for (final (k, v) in _headerControllers) { k.dispose(); v.dispose(); }
+ OidcService().cancel();
+ super.dispose();
+ }
+
+ String _lastValidatedServer = '';
+
+ /// Re-trigger server validation when custom headers change.
+ void _revalidateServer() {
+ if (_serverController.text.trim().isEmpty) return;
+ _lastValidatedServer = ''; // Force re-check
+ _debounce?.cancel();
+ _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());
+ }
+
+ void _onServerChanged() {
+ final text = _serverController.text.trim();
+ if (text.isEmpty) {
+ setState(() {
+ _serverValid = false;
+ _serverChecking = false;
+ _serverError = null;
+ _lastValidatedServer = '';
+ });
+ _debounce?.cancel();
+ return;
+ }
+
+ // Only invalidate if the server text actually changed from what we validated
+ final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');
+ final fullUrl = '$_protocol$cleanUrl';
+ if (fullUrl != _lastValidatedServer) {
+ setState(() {
+ _serverValid = false;
+ _serverChecking = true;
+ _serverError = null;
+ });
+ } else {
+ // Same server, just re-checking — keep fields visible
+ setState(() {
+ _serverChecking = true;
+ _serverError = null;
+ });
+ }
+
+ _debounce?.cancel();
+ _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());
+ }
+
+ Future<void> _checkServer() async {
+ final text = _serverController.text.trim();
+ if (text.isEmpty) return;
+
+ final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');
+ final fullUrl = '$_protocol$cleanUrl';
+
+ try {
+ // Build custom headers for ping
+ final headers = <String, String>{};
+ for (final (keyCtrl, valCtrl) in _headerControllers) {
+ final k = keyCtrl.text.trim();
+ final v = valCtrl.text.trim();
+ if (k.isNotEmpty && v.isNotEmpty) headers[k] = v;
+ }
+
+ final ok = await ApiService.pingServer(fullUrl, customHeaders: headers);
+ if (!mounted) return;
+ if (_serverController.text.trim() != text) return;
+
+ setState(() {
+ _serverChecking = false;
+ _serverValid = ok;
+ _serverError = ok ? null : 'Could not reach server';
+ if (ok) {
+ _lastValidatedServer = fullUrl;
+ } else {
+ _oidcConfig = null;
+ _lastValidatedServer = '';
+ }
+ });
+
+ if (ok) {
+ // Also check if OIDC is available
+ OidcService.checkOidcEnabled(fullUrl).then((config) {
+ if (mounted && _serverController.text.trim() == text) {
+ setState(() => _oidcConfig = config);
+ }
+ });
+
+ Future.delayed(const Duration(milliseconds: 200), () {
+ if (mounted) _usernameFocus.requestFocus();
+ });
+ }
+ } catch (e) {
+ if (!mounted) return;
+ setState(() {
+ _serverChecking = false;
+ _serverValid = false;
+ _serverError = 'Could not reach server';
+ _oidcConfig = null;
+ });
+ }
+ }
+
+ Future<void> _handleLogin() async {
+ if (!_serverValid) return;
+ if (!_formKey.currentState!.validate()) return;
+
+ setState(() {
+ _isConnecting = true;
+ _loginError = null;
+ });
+
+ final auth = context.read<AuthProvider>();
+ final serverText = _serverController.text.trim();
+ final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');
+ final fullUrl = '$_protocol$cleanUrl';
+
+ // Build custom headers map
+ final headers = <String, String>{};
+ for (final (keyCtrl, valCtrl) in _headerControllers) {
+ final k = keyCtrl.text.trim();
+ final v = valCtrl.text.trim();
+ if (k.isNotEmpty && v.isNotEmpty) headers[k] = v;
+ }
+
+ final success = await auth.login(
+ serverUrl: fullUrl,
+ username: _usernameController.text.trim(),
+ password: _passwordController.text,
+ customHeaders: headers,
+ );
+
+ if (mounted) {
+ setState(() => _isConnecting = false);
+
+ if (!success) {
+ setState(() {
+ _loginError = auth.errorMessage ?? 'Login failed';
+ });
+ } else if (Navigator.of(context).canPop()) {
+ // If pushed as a route (e.g. Add Account), pop back
+ Navigator.of(context).pop();
+ }
+ }
+ }
+
+ Future<void> _handleOidcLogin() async {
+ if (!_serverValid) return;
+
+ setState(() {
+ _isOidcLoading = true;
+ _loginError = null;
+ });
+
+ final serverText = _serverController.text.trim();
+ final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');
+ final fullUrl = '$_protocol$cleanUrl';
+
+ final error = await OidcService().startLogin(fullUrl);
+ if (error != null && mounted) {
+ setState(() {
+ _isOidcLoading = false;
+ _loginError = error;
+ });
+ }
+ // If no error, we're waiting for the deep link callback.
+ // _isOidcLoading stays true until callback arrives.
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ body: Container(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ stops: const [0.0, 0.4, 0.7, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.15),
+ cs.primary.withValues(alpha: 0.05),
+ cs.surface,
+ cs.surface,
+ ],
+ ),
+ ),
+ child: SafeArea(
+ child: Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // ── Logo + Tagline ──
+ FadeTransition(
+ opacity: _fadeAnim,
+ child: Column(
+ children: [
+ // Wave icon with glow
+ Container(
+ width: 100,
+ height: 100,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ boxShadow: [
+ BoxShadow(
+ color: cs.primary.withValues(alpha: 0.3),
+ blurRadius: 40,
+ spreadRadius: 8,
+ ),
+ ],
+ ),
+ child: Container(
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: cs.primary.withValues(alpha: 0.1),
+ border: Border.all(
+ color: cs.primary.withValues(alpha: 0.15),
+ width: 1.5,
+ ),
+ ),
+ child: Center(
+ child: AbsorbWaveIcon(
+ size: 44,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 28),
+ Text(
+ 'A B S O R B',
+ style: tt.headlineMedium?.copyWith(
+ fontWeight: FontWeight.w200,
+ color: cs.onSurface,
+ letterSpacing: 10,
+ ),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'Start Absorbing',
+ style: tt.bodyLarge?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),
+ fontWeight: FontWeight.w400,
+ letterSpacing: 0.5,
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 40),
+
+ // ── Glass form card ──
+ SlideTransition(
+ position: Tween<Offset>(
+ begin: const Offset(0, 0.12),
+ end: Offset.zero,
+ ).animate(_slideAnim),
+ child: FadeTransition(
+ opacity: _slideAnim,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(24),
+ child: BackdropFilter(
+ filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
+ child: Container(
+ padding: const EdgeInsets.all(24),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.35),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(
+ color: cs.outlineVariant.withValues(alpha: 0.15),
+ ),
+ ),
+ child: Form(
+ key: _formKey,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Section label
+ Padding(
+ padding: const EdgeInsets.only(left: 4, bottom: 16),
+ child: Text(
+ 'Connect to your server',
+ style: tt.titleSmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ),
+
+ // Server URL
+ _buildInputField(
+ controller: _serverController,
+ label: 'Server address',
+ hint: 'abs.example.com',
+ keyboardType: TextInputType.url,
+ textInputAction: TextInputAction.next,
+ onFieldSubmitted: (_) {
+ if (!_serverValid && !_serverChecking) _checkServer();
+ },
+ cs: cs,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: DropdownButtonHideUnderline(
+ child: DropdownButton<String>(
+ value: _protocol,
+ isDense: true,
+ style: TextStyle(
+ color: cs.primary,
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ ),
+ items: const [
+ DropdownMenuItem(
+ value: 'https://',
+ child: Text('https://'),
+ ),
+ DropdownMenuItem(
+ value: 'http://',
+ child: Text('http://'),
+ ),
+ ],
+ onChanged: (v) {
+ if (v != null) {
+ setState(() {
+ _protocol = v;
+ _serverValid = false;
+ });
+ _onServerChanged();
+ }
+ },
+ ),
+ ),
+ ),
+ suffixIcon: _serverChecking
+ ? const Padding(
+ padding: EdgeInsets.all(14),
+ child: SizedBox(
+ width: 18, height: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ )
+ : _serverValid
+ ? Icon(Icons.check_circle_rounded,
+ color: Colors.green.shade400, size: 22)
+ : _serverError != null
+ ? Icon(Icons.error_outline_rounded,
+ color: cs.error, size: 22)
+ : null,
+ borderColor: _serverValid
+ ? Colors.green.shade400.withValues(alpha: 0.4)
+ : _serverError != null
+ ? cs.error.withValues(alpha: 0.4)
+ : null,
+ errorText: _serverError,
+ ),
+
+ // Advanced: Custom Headers — must be before server validation
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: () => setState(() => _showAdvanced = !_showAdvanced),
+ child: Row(
+ children: [
+ Icon(_showAdvanced ? Icons.expand_less_rounded : Icons.expand_more_rounded,
+ size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ const SizedBox(width: 4),
+ Text('Advanced', style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),
+ ],
+ ),
+ ),
+ if (_showAdvanced) ...[
+ const SizedBox(height: 8),
+ Text('Custom HTTP Headers', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),
+ const SizedBox(height: 4),
+ Text('For Cloudflare tunnels or reverse proxies that require extra headers. Add headers before entering your server URL.',
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),
+ const SizedBox(height: 8),
+ ..._headerControllers.asMap().entries.map((entry) {
+ final i = entry.key;
+ final (keyCtrl, valCtrl) = entry.value;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Row(
+ children: [
+ Expanded(
+ flex: 2,
+ child: TextField(
+ controller: keyCtrl,
+ style: TextStyle(fontSize: 13, color: cs.onSurface),
+ onChanged: (_) => _revalidateServer(),
+ decoration: InputDecoration(
+ hintText: 'Header name',
+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),
+ filled: true,
+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ flex: 3,
+ child: TextField(
+ controller: valCtrl,
+ style: TextStyle(fontSize: 13, color: cs.onSurface),
+ onChanged: (_) => _revalidateServer(),
+ decoration: InputDecoration(
+ hintText: 'Value',
+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),
+ filled: true,
+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ ),
+ ),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: () {
+ setState(() {
+ _headerControllers[i].$1.dispose();
+ _headerControllers[i].$2.dispose();
+ _headerControllers.removeAt(i);
+ });
+ _revalidateServer();
+ },
+ child: Icon(Icons.close_rounded, size: 18, color: cs.error.withValues(alpha: 0.6)),
+ ),
+ ],
+ ),
+ );
+ }),
+ GestureDetector(
+ onTap: () => setState(() {
+ _headerControllers.add((TextEditingController(), TextEditingController()));
+ }),
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.add_rounded, size: 16, color: cs.primary),
+ const SizedBox(width: 4),
+ Text('Add Header', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ ),
+ ],
+
+ // SSO / OIDC button — shown right below server URL so keyboard doesn't hide it
+ AnimatedSize(
+ duration: const Duration(milliseconds: 350),
+ curve: Curves.easeOutCubic,
+ alignment: Alignment.topCenter,
+ child: _serverValid && _oidcConfig != null && _oidcConfig!.enabled
+ ? _buildOidcButton(cs, tt)
+ : const SizedBox.shrink(),
+ ),
+
+ // Credentials — animated in when server is valid
+ AnimatedSize(
+ duration: const Duration(milliseconds: 350),
+ curve: Curves.easeOutCubic,
+ alignment: Alignment.topCenter,
+ child: _serverValid
+ ? _buildCredentialFields(cs, tt)
+ : const SizedBox.shrink(),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+
+ // ── Version label ──
+ const SizedBox(height: 32),
+ FadeTransition(
+ opacity: _fadeAnim,
+ child: Text(
+ _appVersion,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),
+ letterSpacing: 1,
+ ),
+ ),
+ ),
+
+ // ── Saved accounts quick-switch ──
+ _buildSavedAccounts(cs, tt),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildSavedAccounts(ColorScheme cs, TextTheme tt) {
+ final accounts = UserAccountService().accounts;
+ if (accounts.isEmpty) return const SizedBox.shrink();
+
+ return FadeTransition(
+ opacity: _fadeAnim,
+ child: Padding(
+ padding: const EdgeInsets.only(top: 32),
+ child: Column(
+ children: [
+ Row(
+ children: [
+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: Text('saved accounts',
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4))),
+ ),
+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),
+ ],
+ ),
+ const SizedBox(height: 12),
+ ...accounts.map((account) {
+ final shortUrl = account.serverUrl
+ .replaceAll(RegExp(r'^https?://'), '')
+ .replaceAll(RegExp(r'/+$'), '');
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Material(
+ color: cs.surface.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(14),
+ child: InkWell(
+ borderRadius: BorderRadius.circular(14),
+ onTap: () => _quickSwitch(account),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ child: Row(
+ children: [
+ CircleAvatar(
+ radius: 18,
+ backgroundColor: cs.primary.withValues(alpha: 0.15),
+ child: Text(
+ account.username.isNotEmpty
+ ? account.username[0].toUpperCase()
+ : '?',
+ style: TextStyle(
+ color: cs.primary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(account.username,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ Text(shortUrl,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis),
+ ],
+ ),
+ ),
+ Icon(Icons.arrow_forward_ios_rounded,
+ size: 14, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Future<void> _quickSwitch(SavedAccount account) async {
+ setState(() => _isConnecting = true);
+
+ final auth = context.read<AuthProvider>();
+ await auth.switchToAccount(account);
+
+ if (mounted) {
+ setState(() => _isConnecting = false);
+ if (auth.isAuthenticated && Navigator.of(context).canPop()) {
+ Navigator.of(context).pop();
+ }
+ // If this is the root login screen, AuthGate will react to the state change
+ }
+ }
+
+ Widget _buildInputField({
+ required TextEditingController controller,
+ required String label,
+ required ColorScheme cs,
+ String? hint,
+ TextInputType? keyboardType,
+ TextInputAction? textInputAction,
+ FocusNode? focusNode,
+ Widget? prefixIcon,
+ Widget? suffixIcon,
+ Color? borderColor,
+ String? errorText,
+ bool obscureText = false,
+ void Function(String)? onFieldSubmitted,
+ String? Function(String?)? validator,
+ }) {
+ return TextFormField(
+ controller: controller,
+ focusNode: focusNode,
+ keyboardType: keyboardType,
+ textInputAction: textInputAction,
+ obscureText: obscureText,
+ onFieldSubmitted: onFieldSubmitted,
+ validator: validator,
+ style: TextStyle(color: cs.onSurface),
+ decoration: InputDecoration(
+ labelText: label,
+ hintText: hint,
+ prefixIcon: prefixIcon,
+ suffixIcon: suffixIcon,
+ errorText: errorText,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(14),
+ borderSide: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.2)),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(14),
+ borderSide: BorderSide(
+ color: borderColor ?? cs.outlineVariant.withValues(alpha: 0.15),
+ ),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(14),
+ borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.6), width: 1.5),
+ ),
+ filled: true,
+ fillColor: cs.surface.withValues(alpha: 0.4),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
+ ),
+ );
+ }
+
+ Widget _buildOidcButton(ColorScheme cs, TextTheme tt) {
+ return Column(
+ children: [
+ const SizedBox(height: 16),
+ SizedBox(
+ width: double.infinity,
+ height: 52,
+ child: OutlinedButton.icon(
+ onPressed: _isConnecting || _isOidcLoading ? null : _handleOidcLogin,
+ icon: _isOidcLoading
+ ? SizedBox(
+ width: 18, height: 18,
+ child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary),
+ )
+ : Icon(Icons.login_rounded, size: 20, color: cs.primary),
+ label: Text(
+ _isOidcLoading ? 'Waiting for SSO...' : _oidcConfig!.buttonText,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ style: OutlinedButton.styleFrom(
+ side: BorderSide(color: cs.primary.withValues(alpha: 0.3)),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Row(
+ children: [
+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.2))),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: Text('or sign in manually', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.5))),
+ ),
+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.2))),
+ ],
+ ),
+ ],
+ );
+ }
+
+ Widget _buildCredentialFields(ColorScheme cs, TextTheme tt) {
+ return Column(
+ children: [
+ const SizedBox(height: 16),
+
+ // Login error message
+ if (_loginError != null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Container(
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.error.withValues(alpha: 0.1),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.error.withValues(alpha: 0.3)),
+ ),
+ child: Row(
+ children: [
+ Icon(Icons.warning_amber_rounded, size: 18, color: cs.error),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ _loginError!,
+ style: tt.bodySmall?.copyWith(color: cs.error),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+
+ // Username
+ _buildInputField(
+ controller: _usernameController,
+ focusNode: _usernameFocus,
+ label: 'Username',
+ cs: cs,
+ textInputAction: TextInputAction.next,
+ prefixIcon: Icon(Icons.person_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ validator: (v) {
+ if (v == null || v.trim().isEmpty) {
+ return 'Please enter your username';
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 14),
+
+ // Password
+ _buildInputField(
+ controller: _passwordController,
+ label: 'Password',
+ cs: cs,
+ obscureText: _obscurePassword,
+ textInputAction: TextInputAction.done,
+ onFieldSubmitted: (_) => _handleLogin(),
+ prefixIcon: Icon(Icons.lock_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ suffixIcon: IconButton(
+ icon: Icon(
+ _obscurePassword
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined,
+ size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),
+ ),
+ onPressed: () {
+ setState(() => _obscurePassword = !_obscurePassword);
+ },
+ ),
+ validator: (v) {
+ if (v == null || v.isEmpty) {
+ return 'Please enter your password';
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 24),
+
+ // Sign In button
+ SizedBox(
+ width: double.infinity,
+ height: 52,
+ child: FilledButton(
+ onPressed: _isConnecting || _isOidcLoading ? null : _handleLogin,
+ style: FilledButton.styleFrom(
+ backgroundColor: cs.primary,
+ foregroundColor: cs.onPrimary,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14),
+ ),
+ elevation: 0,
+ ),
+ child: AnimatedSwitcher(
+ duration: const Duration(milliseconds: 200),
+ child: _isConnecting
+ ? SizedBox(
+ key: const ValueKey('loading'),
+ width: 22,
+ height: 22,
+ child: CircularProgressIndicator(
+ strokeWidth: 2.5,
+ color: cs.onPrimary,
+ ),
+ )
+ : Text(
+ 'Sign In',
+ key: const ValueKey('text'),
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onPrimary,
+ ),
+ ),
+ ),
+ ),
+ ),
+
+
+ ],
+ );
+ }
+}
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
new file mode 100644
index 00000000..f8cf9920
--- /dev/null
+++ b/lib/screens/settings_screen.dart
@@ -0,0 +1,1609 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:permission_handler/permission_handler.dart';
+import 'package:file_picker/file_picker.dart';
+import 'package:url_launcher/url_launcher.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/download_service.dart';
+import '../services/sleep_timer_service.dart';
+import '../services/user_account_service.dart';
+import '../services/update_checker_service.dart';
+import '../screens/login_screen.dart';
+import '../screens/app_shell.dart';
+import '../screens/admin_screen.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/absorb_slider.dart';
+
+class SettingsScreen extends StatefulWidget {
+ const SettingsScreen({super.key});
+
+ @override
+ State<SettingsScreen> createState() => _SettingsScreenState();
+}
+
+class _SettingsScreenState extends State<SettingsScreen> {
+ AutoRewindSettings _rewindSettings = const AutoRewindSettings();
+ double _defaultSpeed = 1.0;
+ bool _wifiOnlyDownloads = false;
+ bool _showBookSlider = false;
+ bool _speedAdjustedTime = true;
+ int _forwardSkip = 30;
+ int _backSkip = 10;
+ bool _shakeToResetSleep = true;
+ bool _resetSleepOnPause = false;
+ int _shakeAddMinutes = 5;
+ bool _autoContinueSeries = true;
+ bool _hideEbookOnly = false;
+ bool _showGoodreadsButton = false;
+ bool _loaded = false;
+ String _downloadLocationLabel = 'App Internal Storage (Default)';
+ int _totalDownloadSizeBytes = 0;
+ AutoSleepSettings _autoSleepSettings = const AutoSleepSettings();
+ String _appVersion = '';
+
+ @override
+ void initState() {
+ super.initState();
+ _loadSettings();
+ }
+
+ Future<void> _loadSettings() async {
+ final s = await AutoRewindSettings.load();
+ final speed = await PlayerSettings.getDefaultSpeed();
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ final bookSlider = await PlayerSettings.getShowBookSlider();
+ final speedAdj = await PlayerSettings.getSpeedAdjustedTime();
+ final fwd = await PlayerSettings.getForwardSkip();
+ final bk = await PlayerSettings.getBackSkip();
+ final shake = await PlayerSettings.getShakeToResetSleep();
+ final resetOnPause = await PlayerSettings.getResetSleepOnPause();
+ final shakeMins = await PlayerSettings.getShakeAddMinutes();
+ final autoSeries = await PlayerSettings.getAutoContinueSeries();
+ final hideEbook = await PlayerSettings.getHideEbookOnly();
+ final showGoodreads = await PlayerSettings.getShowGoodreadsButton();
+
+ final dlLabel = await DownloadService().downloadLocationLabel;
+ final dlSize = await DownloadService().totalDownloadSize;
+ final autoSleep = await AutoSleepSettings.load();
+ final pkgInfo = await PackageInfo.fromPlatform();
+ if (mounted) setState(() {
+ _rewindSettings = s;
+ _defaultSpeed = speed;
+ _wifiOnlyDownloads = wifiOnly;
+ _showBookSlider = bookSlider;
+ _speedAdjustedTime = speedAdj;
+ _forwardSkip = fwd;
+ _backSkip = bk;
+ _shakeToResetSleep = shake;
+ _resetSleepOnPause = resetOnPause;
+ _shakeAddMinutes = shakeMins;
+ _autoContinueSeries = autoSeries;
+ _hideEbookOnly = hideEbook;
+ _showGoodreadsButton = showGoodreads;
+ _downloadLocationLabel = dlLabel;
+ _totalDownloadSizeBytes = dlSize;
+ _autoSleepSettings = autoSleep;
+ _appVersion = pkgInfo.version;
+ _loaded = true;
+ });
+ }
+
+ Future<void> _saveRewind(AutoRewindSettings s) async {
+ setState(() => _rewindSettings = s);
+ await s.save();
+ }
+
+ void _showTips(BuildContext context, ColorScheme cs, TextTheme tt) {
+ showModalBottomSheet(
+ context: context, isScrollControlled: true, useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => DraggableScrollableSheet(
+ expand: false, initialChildSize: 0.75, maxChildSize: 0.95,
+ builder: (_, sc) => Container(
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: ListView(
+ controller: sc,
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
+ children: [
+ Center(child: Container(
+ width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)),
+ )),
+ Row(children: [
+ Icon(Icons.auto_awesome_rounded, color: cs.primary, size: 24),
+ const SizedBox(width: 10),
+ Text('Tips & Hidden Features', style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
+ ]),
+ const SizedBox(height: 20),
+ _tipCard(cs, tt,
+ icon: Icons.airplanemode_active_rounded,
+ title: 'Offline Mode',
+ desc: 'Tap the airplane button on the Absorbing screen to enter offline mode. This stops syncing, saves data, and only shows your downloaded books. Great for flights or low signal areas.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.stop_rounded,
+ title: 'Stop & Sync',
+ desc: 'The "Stop & Sync" button in the Absorbing header fully stops playback and syncs your progress to the server. Use it when you\'re done listening for the day.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.bookmark_added_rounded,
+ title: 'Quick Bookmarks',
+ desc: 'Long-press the bookmark button on any card to instantly drop a bookmark at your current position without opening the bookmark sheet.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.history_rounded,
+ title: 'Playback History',
+ desc: 'Tap the History button on any card to see a timeline of every play, pause, seek, and speed change. Tap any event to jump back to that position.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.speed_rounded,
+ title: 'Speed-Adjusted Time',
+ desc: 'Time remaining and chapter times automatically adjust based on your playback speed. Listening at 1.5x? The time shown reflects how long it\'ll actually take you.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.auto_stories_rounded,
+ title: 'Series Navigation',
+ desc: 'Tap the series name in any book\'s detail popup to see all books in the series, sorted in reading order with sequence badges on each cover.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.vibration_rounded,
+ title: 'Shake to Extend Sleep',
+ desc: 'If you have a sleep timer running and shake your phone, it\'ll add extra minutes. Configure the amount in Settings under Sleep Timer.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.swipe_rounded,
+ title: 'Swipe Between Books',
+ desc: 'On the Absorbing screen, swipe left and right to switch between your in-progress books. The dots at the top show which book you\'re viewing.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.touch_app_rounded,
+ title: 'Tap to Seek',
+ desc: 'Tap anywhere on the chapter or book progress bar to jump directly to that position. You can also drag the bars for fine-grained control.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.replay_rounded,
+ title: 'Auto-Rewind',
+ desc: 'When you resume after a pause, Absorb automatically rewinds a few seconds so you don\'t lose your place. The rewind amount scales with how long you were away. Configure it in Settings.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.skip_next_rounded,
+ title: 'Auto-Continue Series',
+ desc: 'When you finish a book that\'s part of a series, Absorb can automatically queue up the next book. Enable this in Settings under Playback.',
+ ),
+ _tipCard(cs, tt,
+ icon: Icons.download_rounded,
+ title: 'Download for Offline',
+ desc: 'Tap the download button in any book\'s detail popup to save it for offline listening. Downloaded books are available in offline mode without any internet connection.',
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _tipCard(ColorScheme cs, TextTheme tt, {required IconData icon, required String title, required String desc}) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Container(
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ padding: const EdgeInsets.all(8),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer.withValues(alpha: 0.5),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Icon(icon, size: 20, color: cs.primary),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(desc, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, height: 1.4)),
+ ],
+ )),
+ ],
+ ),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final auth = context.watch<AuthProvider>();
+ final lib = context.watch<LibraryProvider>();
+
+ return Scaffold(
+ body: Container(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.35, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.10),
+ const Color(0xFF121212),
+ const Color(0xFF0E0E0E),
+ ],
+ ),
+ ),
+ child: SafeArea(
+ child: CustomScrollView(
+ slivers: [
+ SliverToBoxAdapter(
+ child: AbsorbPageHeader(
+ title: 'Settings',
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),
+ ),
+ ),
+ SliverToBoxAdapter(
+ child: Column(
+ children: [
+ const SizedBox(height: 8),
+
+ // ── Tips & Tricks ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
+ child: GestureDetector(
+ onTap: () => _showTips(context, cs, tt),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ colors: [cs.primaryContainer, cs.tertiaryContainer],
+ ),
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: Row(
+ children: [
+ Icon(Icons.auto_awesome_rounded, color: cs.onPrimaryContainer, size: 22),
+ const SizedBox(width: 12),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Tips & Hidden Features', style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onPrimaryContainer)),
+ const SizedBox(height: 2),
+ Text('Get the most out of Absorb', style: tt.bodySmall?.copyWith(
+ color: cs.onPrimaryContainer.withValues(alpha: 0.7))),
+ ],
+ )),
+ Icon(Icons.chevron_right_rounded, color: cs.onPrimaryContainer.withValues(alpha: 0.5)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+
+ // ── User Profile ──
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
+ child: Row(
+ children: [
+ CircleAvatar(
+ radius: 28,
+ backgroundColor: cs.primaryContainer,
+ child: Text(
+ (auth.username ?? 'U')[0].toUpperCase(),
+ style: tt.headlineSmall?.copyWith(
+ color: cs.onPrimaryContainer,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(auth.username ?? 'User', style: tt.titleLarge?.copyWith(
+ fontWeight: FontWeight.w700)),
+ const SizedBox(height: 2),
+ Text(
+ auth.serverUrl?.replaceAll(RegExp(r'^https?://'), '').replaceAll(RegExp(r'/+$'), '') ?? '',
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ if (auth.isAdmin)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
+ decoration: BoxDecoration(
+ color: auth.isRoot ? Colors.amber.withValues(alpha: 0.12) : cs.primary.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Text(auth.isRoot ? 'Root Admin' : 'Admin', style: tt.labelSmall?.copyWith(
+ color: auth.isRoot ? Colors.amber : cs.primary, fontWeight: FontWeight.w600, fontSize: 10)),
+ ),
+ ),
+ ],
+ )),
+ ],
+ ),
+ ),
+
+ // ── Admin Controls ──
+ if (auth.isAdmin)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
+ child: Material(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ child: InkWell(
+ borderRadius: BorderRadius.circular(14),
+ onTap: () {
+ Navigator.push(context, MaterialPageRoute(
+ builder: (_) => const AdminScreen(),
+ ));
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(
+ children: [
+ Icon(Icons.admin_panel_settings_rounded, color: cs.primary, size: 22),
+ const SizedBox(width: 14),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Server Admin', style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600)),
+ Text('Manage users, libraries & server settings',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ )),
+ Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+
+ const SizedBox(height: 20),
+
+
+ // ── Playback ──
+ _CollapsibleSection(
+ icon: Icons.play_circle_outline_rounded,
+ title: 'Playback',
+ cs: cs,
+ children: [
+ // Default speed
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Default speed', style: tt.bodyMedium),
+ Text('${_defaultSpeed.toStringAsFixed(2)}x',
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w700, color: cs.primary)),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
+ child: Text('New books start at this speed — each book remembers its own',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),
+ ),
+ AbsorbSlider(
+ value: _defaultSpeed,
+ min: 0.5,
+ max: 3.0,
+ divisions: 25,
+ onChanged: _loaded ? (v) {
+ setState(() => _defaultSpeed = double.parse(v.toStringAsFixed(2)));
+ PlayerSettings.setDefaultSpeed(double.parse(v.toStringAsFixed(2)));
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Wrap(
+ spacing: 6, runSpacing: 4,
+ children: [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0].map((s) {
+ final isActive = (_defaultSpeed - s).abs() < 0.01;
+ return ActionChip(
+ label: Text('${s}x',
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: isActive ? FontWeight.w700 : FontWeight.w400,
+ color: isActive ? cs.onPrimary : cs.onSurface,
+ )),
+ backgroundColor: isActive ? cs.primary : cs.surfaceContainerHighest,
+ side: BorderSide.none,
+ onPressed: () {
+ setState(() => _defaultSpeed = s);
+ PlayerSettings.setDefaultSpeed(s);
+ },
+ );
+ }).toList(),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Skip amounts
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Skip back', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text('${_backSkip}s', style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _backSkip.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _backSkip = v.round());
+ PlayerSettings.setBackSkip(v.round());
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Skip forward', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text('${_forwardSkip}s', style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _forwardSkip.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _forwardSkip = v.round());
+ PlayerSettings.setForwardSkip(v.round());
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Toggles
+ SwitchListTile(
+ title: const Text('Full book scrubber'),
+ subtitle: Text(
+ _showBookSlider ? 'On — seekable slider across entire book' : 'Off — progress bar only',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _showBookSlider,
+ onChanged: _loaded ? (v) {
+ setState(() => _showBookSlider = v);
+ PlayerSettings.setShowBookSlider(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Speed-adjusted time'),
+ subtitle: Text(
+ _speedAdjustedTime ? 'On — remaining time reflects playback speed' : 'Off — showing raw audio duration',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _speedAdjustedTime,
+ onChanged: _loaded ? (v) {
+ setState(() => _speedAdjustedTime = v);
+ PlayerSettings.setSpeedAdjustedTime(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Auto-absorb next in series'),
+ subtitle: Text(
+ _autoContinueSeries ? 'On — next book in series added to Absorbing' : 'Off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoContinueSeries,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoContinueSeries = v);
+ PlayerSettings.setAutoContinueSeries(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // ── Auto-Rewind ──
+ SwitchListTile(
+ title: const Text('Auto-rewind on resume'),
+ subtitle: Text(
+ _rewindSettings.enabled
+ ? 'On — ${_rewindSettings.minRewind.round()}s to ${_rewindSettings.maxRewind.round()}s based on pause length'
+ : 'Off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rewindSettings.enabled,
+ onChanged: _loaded ? (v) => _saveRewind(
+ AutoRewindSettings(
+ enabled: v,
+ minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind,
+ activationDelay: _rewindSettings.activationDelay,
+ ),
+ ) : null,
+ ),
+ if (_rewindSettings.enabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Rewind range', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text('${_rewindSettings.minRewind.round()}s – ${_rewindSettings.maxRewind.round()}s',
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbRangeSlider(
+ values: RangeValues(_rewindSettings.minRewind, _rewindSettings.maxRewind),
+ min: 0, max: 60, divisions: 60,
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true, minRewind: v.start, maxRewind: v.end,
+ activationDelay: _rewindSettings.activationDelay,
+ )),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Expanded(child: Text('Rewind after paused for',
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant))),
+ Text(_rewindSettings.activationDelay == 0 ? 'Any pause' : '${_rewindSettings.activationDelay.round()}s+',
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Slider(
+ value: _rewindSettings.activationDelay, min: 0, max: 10, divisions: 10,
+ label: _rewindSettings.activationDelay == 0 ? 'Always' : '${_rewindSettings.activationDelay.round()}s',
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true, minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind, activationDelay: v,
+ )),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Text(
+ _rewindSettings.activationDelay == 0
+ ? 'Rewinds every time you resume, even after quick interruptions'
+ : 'Only rewinds if paused for ${_rewindSettings.activationDelay.round()}+ seconds',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest,
+ borderRadius: BorderRadius.circular(12)),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Preview', style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 4),
+ ..._buildRewindPreviews(cs, tt),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Sleep Timer ──
+ _CollapsibleSection(
+ icon: Icons.bedtime_outlined,
+ title: 'Sleep Timer',
+ cs: cs,
+ children: [
+ SwitchListTile(
+ title: const Text('Shake to add time'),
+ subtitle: Text(
+ _shakeToResetSleep ? 'On — adds $_shakeAddMinutes min per shake' : 'Off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _shakeToResetSleep,
+ onChanged: _loaded ? (v) {
+ setState(() => _shakeToResetSleep = v);
+ PlayerSettings.setShakeToResetSleep(v);
+ } : null,
+ ),
+ if (_shakeToResetSleep) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Shake adds', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text('$_shakeAddMinutes min',
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _shakeAddMinutes.toDouble(),
+ min: 1, max: 30, divisions: 29,
+ onChanged: _loaded ? (v) {
+ setState(() => _shakeAddMinutes = v.round());
+ PlayerSettings.setShakeAddMinutes(v.round());
+ } : null,
+ ),
+ const SizedBox(height: 4),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Reset timer on pause'),
+ subtitle: Text(
+ _resetSleepOnPause
+ ? 'Timer restarts from full duration when you resume'
+ : 'Timer continues from where it left off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _resetSleepOnPause,
+ onChanged: _loaded ? (v) {
+ setState(() => _resetSleepOnPause = v);
+ PlayerSettings.setResetSleepOnPause(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // ── Auto Sleep Timer ──
+ SwitchListTile(
+ title: const Text('Auto sleep timer'),
+ subtitle: Text(
+ _autoSleepSettings.enabled
+ ? '${_autoSleepSettings.startLabel} – ${_autoSleepSettings.endLabel} · ${_autoSleepSettings.durationMinutes} min'
+ : 'Automatically start a sleep timer during a time window',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoSleepSettings.enabled,
+ onChanged: _loaded ? (v) {
+ final updated = AutoSleepSettings(
+ enabled: v,
+ startHour: _autoSleepSettings.startHour,
+ startMinute: _autoSleepSettings.startMinute,
+ endHour: _autoSleepSettings.endHour,
+ endMinute: _autoSleepSettings.endMinute,
+ durationMinutes: _autoSleepSettings.durationMinutes,
+ );
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ } : null,
+ ),
+ if (_autoSleepSettings.enabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Start time picker
+ ListTile(
+ title: const Text('Window start'),
+ trailing: Text(_autoSleepSettings.startLabel,
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ onTap: () async {
+ final picked = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay(hour: _autoSleepSettings.startHour, minute: _autoSleepSettings.startMinute),
+ );
+ if (picked != null) {
+ final updated = AutoSleepSettings(
+ enabled: true,
+ startHour: picked.hour,
+ startMinute: picked.minute,
+ endHour: _autoSleepSettings.endHour,
+ endMinute: _autoSleepSettings.endMinute,
+ durationMinutes: _autoSleepSettings.durationMinutes,
+ );
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // End time picker
+ ListTile(
+ title: const Text('Window end'),
+ trailing: Text(_autoSleepSettings.endLabel,
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ onTap: () async {
+ final picked = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay(hour: _autoSleepSettings.endHour, minute: _autoSleepSettings.endMinute),
+ );
+ if (picked != null) {
+ final updated = AutoSleepSettings(
+ enabled: true,
+ startHour: _autoSleepSettings.startHour,
+ startMinute: _autoSleepSettings.startMinute,
+ endHour: picked.hour,
+ endMinute: picked.minute,
+ durationMinutes: _autoSleepSettings.durationMinutes,
+ );
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Duration slider
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Timer duration', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text('${_autoSleepSettings.durationMinutes} min',
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _autoSleepSettings.durationMinutes.toDouble(),
+ min: 5, max: 120, divisions: 23,
+ onChanged: _loaded ? (v) {
+ final updated = AutoSleepSettings(
+ enabled: true,
+ startHour: _autoSleepSettings.startHour,
+ startMinute: _autoSleepSettings.startMinute,
+ endHour: _autoSleepSettings.endHour,
+ endMinute: _autoSleepSettings.endMinute,
+ durationMinutes: v.round(),
+ );
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ } : null,
+ ),
+ const SizedBox(height: 4),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Downloads & Storage ──
+ _CollapsibleSection(
+ icon: Icons.download_outlined,
+ title: 'Downloads & Storage',
+ cs: cs,
+ children: [
+ SwitchListTile(
+ title: const Text('Download over Wi-Fi only'),
+ subtitle: Text(
+ _wifiOnlyDownloads ? 'On — mobile data blocked for downloads' : 'Off — downloads on any connection',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _wifiOnlyDownloads,
+ onChanged: _loaded ? (v) {
+ setState(() => _wifiOnlyDownloads = v);
+ PlayerSettings.setWifiOnlyDownloads(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.folder_outlined, color: cs.primary),
+ title: const Text('Download location'),
+ subtitle: Text(
+ _downloadLocationLabel,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ trailing: const Icon(Icons.chevron_right),
+ onTap: () => _pickDownloadLocation(context, cs, tt),
+ ),
+ if (_totalDownloadSizeBytes > 0) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.data_usage_rounded, color: cs.onSurfaceVariant),
+ title: const Text('Storage used'),
+ subtitle: Text(
+ _formatBytes(_totalDownloadSizeBytes),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.storage_rounded, color: cs.primary),
+ title: const Text('Manage downloads'),
+ trailing: const Icon(Icons.chevron_right),
+ onTap: () => _showDownloadManager(context, cs, tt),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Library ──
+ _CollapsibleSection(
+ icon: Icons.auto_stories_outlined,
+ title: 'Library',
+ cs: cs,
+ children: [
+ SwitchListTile(
+ title: const Text('Hide eBook-only titles'),
+ subtitle: Text(
+ _hideEbookOnly
+ ? 'Books with no audio files are hidden'
+ : 'Off — all library items shown',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _hideEbookOnly,
+ onChanged: _loaded ? (v) {
+ setState(() => _hideEbookOnly = v);
+ PlayerSettings.setHideEbookOnly(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Show Goodreads button'),
+ subtitle: Text(
+ _showGoodreadsButton
+ ? 'Book detail sheet shows a link to Goodreads'
+ : 'Off — Goodreads button hidden',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _showGoodreadsButton,
+ onChanged: _loaded ? (v) {
+ setState(() => _showGoodreadsButton = v);
+ PlayerSettings.setShowGoodreadsButton(v);
+ } : null,
+ ),
+ if (lib.libraries.length > 1) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ...lib.libraries
+ .map((library) {
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? 'Library';
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+ return ListTile(
+ leading: Icon(
+ mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded,
+ color: isSelected ? cs.primary : cs.onSurfaceVariant),
+ title: Text(name),
+ trailing: isSelected ? Icon(Icons.check_circle_rounded, color: cs.primary) : null,
+ onTap: () { if (!isSelected) lib.selectLibrary(id); },
+ );
+ }),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Permissions ──
+ _CollapsibleSection(
+ icon: Icons.shield_outlined,
+ title: 'Permissions',
+ cs: cs,
+ children: [
+ ListTile(
+ leading: const Icon(Icons.notifications_outlined),
+ title: const Text('Notifications'),
+ subtitle: Text('For download progress and playback controls',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: const Icon(Icons.chevron_right_rounded, color: Colors.white38),
+ onTap: () async {
+ final status = await Permission.notification.status;
+ if (status.isGranted) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 2),
+ content: const Text('Notifications already enabled'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ } else {
+ final result = await Permission.notification.request();
+ if (result.isPermanentlyDenied && mounted) await openAppSettings();
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: const Icon(Icons.battery_saver_outlined),
+ title: const Text('Unrestricted battery'),
+ subtitle: Text('Prevents Android from killing background playback',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: const Icon(Icons.chevron_right_rounded, color: Colors.white38),
+ onTap: () async {
+ if (Platform.isAndroid) {
+ final status = await Permission.ignoreBatteryOptimizations.status;
+ if (status.isGranted) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 2),
+ content: const Text('Battery already unrestricted'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ } else {
+ final result = await Permission.ignoreBatteryOptimizations.request();
+ if (result.isPermanentlyDenied && mounted) await openAppSettings();
+ }
+ }
+ },
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Support & Info ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ children: [
+ Card(
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ clipBehavior: Clip.antiAlias,
+ child: ListTile(
+ leading: Icon(Icons.feedback_outlined,
+ color: cs.onSurfaceVariant),
+ title: const Text('Bugs & Feature Requests'),
+ subtitle: Text('Open an issue on GitHub',
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.open_in_new_rounded,
+ size: 18, color: cs.onSurfaceVariant),
+ onTap: () => launchUrl(
+ Uri.parse(
+ 'https://github.com/pounat/absorb/issues'),
+ mode: LaunchMode.externalApplication),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Card(
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ clipBehavior: Clip.antiAlias,
+ child: ListTile(
+ leading: Icon(Icons.coffee_rounded,
+ color: Colors.amber.shade600),
+ title: const Text('Support the Dev'),
+ subtitle: Text('Buy me a coffee',
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.favorite_rounded,
+ size: 18, color: Colors.amber.shade600),
+ onTap: () => launchUrl(
+ Uri.parse(
+ 'https://www.buymeacoffee.com/BarnabasApps'),
+ mode: LaunchMode.externalApplication),
+ ),
+ ),
+ const SizedBox(height: 12),
+ GestureDetector(
+ onTap: () async {
+ final update = await UpdateCheckerService.check(force: true);
+ if (!mounted) return;
+ if (update != null) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text('Absorb ${update.latestVersion} is available!'),
+ action: SnackBarAction(
+ label: 'Download',
+ onPressed: () => launchUrl(Uri.parse(update.downloadUrl), mode: LaunchMode.externalApplication),
+ ),
+ ),
+ );
+ } else {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('You\'re on the latest version')),
+ );
+ }
+ },
+ child: Text('Check for updates',
+ style: tt.bodySmall?.copyWith(color: cs.primary, fontWeight: FontWeight.w600)),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ auth.serverVersion != null
+ ? 'Absorb v$_appVersion · Server ${auth.serverVersion}'
+ : 'Absorb v$_appVersion',
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ ],
+ ),
+ ),
+
+ const SizedBox(height: 24),
+
+ // ── Accounts ──
+ Builder(builder: (ctx) {
+ final accounts = UserAccountService().accounts;
+ final auth = ctx.read<AuthProvider>();
+ final otherAccounts = accounts.where((a) =>
+ !(a.serverUrl == auth.serverUrl && a.username == auth.username)
+ ).toList();
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (otherAccounts.isNotEmpty) ...[
+ Text('Switch Account',
+ style: tt.titleSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w600,
+ )),
+ const SizedBox(height: 8),
+ ...otherAccounts.map((account) {
+ final shortUrl = account.serverUrl
+ .replaceAll(RegExp(r'^https?://'), '')
+ .replaceAll(RegExp(r'/+$'), '');
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Material(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ child: InkWell(
+ borderRadius: BorderRadius.circular(14),
+ onTap: () => _switchAccount(ctx, account),
+ onLongPress: () => _removeAccount(ctx, account),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ child: Row(
+ children: [
+ CircleAvatar(
+ radius: 18,
+ backgroundColor: cs.primary.withValues(alpha: 0.15),
+ child: Text(
+ account.username.isNotEmpty
+ ? account.username[0].toUpperCase()
+ : '?',
+ style: TextStyle(
+ color: cs.primary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(account.username,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600)),
+ Text(shortUrl,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis),
+ ],
+ ),
+ ),
+ Icon(Icons.swap_horiz_rounded,
+ size: 20, color: cs.primary),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }),
+ const SizedBox(height: 6),
+ ],
+ // Add Account button — always visible
+ Material(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ child: InkWell(
+ borderRadius: BorderRadius.circular(14),
+ onTap: () => _addAccount(ctx),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ child: Row(
+ children: [
+ CircleAvatar(
+ radius: 18,
+ backgroundColor: cs.primary.withValues(alpha: 0.08),
+ child: Icon(Icons.person_add_rounded,
+ size: 18, color: cs.primary),
+ ),
+ const SizedBox(width: 12),
+ Text('Add Account',
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ ],
+ ),
+ );
+ }),
+
+ // ── Sign out ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: SizedBox(
+ width: double.infinity,
+ child: OutlinedButton.icon(
+ onPressed: () => _confirmLogout(context),
+ icon: const Icon(Icons.logout_rounded),
+ label: const Text('Peace out'),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: cs.error,
+ side: BorderSide(color: cs.error.withValues(alpha: 0.5)),
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 100),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _buildRewindPreviews(ColorScheme cs, TextTheme tt) {
+ final s = _rewindSettings;
+ final delay = s.activationDelay.round();
+
+ // Build dynamic preview durations starting from the delay value
+ final durations = <int, String>{};
+
+ // First row: the activation delay itself (or instant if 0)
+ if (delay == 0) {
+ durations[0] = 'Instant';
+ } else {
+ durations[delay] = '${_formatDuration(delay)} pause';
+ }
+
+ // Add useful reference points above the delay, spread across the full range
+ for (final secs in [30, 120, 600, 1800, 3600]) {
+ if (secs > delay && durations.length < 5) {
+ durations[secs] = '${_formatDuration(secs)} pause';
+ }
+ }
+
+ // Always include 1 hour as the max reference
+ if (!durations.containsKey(3600)) {
+ durations[3600] = '1 hr pause';
+ }
+
+ final rows = <Widget>[];
+ for (final entry in durations.entries) {
+ final rewind = AudioPlayerService.calculateAutoRewind(
+ Duration(seconds: entry.key), s.minRewind, s.maxRewind,
+ activationDelay: s.activationDelay);
+ rows.add(_rewindPreviewRow(entry.value, rewind, cs, tt));
+ }
+
+ return rows;
+ }
+
+ static String _formatDuration(int seconds) {
+ if (seconds < 60) return '${seconds}s';
+ if (seconds < 3600) {
+ final m = seconds ~/ 60;
+ return '$m min';
+ }
+ final h = seconds ~/ 3600;
+ return '$h hr';
+ }
+
+ Widget _rewindPreviewRow(
+ String label, double rewind, ColorScheme cs, TextTheme tt) {
+ final isSkipped = rewind < 0;
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 2),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(label, style: tt.bodySmall?.copyWith(
+ color: isSkipped ? cs.onSurfaceVariant.withValues(alpha: 0.4) : cs.onSurfaceVariant)),
+ Text(isSkipped ? '→ no rewind' : '→ ${rewind.toStringAsFixed(1)}s rewind',
+ style: tt.bodySmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: isSkipped ? cs.onSurfaceVariant.withValues(alpha: 0.3) : cs.primary)),
+ ],
+ ),
+ );
+ }
+
+ static String _formatBytes(int bytes) {
+ if (bytes < 1024) return '$bytes B';
+ if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
+ if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
+ return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
+ }
+
+ Future<void> _pickDownloadLocation(BuildContext context, ColorScheme cs, TextTheme tt) async {
+ final dl = DownloadService();
+ final hasExistingDownloads = dl.downloadedItems.isNotEmpty;
+
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: cs.surface,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (ctx) => Padding(
+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 16),
+ Text('Download Location',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text('Choose where audiobooks are saved',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 20),
+
+ // Current location display
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.2)),
+ ),
+ child: Row(children: [
+ Icon(Icons.folder_rounded, color: cs.primary, size: 20),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Current location',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 2),
+ Text(_downloadLocationLabel,
+ style: tt.bodySmall?.copyWith(color: cs.onSurface),
+ maxLines: 2, overflow: TextOverflow.ellipsis),
+ ],
+ ),
+ ),
+ ]),
+ ),
+ const SizedBox(height: 16),
+
+ if (hasExistingDownloads)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Container(
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.errorContainer.withValues(alpha: 0.2),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.error.withValues(alpha: 0.2)),
+ ),
+ child: Row(children: [
+ Icon(Icons.info_outline_rounded, size: 16, color: cs.error),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ 'Existing downloads stay in their current location. Only new downloads use the new path.',
+ style: tt.bodySmall?.copyWith(
+ color: cs.error.withValues(alpha: 0.8), fontSize: 11),
+ ),
+ ),
+ ]),
+ ),
+ ),
+
+ // Choose folder button
+ SizedBox(
+ width: double.infinity,
+ child: FilledButton.icon(
+ icon: const Icon(Icons.folder_open_rounded),
+ label: const Text('Choose folder'),
+ onPressed: () async {
+ Navigator.pop(ctx);
+ final result = await FilePicker.platform.getDirectoryPath(
+ dialogTitle: 'Choose download folder',
+ );
+ if (result != null) {
+ await dl.setCustomDownloadPath(result);
+ final label = await dl.downloadLocationLabel;
+ if (mounted) {
+ setState(() => _downloadLocationLabel = label);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text('Download location set to $label'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+ },
+ ),
+ ),
+ const SizedBox(height: 8),
+
+ // Reset to default button
+ if (dl.customDownloadPath != null)
+ SizedBox(
+ width: double.infinity,
+ child: OutlinedButton.icon(
+ icon: const Icon(Icons.restart_alt_rounded),
+ label: const Text('Reset to default'),
+ onPressed: () async {
+ Navigator.pop(ctx);
+ await dl.setCustomDownloadPath(null);
+ final label = await dl.downloadLocationLabel;
+ if (mounted) {
+ setState(() => _downloadLocationLabel = label);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text('Reset to default storage'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ void _showDownloadManager(BuildContext context, ColorScheme cs, TextTheme tt) {
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: Colors.transparent,
+ isScrollControlled: true,
+ builder: (ctx) => DraggableScrollableSheet(
+ initialChildSize: 0.5,
+ minChildSize: 0.3,
+ maxChildSize: 0.85,
+ expand: false,
+ builder: (ctx, scrollController) => Container(
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (ctx, _) {
+ final items = DownloadService().downloadedItems;
+ return Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 16),
+ Text('Downloads',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ ],
+ ),
+ ),
+ if (items.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text('No downloads',
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ )
+ else
+ Expanded(
+ child: ListView.builder(
+ controller: scrollController,
+ padding: EdgeInsets.only(bottom: 32 + MediaQuery.of(ctx).viewPadding.bottom),
+ itemCount: items.length,
+ itemBuilder: (ctx, index) {
+ final info = items[index];
+ return ListTile(
+ leading: Icon(Icons.headphones_rounded, color: cs.primary),
+ title: Text(info.title ?? 'Unknown',
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ subtitle: Text(info.author ?? '',
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: IconButton(
+ icon: Icon(Icons.delete_outline, color: cs.error),
+ onPressed: () {
+ showDialog(
+ context: ctx,
+ builder: (d) => AlertDialog(
+ title: const Text('Remove download?'),
+ content: Text('Delete "${info.title}" from device?'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(d),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () {
+ DownloadService().deleteDownload(info.itemId);
+ Navigator.pop(d);
+ },
+ child: const Text('Remove')),
+ ],
+ ),
+ );
+ },
+ ),
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ }
+
+ void _confirmLogout(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ icon: const Icon(Icons.logout_rounded),
+ title: const Text('Peace out?'),
+ content: const Text('This will sign you out. Your downloads will stay on this device.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx),
+ child: const Text('Stay'),
+ ),
+ FilledButton(
+ onPressed: () {
+ Navigator.pop(ctx);
+ context.read<AuthProvider>().logout();
+ },
+ style: FilledButton.styleFrom(backgroundColor: cs.error),
+ child: const Text('Sign Out'),
+ ),
+ ],
+ ),
+ );
+ }
+
+ void _addAccount(BuildContext context) async {
+ // Navigate to login screen as a pushed route (not replacing current)
+ await Navigator.of(context, rootNavigator: true).push(
+ MaterialPageRoute(builder: (_) => const LoginScreen()),
+ );
+ // After login, refresh the library for the newly active account
+ if (!context.mounted) return;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ if (auth.isAuthenticated) {
+ lib.updateAuth(auth);
+ await lib.refresh();
+ if (context.mounted) AppShell.goToAbsorbingGlobal();
+ }
+ }
+
+ void _removeAccount(BuildContext context, SavedAccount account) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Remove Account?'),
+ content: Text(
+ 'Remove ${account.username} on ${account.serverUrl.replaceAll(RegExp(r'^https?://'), '')} from saved accounts?\n\n'
+ 'You can always add it back later by signing in again.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ style: FilledButton.styleFrom(
+ backgroundColor: Theme.of(ctx).colorScheme.error),
+ child: const Text('Remove')),
+ ],
+ ),
+ );
+ if (confirmed != true || !context.mounted) return;
+ await UserAccountService().removeAccount(account.serverUrl, account.username);
+ if (context.mounted) setState(() {});
+ }
+
+ void _switchAccount(BuildContext context, SavedAccount account) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Switch Account?'),
+ content: Text(
+ 'Switch to ${account.username} on ${account.serverUrl.replaceAll(RegExp(r'^https?://'), '')}?\n\n'
+ 'Your current playback will be stopped and the app will reload with the other account\'s data.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Switch')),
+ ],
+ ),
+ );
+ if (confirmed != true || !context.mounted) return;
+
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+
+ await auth.switchToAccount(account);
+
+ // Re-init the library provider with the new user
+ if (context.mounted) {
+ lib.updateAuth(auth);
+ await lib.refresh();
+ // Jump to the absorbing screen
+ AppShell.goToAbsorbingGlobal();
+ }
+ }
+}
+
+class _CollapsibleSection extends StatelessWidget {
+ final IconData icon;
+ final String title;
+ final ColorScheme cs;
+ final List<Widget> children;
+
+ const _CollapsibleSection({
+ required this.icon,
+ required this.title,
+ required this.cs,
+ required this.children,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return Card(
+ elevation: 0,
+ margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
+ clipBehavior: Clip.antiAlias,
+ child: Theme(
+ data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
+ child: ExpansionTile(
+ leading: Icon(icon, color: cs.primary, size: 22),
+ title: Text(title, style: TextStyle(fontWeight: FontWeight.w600)),
+ childrenPadding: EdgeInsets.zero,
+ tilePadding: const EdgeInsets.symmetric(horizontal: 16),
+ children: children,
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
new file mode 100644
index 00000000..27772311
--- /dev/null
+++ b/lib/screens/stats_screen.dart
@@ -0,0 +1,619 @@
+import 'dart:math';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/absorb_wave_icon.dart';
+
+class StatsScreen extends StatefulWidget {
+ const StatsScreen({super.key});
+ @override
+ State<StatsScreen> createState() => _StatsScreenState();
+}
+
+class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStateMixin {
+ Map<String, dynamic>? _stats;
+ List<dynamic> _sessions = [];
+ bool _isLoading = true;
+ late AnimationController _animController;
+ late Animation<double> _animValue;
+
+ @override
+ void initState() {
+ super.initState();
+ _animController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1200));
+ _animValue = CurvedAnimation(parent: _animController, curve: Curves.easeOutCubic);
+ _loadStats();
+ }
+
+ @override
+ void dispose() {
+ _animController.dispose();
+ super.dispose();
+ }
+
+ int _booksFinished = 0;
+
+ Future<void> _loadStats() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final statsFuture = api.getListeningStats();
+ final sessionsFuture = api.getListeningSessions(itemsPerPage: 25);
+ final meFuture = api.getMe();
+ final stats = await statsFuture;
+ final sessionsData = await sessionsFuture;
+ final meData = await meFuture;
+
+ // Count finished from mediaProgress
+ int finished = 0;
+ if (meData != null) {
+ final progress = meData['mediaProgress'] as List<dynamic>? ?? [];
+ for (final p in progress) {
+ if (p is Map<String, dynamic> && p['isFinished'] == true) {
+ finished++;
+ }
+ }
+ }
+
+ if (mounted) {
+ setState(() {
+ _stats = stats;
+ _sessions = sessionsData?['sessions'] as List<dynamic>? ?? [];
+ _booksFinished = finished;
+ _isLoading = false;
+ });
+ _animController.reset();
+ _animController.forward();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Scaffold(
+ backgroundColor: Colors.black,
+ body: Container(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ stops: const [0.0, 0.4, 0.7, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.12),
+ cs.primary.withValues(alpha: 0.04),
+ Colors.black,
+ Colors.black,
+ ],
+ ),
+ ),
+ child: SafeArea(
+ child: _isLoading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))
+ : _stats == null
+ ? _errorState(tt)
+ : RefreshIndicator(
+ onRefresh: () async {
+ setState(() => _isLoading = true);
+ await _loadStats();
+ },
+ color: cs.primary,
+ backgroundColor: const Color(0xFF1A1A1A),
+ child: AnimatedBuilder(
+ animation: _animValue,
+ builder: (_, __) => _buildContent(cs, tt),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _errorState(TextTheme tt) {
+ return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.signal_wifi_off_rounded, size: 48, color: Colors.white.withValues(alpha: 0.15)),
+ const SizedBox(height: 12),
+ Text('Couldn\'t load stats', style: tt.bodyMedium?.copyWith(color: Colors.white38)),
+ const SizedBox(height: 8),
+ TextButton(onPressed: () { setState(() => _isLoading = true); _loadStats(); },
+ child: const Text('Retry')),
+ ]));
+ }
+
+ Widget _buildContent(ColorScheme cs, TextTheme tt) {
+ final totalSeconds = _safeNum(_stats!['totalTime']);
+ final dailyMap = _extractDailyMap(_stats!);
+ final today = _todaySeconds(dailyMap);
+ final thisWeek = _weekSeconds(dailyMap);
+ final thisMonth = _monthSeconds(dailyMap);
+ final streak = _currentStreak(dailyMap);
+ final longestStreak = _longestStreak(dailyMap);
+ final weekData = _last7Days(dailyMap);
+ final monthData = _last30Days(dailyMap);
+
+ // Count finished books — loaded from /api/me mediaProgress
+ final booksFinished = _booksFinished;
+
+ return ListView(
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
+ children: [
+ // Header
+ const AbsorbPageHeader(
+ title: 'Your Stats',
+ brandingColor: Colors.white38,
+ titleColor: Colors.white,
+ padding: EdgeInsets.only(top: 4),
+ ),
+ const SizedBox(height: 24),
+
+ // ── Hero stat ──
+ _heroStat(tt, totalSeconds),
+ const SizedBox(height: 24),
+
+ // ── Quick stats row ──
+ Row(children: [
+ Expanded(child: _statCard(tt, Icons.local_fire_department_rounded, Colors.orange,
+ '${streak}d', 'Current\nStreak')),
+ const SizedBox(width: 10),
+ Expanded(child: _statCard(tt, Icons.emoji_events_rounded, Colors.amber,
+ '${longestStreak}d', 'Longest\nStreak')),
+ const SizedBox(width: 10),
+ Expanded(child: _statCard(tt, Icons.check_circle_rounded, Colors.green,
+ '$booksFinished', 'Books\nFinished')),
+ ]),
+ const SizedBox(height: 24),
+
+ // ── Time periods ──
+ Row(children: [
+ Expanded(child: _periodCard(tt, 'Today', today)),
+ const SizedBox(width: 10),
+ Expanded(child: _periodCard(tt, 'This Week', thisWeek)),
+ const SizedBox(width: 10),
+ Expanded(child: _periodCard(tt, 'This Month', thisMonth)),
+ ]),
+ const SizedBox(height: 28),
+
+ // ── Last 7 days chart ──
+ Text('Last 7 Days', style: tt.titleSmall?.copyWith(
+ color: Colors.white60, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ _barChart(weekData, cs),
+ const SizedBox(height: 28),
+
+ // ── Last 30 days chart ──
+ Text('Last 30 Days', style: tt.titleSmall?.copyWith(
+ color: Colors.white60, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ _heatMap(monthData, tt),
+ const SizedBox(height: 28),
+
+ // ── Recent Sessions ──
+ if (_sessions.isNotEmpty) ...[
+ Text('Recent Sessions', style: tt.titleSmall?.copyWith(
+ color: Colors.white60, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ ..._buildSessions(tt, cs),
+ ],
+ ],
+ );
+ }
+
+ // ─── HERO STAT ──────────────────────────────────────────────
+
+ Widget _heroStat(TextTheme tt, double totalSeconds) {
+ final hours = (totalSeconds / 3600).floor();
+ final minutes = ((totalSeconds % 3600) / 60).floor();
+ final anim = _animValue.value;
+
+ return Container(
+ padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 20),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(20),
+ gradient: LinearGradient(
+ begin: Alignment.topLeft, end: Alignment.bottomRight,
+ colors: [
+ Colors.white.withValues(alpha: 0.06),
+ Colors.white.withValues(alpha: 0.02),
+ ],
+ ),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Column(children: [
+ Text('Total Listening Time', style: tt.labelMedium?.copyWith(
+ color: Colors.white38, letterSpacing: 1.5, fontWeight: FontWeight.w500)),
+ const SizedBox(height: 12),
+ Row(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
+ Text('${(hours * anim).round()}',
+ style: tt.displayLarge?.copyWith(
+ fontWeight: FontWeight.w800, color: Colors.white, fontSize: 56, height: 1)),
+ Padding(padding: const EdgeInsets.only(bottom: 8),
+ child: Text('h', style: tt.headlineSmall?.copyWith(color: Colors.white38, fontWeight: FontWeight.w300))),
+ const SizedBox(width: 8),
+ Text('${(minutes * anim).round()}',
+ style: tt.displayLarge?.copyWith(
+ fontWeight: FontWeight.w800, color: Colors.white, fontSize: 56, height: 1)),
+ Padding(padding: const EdgeInsets.only(bottom: 8),
+ child: Text('m', style: tt.headlineSmall?.copyWith(color: Colors.white38, fontWeight: FontWeight.w300))),
+ ]),
+ const SizedBox(height: 8),
+ Text(_daysEquivalent(totalSeconds),
+ style: tt.bodySmall?.copyWith(color: Colors.white24)),
+ ]),
+ );
+ }
+
+ String _daysEquivalent(double seconds) {
+ final days = seconds / 86400;
+ if (days >= 1) return 'That\'s ${days.toStringAsFixed(1)} days of audio';
+ final hours = seconds / 3600;
+ return 'That\'s ${hours.toStringAsFixed(1)} hours of audio';
+ }
+
+ // ─── STAT CARD ──────────────────────────────────────────────
+
+ Widget _statCard(TextTheme tt, IconData icon, Color color, String value, String label) {
+ return Container(
+ padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.06)),
+ ),
+ child: Column(children: [
+ Icon(icon, color: color.withValues(alpha: 0.8), size: 22),
+ const SizedBox(height: 8),
+ Text(value, style: tt.headlineSmall?.copyWith(
+ fontWeight: FontWeight.w800, color: Colors.white, height: 1)),
+ const SizedBox(height: 4),
+ Text(label, textAlign: TextAlign.center, style: tt.labelSmall?.copyWith(
+ color: Colors.white30, fontSize: 10, height: 1.2)),
+ ]),
+ );
+ }
+
+ // ─── PERIOD CARD ────────────────────────────────────────────
+
+ Widget _periodCard(TextTheme tt, String label, double seconds) {
+ return Container(
+ padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 10),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.06)),
+ ),
+ child: Column(children: [
+ Text(_formatDuration(seconds), style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w700, color: Colors.white, height: 1)),
+ const SizedBox(height: 4),
+ Text(label, style: tt.labelSmall?.copyWith(color: Colors.white30, fontSize: 10)),
+ ]),
+ );
+ }
+
+ // ─── BAR CHART (7 days) ─────────────────────────────────────
+
+ Widget _barChart(List<_DayData> data, ColorScheme cs) {
+ final maxVal = data.map((d) => d.seconds).fold(0.0, (a, b) => a > b ? a : b);
+ final barMax = maxVal > 0 ? maxVal : 1.0;
+ final anim = _animValue.value;
+
+ return Container(
+ height: 140,
+ padding: const EdgeInsets.fromLTRB(0, 8, 0, 0),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.03),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.05)),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: data.map((d) {
+ final ratio = (d.seconds / barMax * anim).clamp(0.0, 1.0);
+ final isToday = d.label == _dayLabel(DateTime.now());
+ return Expanded(child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: Column(mainAxisAlignment: MainAxisAlignment.end, children: [
+ if (d.seconds > 0)
+ Padding(padding: const EdgeInsets.only(bottom: 4),
+ child: Text(_shortDuration(d.seconds), style: TextStyle(
+ color: Colors.white30, fontSize: 9, fontWeight: FontWeight.w500))),
+ AnimatedContainer(
+ duration: const Duration(milliseconds: 600),
+ curve: Curves.easeOutCubic,
+ height: (ratio * 80).clamp(2.0, 80.0),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(4),
+ color: isToday ? Colors.white.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.15),
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(d.label, style: TextStyle(
+ color: isToday ? Colors.white60 : Colors.white.withValues(alpha: 0.2),
+ fontSize: 10, fontWeight: isToday ? FontWeight.w600 : FontWeight.w400)),
+ const SizedBox(height: 8),
+ ]),
+ ));
+ }).toList(),
+ ),
+ );
+ }
+
+ // ─── HEAT MAP (30 days) ─────────────────────────────────────
+
+ Widget _heatMap(List<_DayData> data, TextTheme tt) {
+ final maxVal = data.map((d) => d.seconds).fold(0.0, (a, b) => a > b ? a : b);
+
+ return Wrap(
+ spacing: 3, runSpacing: 3,
+ children: data.map((d) {
+ final intensity = maxVal > 0 ? (d.seconds / maxVal).clamp(0.0, 1.0) : 0.0;
+ return Tooltip(
+ message: '${d.fullLabel}: ${_formatDuration(d.seconds)}',
+ child: Container(
+ width: 18, height: 18,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(3),
+ color: intensity > 0
+ ? Colors.white.withValues(alpha: 0.08 + intensity * 0.4)
+ : Colors.white.withValues(alpha: 0.03),
+ ),
+ ),
+ );
+ }).toList(),
+ );
+ }
+
+ // ─── SESSIONS ───────────────────────────────────────────────
+
+ List<Widget> _buildSessions(TextTheme tt, ColorScheme cs) {
+ return _sessions.take(15).map((s) {
+ if (s is! Map<String, dynamic>) return const SizedBox.shrink();
+ final title = s['displayTitle'] as String? ??
+ (s['mediaMetadata'] as Map<String, dynamic>?)?['title'] as String? ?? 'Unknown';
+ final author = s['displayAuthor'] as String? ??
+ (s['mediaMetadata'] as Map<String, dynamic>?)?['authorName'] as String? ?? '';
+ final duration = _safeNum(s['timeListening']);
+ final updatedAt = s['updatedAt'] is num
+ ? DateTime.fromMillisecondsSinceEpoch((s['updatedAt'] as num).toInt())
+ : null;
+
+ // Device / app info
+ final deviceInfo = s['deviceInfo'] as Map<String, dynamic>? ?? {};
+ final clientName = deviceInfo['clientName'] as String? ??
+ deviceInfo['deviceName'] as String? ?? '';
+ final manufacturer = deviceInfo['manufacturer'] as String? ?? '';
+ final model = deviceInfo['model'] as String? ?? '';
+ final deviceStr = [manufacturer, model].where((s) => s.isNotEmpty).join(' ');
+ final appLabel = clientName.isNotEmpty ? clientName : 'Unknown Client';
+
+ // Pick an icon based on client name
+ final isAbsorb = clientName.toLowerCase().contains('absorb');
+ final icon = _clientIcon(clientName);
+ final iconColor = _clientColor(clientName);
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.06)),
+ ),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ // App icon
+ Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(
+ color: iconColor.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Center(
+ child: isAbsorb
+ ? AbsorbWaveIcon(size: 20, color: iconColor.withValues(alpha: 0.8))
+ : Icon(icon, size: 18, color: iconColor.withValues(alpha: 0.8)),
+ ),
+ ),
+ const SizedBox(width: 12),
+ // Title + author + app
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: Colors.white70, fontWeight: FontWeight.w600)),
+ if (author.isNotEmpty)
+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(color: Colors.white30, fontSize: 10)),
+ const SizedBox(height: 4),
+ Row(children: [
+ isAbsorb
+ ? AbsorbWaveIcon(size: 10, color: iconColor.withValues(alpha: 0.5))
+ : Icon(icon, size: 10, color: iconColor.withValues(alpha: 0.5)),
+ const SizedBox(width: 4),
+ Flexible(child: Text(
+ deviceStr.isNotEmpty ? '$appLabel · $deviceStr' : appLabel,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: TextStyle(color: Colors.white.withValues(alpha: 0.2), fontSize: 9),
+ )),
+ ]),
+ ])),
+ const SizedBox(width: 8),
+ // Duration + time
+ Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
+ Text(_formatDuration(duration),
+ style: tt.labelSmall?.copyWith(color: Colors.white38, fontWeight: FontWeight.w600)),
+ if (updatedAt != null)
+ Text(_relativeDate(updatedAt),
+ style: tt.labelSmall?.copyWith(color: Colors.white.withValues(alpha: 0.2), fontSize: 9)),
+ ]),
+ ]),
+ ),
+ );
+ }).toList();
+ }
+
+ IconData _clientIcon(String clientName) {
+ final lower = clientName.toLowerCase();
+ if (lower.contains('absorb')) return Icons.waves_rounded;
+ if (lower.contains('audiobookshelf') || lower.contains('abs')) return Icons.headphones_rounded;
+ if (lower.contains('web') || lower.contains('browser')) return Icons.language_rounded;
+ if (lower.contains('ios') || lower.contains('apple')) return Icons.phone_iphone_rounded;
+ if (lower.contains('android')) return Icons.phone_android_rounded;
+ if (lower.contains('sonos') || lower.contains('cast')) return Icons.speaker_rounded;
+ return Icons.devices_rounded;
+ }
+
+ Color _clientColor(String clientName) {
+ final lower = clientName.toLowerCase();
+ if (lower.contains('absorb')) return Colors.tealAccent;
+ if (lower.contains('audiobookshelf') || lower.contains('abs')) return Colors.deepPurple;
+ if (lower.contains('web') || lower.contains('browser')) return Colors.blue;
+ if (lower.contains('ios') || lower.contains('apple')) return Colors.grey;
+ if (lower.contains('android')) return Colors.green;
+ return Colors.white54;
+ }
+
+ // ─── HELPERS ────────────────────────────────────────────────
+
+ static double _safeNum(dynamic val) => val is num ? val.toDouble() : 0;
+
+ Map<String, dynamic> _extractDailyMap(Map<String, dynamic> stats) {
+ for (final key in ['dayListeningMap', 'days']) {
+ final val = stats[key];
+ if (val is Map<String, dynamic>) return val;
+ }
+ return {};
+ }
+
+ double _todaySeconds(Map<String, dynamic> dailyMap) {
+ final key = _dateKey(DateTime.now());
+ return _daySeconds(dailyMap, key);
+ }
+
+ double _weekSeconds(Map<String, dynamic> dailyMap) {
+ final now = DateTime.now();
+ double total = 0;
+ for (int i = 0; i < 7; i++) {
+ total += _daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i))));
+ }
+ return total;
+ }
+
+ double _monthSeconds(Map<String, dynamic> dailyMap) {
+ final now = DateTime.now();
+ double total = 0;
+ for (int i = 0; i < 30; i++) {
+ total += _daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i))));
+ }
+ return total;
+ }
+
+ double _daySeconds(Map<String, dynamic> map, String key) {
+ final val = map[key];
+ if (val is num) return val.toDouble();
+ if (val is Map) {
+ final t = _safeNum(val['timeListening']);
+ return t > 0 ? t : _safeNum(val['totalTime']);
+ }
+ return 0;
+ }
+
+ int _currentStreak(Map<String, dynamic> dailyMap) {
+ int streak = 0;
+ final now = DateTime.now();
+ // Start from yesterday if today has no listening yet
+ int startOffset = _daySeconds(dailyMap, _dateKey(now)) > 0 ? 0 : 1;
+ for (int i = startOffset; i < 365; i++) {
+ final key = _dateKey(now.subtract(Duration(days: i)));
+ if (_daySeconds(dailyMap, key) > 0) {
+ streak++;
+ } else {
+ break;
+ }
+ }
+ return streak;
+ }
+
+ int _longestStreak(Map<String, dynamic> dailyMap) {
+ int longest = 0, current = 0;
+ // Sort days and iterate
+ final keys = dailyMap.keys.toList()..sort();
+ DateTime? lastDate;
+ for (final key in keys) {
+ final val = _daySeconds(dailyMap, key);
+ if (val <= 0) continue;
+ final parts = key.split('-');
+ if (parts.length != 3) continue;
+ final date = DateTime.tryParse(key);
+ if (date == null) continue;
+ if (lastDate != null && date.difference(lastDate).inDays == 1) {
+ current++;
+ } else {
+ current = 1;
+ }
+ longest = max(longest, current);
+ lastDate = date;
+ }
+ return longest;
+ }
+
+ List<_DayData> _last7Days(Map<String, dynamic> dailyMap) {
+ final now = DateTime.now();
+ return List.generate(7, (i) {
+ final date = now.subtract(Duration(days: 6 - i));
+ return _DayData(
+ label: _dayLabel(date),
+ fullLabel: _dateKey(date),
+ seconds: _daySeconds(dailyMap, _dateKey(date)),
+ );
+ });
+ }
+
+ List<_DayData> _last30Days(Map<String, dynamic> dailyMap) {
+ final now = DateTime.now();
+ return List.generate(30, (i) {
+ final date = now.subtract(Duration(days: 29 - i));
+ return _DayData(
+ label: _dayLabel(date),
+ fullLabel: _dateKey(date),
+ seconds: _daySeconds(dailyMap, _dateKey(date)),
+ );
+ });
+ }
+
+ String _dateKey(DateTime d) =>
+ '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
+
+ String _dayLabel(DateTime d) => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d.weekday - 1];
+
+ String _formatDuration(double seconds) {
+ final h = (seconds / 3600).floor();
+ final m = ((seconds % 3600) / 60).floor();
+ if (h > 0) return '${h}h ${m}m';
+ if (m > 0) return '${m}m';
+ if (seconds > 0) return '<1m';
+ return '0m';
+ }
+
+ String _shortDuration(double seconds) {
+ final h = (seconds / 3600).floor();
+ final m = ((seconds % 3600) / 60).floor();
+ if (h > 0) return '${h}h';
+ return '${m}m';
+ }
+
+ String _relativeDate(DateTime date) {
+ final diff = DateTime.now().difference(date);
+ if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
+ if (diff.inHours < 24) return '${diff.inHours}h ago';
+ if (diff.inDays < 7) return '${diff.inDays}d ago';
+ return '${date.month}/${date.day}';
+ }
+}
+
+class _DayData {
+ final String label;
+ final String fullLabel;
+ final double seconds;
+ const _DayData({required this.label, required this.fullLabel, required this.seconds});
+}
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
new file mode 100644
index 00000000..e97bce30
--- /dev/null
+++ b/lib/services/android_auto_service.dart
@@ -0,0 +1,768 @@
+import 'dart:async';
+import 'dart:convert';
+import 'package:audio_service/audio_service.dart';
+import 'package:connectivity_plus/connectivity_plus.dart';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'api_service.dart';
+import 'download_service.dart';
+import 'progress_sync_service.dart';
+
+// ─── Media ID scheme ─────────────────────────────────────────────────
+//
+// Root tabs (max 4):
+// continue → list of in-progress books
+// recent → list of recently added books (default library)
+// library → list of book-type libraries
+// downloads → list of downloaded books
+//
+// Library drilldown:
+// lib:<libraryId> → sub-categories (Books, Series, Authors)
+// lib:<libraryId>:books → all books in library
+// lib:<libraryId>:series → list of series
+// lib:<libraryId>:authors → list of authors
+// series:<seriesId>@<libId> → books in that series
+// author:<authorId>@<libId> → books by that author
+//
+// Playable items:
+// item:<absItemId> → a playable book
+// ─────────────────────────────────────────────────────────────────────
+
+class AutoMediaIds {
+ // Root tabs
+ static const root = 'root';
+ static const continueListening = 'continue';
+ static const recent = 'recent';
+ static const library = 'library';
+ static const downloads = 'downloads';
+
+ // Prefixes
+ static const itemPrefix = 'item:';
+ static const libPrefix = 'lib:';
+ static const seriesPrefix = 'series:';
+ static const authorPrefix = 'author:';
+
+ // Build IDs
+ static String itemId(String absId) => '$itemPrefix$absId';
+ static String libId(String libraryId) => '$libPrefix$libraryId';
+ static String libBooks(String libraryId) => '$libPrefix$libraryId:books';
+ static String libSeries(String libraryId) => '$libPrefix$libraryId:series';
+ static String libAuthors(String libraryId) => '$libPrefix$libraryId:authors';
+ static String seriesId(String sId, String libId) => '$seriesPrefix$sId@$libId';
+ static String authorId(String aId, String libId) => '$authorPrefix$aId@$libId';
+
+ // Parse helpers
+ static String? absItemId(String mediaId) =>
+ mediaId.startsWith(itemPrefix) ? mediaId.substring(itemPrefix.length) : null;
+
+ /// Parse "series:<seriesId>@<libId>" → {seriesId, libId}
+ static ({String seriesId, String libId})? parseSeries(String mediaId) {
+ if (!mediaId.startsWith(seriesPrefix)) return null;
+ final rest = mediaId.substring(seriesPrefix.length);
+ final at = rest.indexOf('@');
+ if (at < 0) return null;
+ return (seriesId: rest.substring(0, at), libId: rest.substring(at + 1));
+ }
+
+ /// Parse "author:<authorId>@<libId>" → {authorId, libId}
+ static ({String authorId, String libId})? parseAuthor(String mediaId) {
+ if (!mediaId.startsWith(authorPrefix)) return null;
+ final rest = mediaId.substring(authorPrefix.length);
+ final at = rest.indexOf('@');
+ if (at < 0) return null;
+ return (authorId: rest.substring(0, at), libId: rest.substring(at + 1));
+ }
+
+ /// Parse "lib:<libraryId>" or "lib:<libraryId>:books" etc.
+ static String? parseLibId(String mediaId) {
+ if (!mediaId.startsWith(libPrefix)) return null;
+ final rest = mediaId.substring(libPrefix.length);
+ final colon = rest.indexOf(':');
+ return colon >= 0 ? rest.substring(0, colon) : rest;
+ }
+
+ /// Parse sub-category from "lib:<libraryId>:<sub>"
+ static String? parseLibSub(String mediaId) {
+ if (!mediaId.startsWith(libPrefix)) return null;
+ final rest = mediaId.substring(libPrefix.length);
+ final colon = rest.indexOf(':');
+ return colon >= 0 ? rest.substring(colon + 1) : null;
+ }
+}
+
+// ─── Data models ─────────────────────────────────────────────────────
+
+class AutoBookEntry {
+ final String id;
+ final String title;
+ final String author;
+ final double duration;
+ final String? coverUrl;
+ final List<dynamic> chapters;
+ final double? currentTime;
+
+ const AutoBookEntry({
+ required this.id,
+ required this.title,
+ required this.author,
+ required this.duration,
+ this.coverUrl,
+ this.chapters = const [],
+ this.currentTime,
+ });
+
+ MediaItem toMediaItem() {
+ final uri = coverUrl != null ? Uri.tryParse(coverUrl!) : null;
+ return MediaItem(
+ id: AutoMediaIds.itemId(id),
+ title: title,
+ artist: author,
+ album: title,
+ duration: Duration(seconds: duration.round()),
+ artUri: uri,
+ playable: true,
+ extras: uri != null ? {'artUri': uri.toString()} : null,
+ );
+ }
+}
+
+class AutoLibraryEntry {
+ final String id;
+ final String name;
+ final String mediaType;
+
+ const AutoLibraryEntry({
+ required this.id,
+ required this.name,
+ required this.mediaType,
+ });
+
+ bool get isBook => mediaType == 'book';
+}
+
+// ─── Android Auto Service ────────────────────────────────────────────
+
+class AndroidAutoService {
+ static final AndroidAutoService _instance = AndroidAutoService._();
+ factory AndroidAutoService() => _instance;
+ AndroidAutoService._();
+
+ // ── Cached data ──
+ List<AutoBookEntry> _continueListening = [];
+ List<AutoBookEntry> _downloaded = [];
+ List<AutoBookEntry> _recentlyAdded = [];
+ List<AutoLibraryEntry> _libraries = [];
+
+ DateTime? _lastRefresh;
+ bool _isRefreshing = false;
+
+ // ── API helpers ──
+
+ Future<ApiService?> getApi() async {
+ final prefs = await SharedPreferences.getInstance();
+ final url = prefs.getString('server_url');
+ final token = prefs.getString('token');
+ if (url == null || token == null) return null;
+ return ApiService(baseUrl: url, token: token);
+ }
+
+ Future<String?> getDefaultLibraryId() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getString('default_library_id');
+ }
+
+ // ── Refresh ──
+
+ /// Whether downloads have been populated at least once (synchronous, no server needed).
+ bool _downloadsReady = false;
+
+ /// Fire-and-forget server refresh. Downloads are already available;
+ /// this populates Continue, Recent, and Library tabs in the background.
+ void _backgroundRefresh() {
+ refresh().then((_) {
+ debugPrint('[AndroidAuto] Background refresh completed');
+ }).catchError((e) {
+ debugPrint('[AndroidAuto] Background refresh failed: $e');
+ });
+ }
+
+ Future<void> refresh({bool force = false}) async {
+ // Always populate downloads immediately — no server needed.
+ // This ensures Android Auto can show the Downloads tab even if the
+ // server is unreachable (e.g. no remote access, offline-only users).
+ if (!_downloadsReady || force) {
+ await _refreshDownloaded();
+ _downloadsReady = true;
+ }
+
+ if (_isRefreshing) return;
+ if (!force && _lastRefresh != null &&
+ DateTime.now().difference(_lastRefresh!) < const Duration(seconds: 30)) {
+ return;
+ }
+
+ _isRefreshing = true;
+ debugPrint('[AndroidAuto] Refreshing browse tree...');
+
+ // Server fetch is best-effort — don't block the browse tree
+ try {
+ await _refreshDownloaded(); // re-fetch in case downloads changed
+ await _refreshFromServer();
+ _lastRefresh = DateTime.now();
+ debugPrint('[AndroidAuto] Refresh done: '
+ '${_continueListening.length} continue, '
+ '${_downloaded.length} downloaded, '
+ '${_recentlyAdded.length} recent, '
+ '${_libraries.length} libraries '
+ '(${_libraries.where((l) => l.isBook).length} book-type)');
+ } catch (e) {
+ // Server unreachable — downloads are still available.
+ _lastRefresh = DateTime.now();
+ debugPrint('[AndroidAuto] Server refresh failed (downloads still available): $e');
+ } finally {
+ _isRefreshing = false;
+ // Tell the head unit to re-fetch the root browse tree now that data has changed.
+ try {
+ // ignore: deprecated_member_use
+ await AudioServiceBackground.notifyChildrenChanged(AutoMediaIds.root);
+ } catch (_) {}
+ }
+ }
+
+ /// Content provider authority for serving local cover images to Android Auto.
+ /// Must match the authority registered in AndroidManifest.xml.
+ static const _coverAuthority = 'com.barnabas.absorb.covers';
+
+ /// Build a content:// URI for a locally cached cover image.
+ /// Android Auto requires content:// URIs — file:// won't work.
+ static String _localCoverUri(String itemId) =>
+ 'content://$_coverAuthority/cover/$itemId';
+
+ Future<void> _refreshDownloaded() async {
+ final ds = DownloadService();
+ final api = await getApi();
+ final items = ds.downloadedItems;
+ final entries = <AutoBookEntry>[];
+
+ for (final dl in items) {
+ double duration = 0;
+ List<dynamic> chapters = [];
+ if (dl.sessionData != null) {
+ try {
+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
+ duration = (session['duration'] as num?)?.toDouble() ?? 0;
+ chapters = session['chapters'] as List<dynamic>? ?? [];
+ } catch (_) {}
+ }
+
+ final localPos = await ProgressSyncService().getSavedPosition(dl.itemId);
+
+ // Use HTTP cover URLs when online (more reliable in AA browse list),
+ // fall back to local content:// URIs when offline.
+ String? coverUrl;
+ final connectivity = await Connectivity().checkConnectivity();
+ final isOnline = !connectivity.contains(ConnectivityResult.none);
+ if (isOnline && api != null) {
+ coverUrl = api.getCoverUrl(dl.itemId, width: 400);
+ } else {
+ final localCover = await ds.getLocalCoverPath(dl.itemId);
+ if (localCover != null) {
+ coverUrl = _localCoverUri(dl.itemId);
+ }
+ }
+
+ entries.add(AutoBookEntry(
+ id: dl.itemId,
+ title: dl.title ?? 'Unknown',
+ author: dl.author ?? '',
+ duration: duration,
+ coverUrl: coverUrl,
+ chapters: chapters,
+ currentTime: localPos > 0 ? localPos : null,
+ ));
+ debugPrint('[AndroidAuto] Download entry: ${dl.title} cover=${coverUrl ?? "null"}');
+ }
+
+ _downloaded = entries;
+ }
+
+ Future<void> _refreshFromServer() async {
+ final api = await getApi();
+ if (api == null) return;
+
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ if (manualOffline) {
+ _continueListening = [];
+ _recentlyAdded = [];
+ _libraries = [];
+ return;
+ }
+
+ try {
+ // ── Fetch all libraries (filter out podcasts) ──
+ final libs = await api.getLibraries();
+ _libraries = libs.map((l) {
+ final m = l as Map<String, dynamic>;
+ return AutoLibraryEntry(
+ id: m['id'] as String? ?? '',
+ name: m['name'] as String? ?? 'Library',
+ mediaType: m['mediaType'] as String? ?? 'book',
+ );
+ }).where((l) => l.id.isNotEmpty && l.isBook).toList();
+
+ // ── Continue Listening (from default library) ──
+ final defaultLibId = await getDefaultLibraryId();
+ if (defaultLibId != null) {
+ final sections = await api.getPersonalizedView(defaultLibId);
+ final continueEntries = <AutoBookEntry>[];
+ final seenIds = <String>{};
+
+ for (final section in sections) {
+ final sectionId = section['id'] as String? ?? '';
+ if (sectionId == 'continue-listening' || sectionId == 'continue-series') {
+ for (final entity in (section['entities'] as List<dynamic>? ?? [])) {
+ if (entity is Map<String, dynamic>) {
+ final entry = _entityToEntry(entity, api);
+ if (entry != null && seenIds.add(entry.id)) {
+ continueEntries.add(entry);
+ }
+ }
+ }
+ }
+ }
+ _continueListening = continueEntries;
+
+ // ── Recently Added (default library) ──
+ final recentResult = await api.getLibraryItems(
+ defaultLibId, limit: 30, sort: 'addedAt', desc: 1,
+ );
+ if (recentResult != null) {
+ _recentlyAdded = _resultsToEntries(recentResult, api);
+ }
+ }
+ } catch (e) {
+ // Server unreachable — clear stale tabs so only Downloads shows offline
+ _continueListening = [];
+ _recentlyAdded = [];
+ _libraries = [];
+ debugPrint('[AndroidAuto] Server fetch error: $e');
+ }
+ }
+
+ // ── Data conversion ──
+
+ List<AutoBookEntry> _resultsToEntries(
+ Map<String, dynamic> result, ApiService api) {
+ final results = result['results'] as List<dynamic>? ?? [];
+ return results
+ .whereType<Map<String, dynamic>>()
+ .map((item) => _libraryItemToEntry(item, api))
+ .whereType<AutoBookEntry>()
+ .toList();
+ }
+
+ AutoBookEntry? _entityToEntry(Map<String, dynamic> entity, ApiService api) {
+ final id = entity['id'] as String?;
+ if (id == null) return null;
+
+ final media = entity['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final duration = (media?['duration'] as num?)?.toDouble() ?? 0;
+ final chapters = media?['chapters'] as List<dynamic>? ?? [];
+
+ final progress = entity['mediaProgress'] as Map<String, dynamic>?;
+ final currentTime = (progress?['currentTime'] as num?)?.toDouble();
+
+ return AutoBookEntry(
+ id: id,
+ title: title,
+ author: author,
+ duration: duration,
+ coverUrl: api.getCoverUrl(id, width: 400),
+ chapters: chapters,
+ currentTime: currentTime,
+ );
+ }
+
+ AutoBookEntry? _libraryItemToEntry(
+ Map<String, dynamic> item, ApiService api) {
+ final id = item['id'] as String?;
+ if (id == null) return null;
+
+ final media = item['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final duration = (media?['duration'] as num?)?.toDouble() ?? 0;
+ final chapters = media?['chapters'] as List<dynamic>? ?? [];
+
+ return AutoBookEntry(
+ id: id,
+ title: title,
+ author: author,
+ duration: duration,
+ coverUrl: api.getCoverUrl(id, width: 400),
+ chapters: chapters,
+ );
+ }
+
+ // ─── Browse tree ───────────────────────────────────────────────────
+
+ List<MediaItem> _getRootChildren() {
+ final tabs = <MediaItem>[];
+
+ if (_continueListening.isNotEmpty) {
+ tabs.add(const MediaItem(
+ id: AutoMediaIds.continueListening,
+ title: 'Continue',
+ playable: false,
+ ));
+ }
+
+ if (_recentlyAdded.isNotEmpty) {
+ tabs.add(const MediaItem(
+ id: AutoMediaIds.recent,
+ title: 'Recent',
+ playable: false,
+ ));
+ }
+
+ if (_libraries.isNotEmpty) {
+ tabs.add(const MediaItem(
+ id: AutoMediaIds.library,
+ title: 'Library',
+ playable: false,
+ ));
+ }
+
+ if (_downloaded.isNotEmpty) {
+ tabs.add(const MediaItem(
+ id: AutoMediaIds.downloads,
+ title: 'Downloads',
+ playable: false,
+ ));
+ }
+
+ if (tabs.isEmpty) {
+ tabs.add(const MediaItem(
+ id: AutoMediaIds.library,
+ title: 'Library',
+ playable: false,
+ ));
+ }
+
+ return tabs;
+ }
+
+ /// Library tab → list of book-type libraries
+ List<MediaItem> _getLibraryList() {
+ // If only one book library, skip the picker — go straight to sub-categories
+ // (handled by caller checking length)
+ return _libraries.map((lib) {
+ return MediaItem(
+ id: AutoMediaIds.libId(lib.id),
+ title: lib.name,
+ playable: false,
+ );
+ }).toList();
+ }
+
+ /// Sub-categories for a library: Books, Series, Authors
+ List<MediaItem> _getLibrarySubCategories(String libraryId) {
+ return [
+ MediaItem(
+ id: AutoMediaIds.libBooks(libraryId),
+ title: 'Books',
+ playable: false,
+ ),
+ MediaItem(
+ id: AutoMediaIds.libSeries(libraryId),
+ title: 'Series',
+ playable: false,
+ ),
+ MediaItem(
+ id: AutoMediaIds.libAuthors(libraryId),
+ title: 'Authors',
+ playable: false,
+ ),
+ ];
+ }
+
+ /// Main entry point for browse tree. May make API calls for drilldowns.
+ Future<List<MediaItem>> getChildrenOf(String parentMediaId) async {
+ // Ensure downloads are always populated before returning root.
+ // This is instant (no network) so Android Auto never waits on a server.
+ if (!_downloadsReady) {
+ await _refreshDownloaded();
+ _downloadsReady = true;
+ }
+
+ // Kick off a full server refresh in the background if we haven't done one.
+ // Don't await — return what we have now (downloads at minimum).
+ if (_lastRefresh == null && !_isRefreshing) {
+ _backgroundRefresh();
+ }
+
+ // ── Root ──
+ if (parentMediaId == AutoMediaIds.root) {
+ return _getRootChildren();
+ }
+
+ // ── Top-level tabs ──
+ if (parentMediaId == AutoMediaIds.continueListening) {
+ return _continueListening.map((e) => e.toMediaItem()).toList();
+ }
+ if (parentMediaId == AutoMediaIds.recent) {
+ return _recentlyAdded.map((e) => e.toMediaItem()).toList();
+ }
+ if (parentMediaId == AutoMediaIds.downloads) {
+ return _downloaded.map((e) => e.toMediaItem()).toList();
+ }
+
+ // ── Library tab ──
+ if (parentMediaId == AutoMediaIds.library) {
+ // If only one book library, skip picker → show sub-categories directly
+ if (_libraries.length == 1) {
+ return _getLibrarySubCategories(_libraries.first.id);
+ }
+ return _getLibraryList();
+ }
+
+ // ── Library drilldowns ──
+ if (parentMediaId.startsWith(AutoMediaIds.libPrefix)) {
+ final libId = AutoMediaIds.parseLibId(parentMediaId);
+ final sub = AutoMediaIds.parseLibSub(parentMediaId);
+ if (libId == null) return [];
+
+ if (sub == null) {
+ // "lib:<id>" → sub-categories
+ return _getLibrarySubCategories(libId);
+ }
+
+ switch (sub) {
+ case 'books':
+ return _fetchLibraryBooks(libId);
+ case 'series':
+ return _fetchLibrarySeries(libId);
+ case 'authors':
+ return _fetchLibraryAuthors(libId);
+ }
+ }
+
+ // ── Series drilldown ──
+ final series = AutoMediaIds.parseSeries(parentMediaId);
+ if (series != null) {
+ return _fetchSeriesBooks(series.seriesId, series.libId);
+ }
+
+ // ── Author drilldown ──
+ final author = AutoMediaIds.parseAuthor(parentMediaId);
+ if (author != null) {
+ return _fetchAuthorBooks(author.authorId, author.libId);
+ }
+
+ return [];
+ }
+
+ // ─── On-demand fetchers ────────────────────────────────────────────
+
+ Future<List<MediaItem>> _fetchLibraryBooks(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+
+ try {
+ // Android Auto has a ~1MB Binder transaction limit for onLoadChildren
+ // results. With cover URLs, each MediaItem is ~1.2KB, so we cap at 200
+ // items to stay safely under the limit. For larger libraries, users can
+ // browse via Series or Authors instead.
+ const maxItems = 200;
+ final allBooks = <MediaItem>[];
+ int page = 0;
+ const pageSize = 100;
+
+ while (allBooks.length < maxItems) {
+ final result = await api.getLibraryItems(
+ libraryId, page: page, limit: pageSize,
+ sort: 'media.metadata.title', desc: 0,
+ );
+ if (result == null) break;
+
+ final entries = _resultsToEntries(result, api);
+ allBooks.addAll(entries.map((e) => e.toMediaItem()));
+
+ final total = (result['total'] as num?)?.toInt() ?? 0;
+ if (allBooks.length >= total || entries.length < pageSize) break;
+ page++;
+ }
+
+ if (allBooks.length > maxItems) {
+ debugPrint('[AndroidAuto] Trimmed books from ${allBooks.length} to $maxItems (Binder limit)');
+ return allBooks.sublist(0, maxItems);
+ }
+
+ debugPrint('[AndroidAuto] Fetched ${allBooks.length} books');
+ return allBooks;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching library books: $e');
+ }
+ return [];
+ }
+
+ Future<List<MediaItem>> _fetchLibrarySeries(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+
+ try {
+ // Fetch all series, paginated, sorted alphabetically
+ final allSeries = <MediaItem>[];
+ int page = 0;
+ const pageSize = 100;
+
+ while (true) {
+ final result = await api.getLibrarySeries(
+ libraryId, page: page, limit: pageSize, sort: 'name', desc: 0,
+ );
+ if (result == null) break;
+
+ final seriesList = result['results'] as List<dynamic>? ?? [];
+ for (final s in seriesList) {
+ final sm = s as Map<String, dynamic>;
+ final sId = sm['id'] as String? ?? '';
+ final name = sm['name'] as String? ?? 'Unknown';
+ if (sId.isEmpty) continue;
+ allSeries.add(MediaItem(
+ id: AutoMediaIds.seriesId(sId, libraryId),
+ title: name,
+ playable: false,
+ ));
+ }
+
+ final total = (result['total'] as num?)?.toInt() ?? 0;
+ if (allSeries.length >= total || seriesList.length < pageSize) break;
+ page++;
+ }
+
+ debugPrint('[AndroidAuto] Fetched ${allSeries.length} series');
+ return allSeries;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching series: $e');
+ }
+ return [];
+ }
+
+ Future<List<MediaItem>> _fetchLibraryAuthors(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+
+ try {
+ final filterData = await api.getLibraryFilterData(libraryId);
+ if (filterData != null) {
+ final authorsList = filterData['authors'] as List<dynamic>? ?? [];
+ final items = authorsList.map((a) {
+ final am = a as Map<String, dynamic>;
+ final aId = am['id'] as String? ?? '';
+ final name = am['name'] as String? ?? 'Unknown';
+ if (aId.isEmpty) return null;
+ return MediaItem(
+ id: AutoMediaIds.authorId(aId, libraryId),
+ title: name,
+ playable: false,
+ );
+ }).whereType<MediaItem>().toList();
+
+ items.sort((a, b) => a.title.toLowerCase().compareTo(b.title.toLowerCase()));
+ debugPrint('[AndroidAuto] Fetched ${items.length} authors');
+ return items;
+ }
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching authors: $e');
+ }
+ return [];
+ }
+
+ Future<List<MediaItem>> _fetchSeriesBooks(String seriesId, String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+
+ try {
+ final results = await api.getBooksBySeries(libraryId, seriesId);
+ return results
+ .whereType<Map<String, dynamic>>()
+ .map((item) => _libraryItemToEntry(item, api))
+ .whereType<AutoBookEntry>()
+ .map((e) => e.toMediaItem())
+ .toList();
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching series books: $e');
+ return [];
+ }
+ }
+
+ Future<List<MediaItem>> _fetchAuthorBooks(String authorId, String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+
+ try {
+ final results = await api.getBooksByAuthor(libraryId, authorId);
+ return results
+ .whereType<Map<String, dynamic>>()
+ .map((item) => _libraryItemToEntry(item, api))
+ .whereType<AutoBookEntry>()
+ .map((e) => e.toMediaItem())
+ .toList();
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching author books: $e');
+ return [];
+ }
+ }
+
+ // ─── Search ────────────────────────────────────────────────────────
+
+ Future<List<MediaItem>> search(String query) async {
+ final api = await getApi();
+ final libId = await getDefaultLibraryId();
+ if (api == null || libId == null) return [];
+
+ try {
+ final result = await api.searchLibrary(libId, query, limit: 20);
+ if (result == null) return [];
+
+ final items = <MediaItem>[];
+ final books = result['book'] as List<dynamic>? ?? [];
+ for (final b in books) {
+ final bm = b as Map<String, dynamic>;
+ final libraryItem = bm['libraryItem'] as Map<String, dynamic>?;
+ if (libraryItem != null) {
+ final entry = _libraryItemToEntry(libraryItem, api);
+ if (entry != null) {
+ items.add(entry.toMediaItem());
+ }
+ }
+ }
+ return items;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Search error: $e');
+ return [];
+ }
+ }
+
+ // ─── Lookup helpers ────────────────────────────────────────────────
+
+ AutoBookEntry? findEntry(String absItemId) {
+ for (final list in [_continueListening, _downloaded, _recentlyAdded]) {
+ for (final entry in list) {
+ if (entry.id == absItemId) return entry;
+ }
+ }
+ return null;
+ }
+
+ MediaItem? getMediaItem(String mediaId) {
+ final absId = AutoMediaIds.absItemId(mediaId);
+ if (absId == null) return null;
+ return findEntry(absId)?.toMediaItem();
+ }
+}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
new file mode 100644
index 00000000..63681063
--- /dev/null
+++ b/lib/services/api_service.dart
@@ -0,0 +1,1222 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:http/http.dart' as http;
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+
+class ApiService {
+ static String appVersion = '1.3.0'; // fallback; overwritten by initVersion()
+
+ /// Call once at startup to read the real version from pubspec via package_info_plus.
+ static Future<void> initVersion() async {
+ try {
+ final info = await PackageInfo.fromPlatform();
+ appVersion = info.version;
+ } catch (_) {}
+ }
+
+ final String baseUrl;
+ final String token;
+ final Map<String, String> customHeaders;
+
+ // Device info — set once at app start
+ static String deviceManufacturer = '';
+ static String deviceModel = '';
+ static String deviceId = '';
+
+ /// Generate or load a persistent unique device ID
+ static Future<void> initDeviceId() async {
+ final prefs = await SharedPreferences.getInstance();
+ var id = prefs.getString('absorb_device_id');
+ if (id == null || id.isEmpty) {
+ // Generate a unique ID for this install
+ id = 'absorb-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-${(DateTime.now().microsecond * 31337).toRadixString(36)}';
+ await prefs.setString('absorb_device_id', id);
+ }
+ deviceId = id;
+ }
+
+ ApiService({required this.baseUrl, required this.token, this.customHeaders = const {}});
+
+ Map<String, String> get _headers => {
+ ...customHeaders,
+ 'Authorization': 'Bearer $token',
+ 'Content-Type': 'application/json',
+ };
+
+ /// Public headers for image/audio requests (no Content-Type needed).
+ /// Use this for CachedNetworkImage, Image.network, AudioSource.uri, etc.
+ Map<String, String> get mediaHeaders => {
+ ...customHeaders,
+ 'Authorization': 'Bearer $token',
+ };
+
+ String get _cleanBaseUrl =>
+ baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;
+
+ /// Login and return the full response JSON (contains user, token, etc.)
+ static Future<Map<String, dynamic>?> login({
+ required String serverUrl,
+ required String username,
+ required String password,
+ Map<String, String> customHeaders = const {},
+ }) async {
+ final url = serverUrl.endsWith('/')
+ ? '${serverUrl}login'
+ : '$serverUrl/login';
+
+ try {
+ final response = await http.post(
+ Uri.parse(url),
+ headers: {...customHeaders, 'Content-Type': 'application/json'},
+ body: jsonEncode({'username': username, 'password': password}),
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ return null;
+ } catch (e) {
+ return null;
+ }
+ }
+
+ /// Ping the server to check connectivity.
+ static Future<bool> pingServer(String serverUrl, {Map<String, String> customHeaders = const {}}) async {
+ final url = serverUrl.endsWith('/')
+ ? '${serverUrl}ping'
+ : '$serverUrl/ping';
+ try {
+ final response = await http.get(Uri.parse(url), headers: customHeaders.isNotEmpty ? customHeaders : null)
+ .timeout(const Duration(seconds: 10));
+ return response.statusCode == 200;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ /// Get the server version via the /status endpoint (no auth needed).
+ static Future<String?> getServerVersion(String serverUrl, {Map<String, String> customHeaders = const {}}) async {
+ final url = serverUrl.endsWith('/')
+ ? '${serverUrl}status'
+ : '$serverUrl/status';
+ try {
+ final response = await http.get(Uri.parse(url), headers: customHeaders.isNotEmpty ? customHeaders : null)
+ .timeout(const Duration(seconds: 10));
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ return data['serverVersion'] as String?;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Get all libraries.
+ Future<List<dynamic>> getLibraries() async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body);
+ return (data['libraries'] as List?) ?? [];
+ }
+ } catch (e) {
+ // ignore
+ }
+ return [];
+ }
+
+ /// Get the personalized home view for a library.
+ /// Returns sections like "continue-listening", "recently-added", "discover", etc.
+ Future<List<dynamic>> getPersonalizedView(String libraryId) async {
+ try {
+ final response = await http.get(
+ Uri.parse(
+ '$_cleanBaseUrl/api/libraries/$libraryId/personalized'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as List<dynamic>;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return [];
+ }
+
+ /// Get library items (paginated).
+ Future<Map<String, dynamic>?> getLibraryItems(
+ String libraryId, {
+ int page = 0,
+ int limit = 20,
+ String sort = 'addedAt',
+ int desc = 1,
+ String? filter,
+ bool expanded = false,
+ }) async {
+ try {
+ var url = '$_cleanBaseUrl/api/libraries/$libraryId/items'
+ '?page=$page&limit=$limit&sort=$sort&desc=$desc';
+ if (filter != null) url += '&filter=$filter';
+ if (expanded) url += '&minified=0';
+ final response = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ /// Build a cover image URL for a library item.
+ String getCoverUrl(String itemId, {int width = 400}) {
+ return '$_cleanBaseUrl/api/items/$itemId/cover?width=$width&token=$token';
+ }
+
+ /// Get current user info including all mediaProgress.
+ Future<Map<String, dynamic>?> getMe() async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/me'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Get user's listening stats.
+ Future<Map<String, dynamic>?> getListeningStats() async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/me/listening-stats'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Get user's listening sessions (paginated).
+ Future<Map<String, dynamic>?> getListeningSessions({int page = 0, int itemsPerPage = 20}) async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/me/listening-sessions?itemsPerPage=$itemsPerPage&page=$page'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Get a library's series (paginated).
+ Future<Map<String, dynamic>?> getLibrarySeries(
+ String libraryId, {
+ int page = 0,
+ int limit = 50,
+ String sort = 'addedAt',
+ int desc = 1,
+ }) async {
+ try {
+ final response = await http.get(
+ Uri.parse(
+ '$_cleanBaseUrl/api/libraries/$libraryId/series'
+ '?page=$page&limit=$limit&sort=$sort&desc=$desc',
+ ),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ /// Build an author image URL.
+ String getAuthorImageUrl(String authorId, {int width = 200}) {
+ return '$_cleanBaseUrl/api/authors/$authorId/image?width=$width&token=$token';
+ }
+
+ /// Get a library's filter data (authors, series, genres, etc.)
+ /// Used by Android Auto to build browse tree without fetching full items.
+ Future<Map<String, dynamic>?> getLibraryFilterData(String libraryId) async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId?include=filterdata'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ return data['filterdata'] as Map<String, dynamic>?;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ /// Get books by a specific author using the filter API.
+ /// Filter format: authors.<base64(authorId)>
+ Future<List<dynamic>> getBooksByAuthor(
+ String libraryId,
+ String authorId, {
+ int limit = 50,
+ }) async {
+ try {
+ final filterValue = base64Encode(utf8.encode(authorId));
+ final url = '$_cleanBaseUrl/api/libraries/$libraryId/items'
+ '?filter=authors.$filterValue&sort=media.metadata.title&limit=$limit';
+ final response = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ return data['results'] as List<dynamic>? ?? [];
+ }
+ } catch (e) {
+ debugPrint('[API] getBooksByAuthor error: $e');
+ }
+ return [];
+ }
+
+ /// Get books in a specific series using the filter API.
+ /// Filter format: series.<base64(seriesId)>
+ Future<List<dynamic>> getBooksBySeries(
+ String libraryId,
+ String seriesId, {
+ int limit = 50,
+ }) async {
+ try {
+ final filterValue = base64Encode(utf8.encode(seriesId));
+ final url = '$_cleanBaseUrl/api/libraries/$libraryId/items'
+ '?filter=series.$filterValue'
+ '&sort=media.metadata.series.sequence&limit=$limit&collapseseries=0';
+ final response = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ return data['results'] as List<dynamic>? ?? [];
+ }
+ } catch (e) {
+ debugPrint('[API] getBooksBySeries error: $e');
+ }
+ return [];
+ }
+
+ /// Expose clean base URL for audio player to build URLs
+ String get cleanBaseUrl => _cleanBaseUrl;
+
+ /// Start a playback session for a library item.
+ /// POST /api/items/:id/play
+ /// Returns the full session object including audioTracks with contentUrl.
+ Future<Map<String, dynamic>?> startPlaybackSession(String itemId) async {
+ try {
+ final url = '$_cleanBaseUrl/api/items/$itemId/play';
+ debugPrint('[ABS] Starting playback session: POST $url');
+ final response = await http.post(
+ Uri.parse(url),
+ headers: _headers,
+ body: jsonEncode({
+ 'deviceInfo': {
+ 'clientName': 'Absorb',
+ 'clientVersion': appVersion,
+ 'deviceId': deviceId,
+ 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),
+ 'manufacturer': deviceManufacturer,
+ 'model': deviceModel,
+ },
+ 'forceDirectPlay': true,
+ 'forceTranscode': false,
+ 'mediaPlayer': 'unknown',
+ 'supportedMimeTypes': [
+ 'audio/flac',
+ 'audio/mpeg',
+ 'audio/mp4',
+ 'audio/ogg',
+ 'audio/aac',
+ ],
+ }),
+ ).timeout(const Duration(seconds: 20));
+
+ debugPrint('[ABS] Play session response: ${response.statusCode}');
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final tracks = data['audioTracks'] as List<dynamic>?;
+ debugPrint('[ABS] Session ID: ${data['id']}');
+ debugPrint('[ABS] Audio tracks: ${tracks?.length ?? 0}');
+ if (tracks != null && tracks.isNotEmpty) {
+ final firstTrack = tracks.first as Map<String, dynamic>;
+ debugPrint('[ABS] First track contentUrl: ${firstTrack['contentUrl']}');
+ }
+ return data;
+ } else {
+ debugPrint('[ABS] Play session failed: ${response.body}');
+ }
+ } catch (e) {
+ debugPrint('[ABS] Play session error: $e');
+ }
+ return null;
+ }
+
+ /// Build a full audio track URL from a contentUrl returned by the play session.
+ String buildTrackUrl(String contentUrl) {
+ if (contentUrl.startsWith('http')) return contentUrl;
+ final url = '$_cleanBaseUrl$contentUrl?token=$token';
+ debugPrint('[ABS] Track URL: $url');
+ return url;
+ }
+
+ /// Sync playback progress.
+ /// POST /api/session/:id/sync
+ Future<void> syncPlaybackSession(
+ String sessionId, {
+ required double currentTime,
+ required double duration,
+ }) async {
+ try {
+ await http.post(
+ Uri.parse('$_cleanBaseUrl/api/session/$sessionId/sync'),
+ headers: _headers,
+ body: jsonEncode({
+ 'currentTime': currentTime,
+ 'timeListened': 15,
+ 'duration': duration,
+ }),
+ ).timeout(const Duration(seconds: 10));
+ } catch (_) {}
+ }
+
+ /// Close a playback session.
+ /// POST /api/session/:id/close
+ Future<void> closePlaybackSession(String sessionId) async {
+ try {
+ await http.post(
+ Uri.parse('$_cleanBaseUrl/api/session/$sessionId/close'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ } catch (_) {}
+ }
+
+ /// Get server progress for a single item.
+ /// GET /api/me/progress/:id
+ Future<Map<String, dynamic>?> getItemProgress(String itemId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Update media progress directly (for offline sync).
+ /// PATCH /api/me/progress/:id
+ Future<void> updateProgress(
+ String itemId, {
+ required double currentTime,
+ required double duration,
+ bool isFinished = false,
+ }) async {
+ try {
+ final body = jsonEncode({
+ 'currentTime': currentTime,
+ 'duration': duration,
+ 'progress': duration > 0 ? currentTime / duration : 0,
+ 'isFinished': isFinished,
+ });
+ debugPrint('[API] updateProgress PATCH /api/me/progress/$itemId');
+ debugPrint('[API] updateProgress body: currentTime=$currentTime');
+ final resp = await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ headers: _headers,
+ body: body,
+ ).timeout(const Duration(seconds: 10));
+ debugPrint('[API] updateProgress response: ${resp.statusCode} ${resp.body}');
+ } catch (e) {
+ debugPrint('[API] updateProgress error: $e');
+ rethrow;
+ }
+ }
+
+ /// Mark a book as finished on the server.
+ Future<void> markFinished(String itemId, double duration) async {
+ await updateProgress(
+ itemId,
+ currentTime: duration,
+ duration: duration,
+ isFinished: true,
+ );
+ }
+
+ /// Mark a book as not finished (reset progress to a position).
+ Future<void> markNotFinished(String itemId, {
+ required double currentTime,
+ required double duration,
+ }) async {
+ await updateProgress(
+ itemId,
+ currentTime: currentTime,
+ duration: duration,
+ isFinished: false,
+ );
+ }
+
+ /// DELETE /api/me/progress/:id — fully remove progress entry
+ Future<bool> deleteProgress(String itemId) async {
+ try {
+ final resp = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ debugPrint('[API] deleteProgress response: ${resp.statusCode} ${resp.body}');
+ return resp.statusCode >= 200 && resp.statusCode < 300;
+ } catch (e) {
+ debugPrint('[API] deleteProgress error: $e');
+ return false;
+ }
+ }
+
+ /// Reset progress to zero.
+ Future<bool> resetProgress(String itemId, double duration) async {
+ try {
+ // DELETE progress entry
+ await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+
+ // Start session at 0 and close — forces server to update position
+ final sessionData = await startPlaybackSession(itemId);
+ if (sessionData != null) {
+ final sessionId = sessionData['id'] as String?;
+ if (sessionId != null) {
+ await syncPlaybackSession(sessionId, currentTime: 0, duration: duration);
+ await closePlaybackSession(sessionId);
+ }
+ }
+
+ // PATCH last to hide from continue listening (after session sync)
+ await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ headers: _headers,
+ body: jsonEncode({
+ 'currentTime': 0,
+ 'progress': 0,
+ 'isFinished': false,
+ 'hideFromContinueListening': true,
+ 'lastUpdate': DateTime.now().millisecondsSinceEpoch,
+ }),
+ ).timeout(const Duration(seconds: 10));
+
+ return true;
+ } catch (e) {
+ debugPrint('[API] resetProgress error: $e');
+ return false;
+ }
+ }
+
+ // ─── Podcast Episode Endpoints ─────────────────────────────
+
+ /// Start a playback session for a podcast episode.
+ /// POST /api/items/:itemId/play/:episodeId
+ Future<Map<String, dynamic>?> startEpisodePlaybackSession(
+ String itemId, String episodeId) async {
+ try {
+ final url = '$_cleanBaseUrl/api/items/$itemId/play/$episodeId';
+ debugPrint('[ABS] Starting episode session: POST $url');
+ final response = await http.post(
+ Uri.parse(url),
+ headers: _headers,
+ body: jsonEncode({
+ 'deviceInfo': {
+ 'clientName': 'Absorb',
+ 'clientVersion': appVersion,
+ 'deviceId': deviceId,
+ 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),
+ 'manufacturer': deviceManufacturer,
+ 'model': deviceModel,
+ },
+ 'forceDirectPlay': true,
+ 'forceTranscode': false,
+ 'mediaPlayer': 'unknown',
+ 'supportedMimeTypes': [
+ 'audio/flac',
+ 'audio/mpeg',
+ 'audio/mp4',
+ 'audio/ogg',
+ 'audio/aac',
+ ],
+ }),
+ ).timeout(const Duration(seconds: 20));
+
+ debugPrint('[ABS] Episode session response: ${response.statusCode}');
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ } else {
+ debugPrint('[ABS] Episode session failed: ${response.body}');
+ }
+ } catch (e) {
+ debugPrint('[ABS] Episode session error: $e');
+ }
+ return null;
+ }
+
+ /// Get server progress for a podcast episode.
+ /// GET /api/me/progress/:itemId/:episodeId
+ Future<Map<String, dynamic>?> getEpisodeProgress(
+ String itemId, String episodeId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId/$episodeId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// Update progress for a podcast episode.
+ /// PATCH /api/me/progress/:itemId/:episodeId
+ Future<void> updateEpisodeProgress(
+ String itemId,
+ String episodeId, {
+ required double currentTime,
+ required double duration,
+ bool isFinished = false,
+ }) async {
+ try {
+ await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId/$episodeId'),
+ headers: _headers,
+ body: jsonEncode({
+ 'currentTime': currentTime,
+ 'duration': duration,
+ 'progress': duration > 0 ? currentTime / duration : 0,
+ 'isFinished': isFinished,
+ }),
+ ).timeout(const Duration(seconds: 10));
+ } catch (e) {
+ debugPrint('[API] updateEpisodeProgress error: $e');
+ }
+ }
+
+ /// DELETE /api/me/progress/:itemId/:episodeId
+ Future<bool> deleteEpisodeProgress(String itemId, String episodeId) async {
+ try {
+ final resp = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId/$episodeId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ return resp.statusCode >= 200 && resp.statusCode < 300;
+ } catch (e) {
+ debugPrint('[API] deleteEpisodeProgress error: $e');
+ return false;
+ }
+ }
+
+ /// Get recent podcast episodes for a library.
+ /// GET /api/libraries/:id/recent-episodes
+ Future<List<dynamic>> getRecentEpisodes(String libraryId, {int limit = 25}) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/recent-episodes?limit=$limit'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (resp.statusCode == 200) {
+ final data = jsonDecode(resp.body);
+ if (data is Map && data['episodes'] is List) return data['episodes'] as List<dynamic>;
+ if (data is List) return data;
+ }
+ } catch (e) {
+ debugPrint('[API] getRecentEpisodes error: $e');
+ }
+ return [];
+ }
+
+ /// Get a single library item with full detail (expanded=1 gives chapters, tracks, etc.)
+ Future<Map<String, dynamic>?> getLibraryItem(String itemId) async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/items/$itemId?expanded=1&include=progress'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ /// Get a single series with its books.
+ Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId}) async {
+ try {
+ Map<String, dynamic>? seriesMeta;
+
+ // Get series metadata
+ if (libraryId != null) {
+ final metaResp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (metaResp.statusCode == 200) {
+ seriesMeta = jsonDecode(metaResp.body) as Map<String, dynamic>;
+ }
+ }
+
+ // Get books in the series via library items filter
+ // ABS filter format: series.<base64(seriesId)>
+ if (libraryId != null) {
+ final filterValue = base64Encode(utf8.encode(seriesId));
+ final url = '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=media.metadata.series.sequence&limit=100&collapseseries=0';
+ final itemsResp = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (itemsResp.statusCode == 200) {
+ final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;
+ final results = data['results'] as List<dynamic>? ?? [];
+ return {
+ 'id': seriesId,
+ 'name': seriesMeta?['name'] ?? '',
+ 'books': results,
+ };
+ }
+ }
+ } catch (e) {
+ }
+ return null;
+ }
+
+ /// Search a library. Returns { book: [...], series: [...], authors: [...] }
+ Future<Map<String, dynamic>?> searchLibrary(
+ String libraryId,
+ String query, {
+ int limit = 25,
+ }) async {
+ try {
+ final encoded = Uri.encodeQueryComponent(query);
+ final response = await http.get(
+ Uri.parse(
+ '$_cleanBaseUrl/api/libraries/$libraryId/search?q=$encoded&limit=$limit',
+ ),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ /// Search for book metadata via the ABS server's search endpoint.
+ /// Uses the server's configured providers (Audible, Google, etc.).
+ /// Returns a list of result maps with title, author, description, cover, etc.
+ Future<List<Map<String, dynamic>>> searchBooks({
+ required String title,
+ String? author,
+ String provider = 'audible',
+ }) async {
+ try {
+ final params = <String, String>{
+ 'title': title,
+ 'provider': provider,
+ };
+ if (author != null && author.isNotEmpty) {
+ params['author'] = author;
+ }
+ final uri = Uri.parse('$_cleanBaseUrl/api/search/books')
+ .replace(queryParameters: params);
+ debugPrint('[API] searchBooks: $uri');
+ final response = await http.get(
+ uri,
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ debugPrint('[API] searchBooks status=${response.statusCode} bodyLen=${response.body.length}');
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body);
+
+ // ABS returns a plain List for most providers
+ if (data is List) {
+ debugPrint('[API] searchBooks: got List with ${data.length} items');
+ return data.whereType<Map<String, dynamic>>().toList();
+ }
+
+ // Some providers may return a Map with results nested under a key
+ if (data is Map<String, dynamic>) {
+ debugPrint('[API] searchBooks: got Map with keys: ${data.keys.join(', ')}');
+ // Try common nesting patterns
+ for (final key in ['results', 'items', 'books', 'matches']) {
+ final nested = data[key];
+ if (nested is List && nested.isNotEmpty) {
+ return nested.whereType<Map<String, dynamic>>().toList();
+ }
+ }
+ // Single result as a map — wrap it
+ if (data.containsKey('title') || data.containsKey('book')) {
+ return [data];
+ }
+ }
+
+ debugPrint('[API] searchBooks: unexpected response type: ${data.runtimeType}');
+ }
+ } catch (e) {
+ debugPrint('[API] searchBooks error: $e');
+ }
+ return [];
+ }
+
+ /// Fetch Audible rating from Audnexus API using ASIN.
+ /// Returns { rating } or null.
+ static Future<Map<String, dynamic>?> getAudibleRating(String asin) async {
+ try {
+ final response = await http.get(
+ Uri.parse('https://api.audnex.us/books/$asin?update=1'),
+ ).timeout(const Duration(seconds: 10));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final rating = data['rating'] as String?;
+ if (rating != null) {
+ return {
+ 'rating': double.tryParse(rating) ?? 0.0,
+ };
+ }
+ }
+ } catch (e) {
+ // ignore — Audnexus is optional
+ }
+ return null;
+ }
+
+ /// Search Audible via the audiobookshelf server for an ASIN by title+author,
+ /// then fetch the rating from Audnexus. Used as a fallback when the book's
+ /// stored ASIN returns no rating.
+ Future<Map<String, dynamic>?> searchAudibleRating(
+ String title, String? author) async {
+ try {
+ // Use the ABS server's search endpoint to query Audible for the book
+ final query = author != null && author.isNotEmpty
+ ? '$title $author'
+ : title;
+ final encoded = Uri.encodeQueryComponent(query);
+ final response = await http.get(
+ Uri.parse(
+ '$_cleanBaseUrl/api/search/covers?title=${Uri.encodeQueryComponent(title)}'
+ '&author=${Uri.encodeQueryComponent(author ?? '')}'
+ '&provider=audible',
+ ),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final results = jsonDecode(response.body) as List<dynamic>? ?? [];
+ // Look for an ASIN in the results
+ for (final r in results) {
+ if (r is Map<String, dynamic>) {
+ final asin = r['asin'] as String? ?? r['key'] as String? ?? '';
+ if (asin.isNotEmpty && asin.startsWith('B')) {
+ return await getAudibleRating(asin);
+ }
+ }
+ }
+ }
+ } catch (e) {
+ // ignore
+ }
+ return null;
+ }
+
+ // ─── Admin Endpoints ──────────────────────────────────────
+
+ /// Get all users (admin only)
+ Future<List<dynamic>> getUsers() async {
+ try {
+ final r = await http.get(Uri.parse('$_cleanBaseUrl/api/users'), headers: _headers)
+ .timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ if (data is List) return data;
+ if (data is Map) {
+ // ABS wraps in {"users": [...]}
+ if (data['users'] is List) return data['users'] as List<dynamic>;
+ // Fallback: return first list found
+ for (final v in data.values) {
+ if (v is List) return v;
+ }
+ }
+ }
+ } catch (e) { debugPrint('getUsers error: $e'); }
+ return [];
+ }
+
+ /// Get online users (admin only)
+ Future<List<dynamic>> getOnlineUsers() async {
+ try {
+ final r = await http.get(Uri.parse('$_cleanBaseUrl/api/users/online'), headers: _headers)
+ .timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ if (data is Map && data['usersOnline'] is List) return data['usersOnline'] as List<dynamic>;
+ if (data is Map && data['openSessions'] is List) return data['openSessions'] as List<dynamic>;
+ if (data is List) return data;
+ }
+ } catch (e) { debugPrint('getOnlineUsers error: $e'); }
+ return [];
+ }
+
+ /// Get all listening sessions (admin only)
+ Future<List<dynamic>> getAllSessions({int limit = 25}) async {
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/sessions?itemsPerPage=$limit'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ return (data['sessions'] as List<dynamic>?) ?? [];
+ }
+ } catch (e) { debugPrint('getAllSessions error: $e'); }
+ return [];
+ }
+
+ /// Get all backups (admin only)
+ Future<List<dynamic>> getBackups() async {
+ try {
+ final r = await http.get(Uri.parse('$_cleanBaseUrl/api/backups'), headers: _headers)
+ .timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ return (data['backups'] as List<dynamic>?) ?? [];
+ }
+ } catch (e) { debugPrint('getBackups error: $e'); }
+ return [];
+ }
+
+ /// Create a backup (admin only)
+ Future<bool> createBackup() async {
+ try {
+ final r = await http.post(Uri.parse('$_cleanBaseUrl/api/backups'), headers: _headers)
+ .timeout(const Duration(seconds: 60));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('createBackup error: $e'); }
+ return false;
+ }
+
+ /// Scan a library's folders (admin only)
+ Future<bool> scanLibrary(String libraryId) async {
+ try {
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/scan'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 30));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('scanLibrary error: $e'); }
+ return false;
+ }
+
+ /// Match all items in a library (admin only)
+ Future<bool> matchLibrary(String libraryId) async {
+ try {
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/match'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 30));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('matchLibrary error: $e'); }
+ return false;
+ }
+
+ /// Get library stats (admin only)
+ Future<Map<String, dynamic>?> getLibraryStats(String libraryId) async {
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/stats'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;
+ } catch (e) { debugPrint('getLibraryStats error: $e'); }
+ return null;
+ }
+
+ /// Purge server cache (admin only)
+ Future<bool> purgeCache() async {
+ try {
+ final r = await http.post(Uri.parse('$_cleanBaseUrl/api/cache/purge'), headers: _headers)
+ .timeout(const Duration(seconds: 30));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('purgeCache error: $e'); }
+ return false;
+ }
+
+ /// Create a new user (admin only)
+ Future<Map<String, dynamic>?> createUser({
+ required String username,
+ required String password,
+ required String type,
+ Map<String, dynamic>? permissions,
+ List<String>? librariesAccessible,
+ }) async {
+ try {
+ final body = <String, dynamic>{
+ 'username': username,
+ 'password': password,
+ 'type': type,
+ };
+ if (permissions != null) body['permissions'] = permissions;
+ if (librariesAccessible != null) body['librariesAccessible'] = librariesAccessible;
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/users'),
+ headers: _headers,
+ body: jsonEncode(body),
+ ).timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;
+ } catch (e) { debugPrint('createUser error: $e'); }
+ return null;
+ }
+
+ /// Get a single user with full details including mediaProgress (admin only)
+ Future<Map<String, dynamic>?> getUser(String userId) async {
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/users/$userId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;
+ } catch (e) { debugPrint('getUser error: $e'); }
+ return null;
+ }
+
+ /// Update a user (admin only)
+ Future<bool> updateUser(String userId, Map<String, dynamic> updates) async {
+ try {
+ final r = await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/users/$userId'),
+ headers: _headers,
+ body: jsonEncode(updates),
+ ).timeout(const Duration(seconds: 15));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('updateUser error: $e'); }
+ return false;
+ }
+
+ /// Delete a user (admin only)
+ Future<bool> deleteUser(String userId) async {
+ try {
+ final r = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/users/$userId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('deleteUser error: $e'); }
+ return false;
+ }
+
+ // ─── Podcast Endpoints ────────────────────────────────────
+
+ /// Search for podcasts (uses iTunes)
+ Future<List<dynamic>> searchPodcasts(String query) async {
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/search/podcast?term=${Uri.encodeComponent(query)}'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ if (data is List) return data;
+ if (data is Map) {
+ if (data['podcasts'] is List) return data['podcasts'] as List<dynamic>;
+ for (final key in data.keys) {
+ if (data[key] is List) return data[key] as List<dynamic>;
+ }
+ }
+ }
+ } catch (e) { debugPrint('searchPodcasts error: $e'); }
+ return [];
+ }
+
+ /// Create a podcast (add to library from feed URL)
+ Future<Map<String, dynamic>?> createPodcast({
+ required String libraryId,
+ required String folderId,
+ required String feedUrl,
+ required Map<String, dynamic> podcastData,
+ bool autoDownloadEpisodes = false,
+ String? autoDownloadSchedule,
+ }) async {
+ try {
+ // ABS search returns: id, artistId, title, artistName, description,
+ // descriptionPlain, releaseDate, genres, cover, trackCount, feedUrl,
+ // pageUrl, explicit
+ final title = podcastData['title'] as String? ?? 'Podcast';
+
+ // Build the podcast path from the library folder + title
+ String podcastPath = '';
+ try {
+ final libs = await getLibraries();
+ final lib = libs.firstWhere((l) => l['id'] == libraryId, orElse: () => <String, dynamic>{});
+ final folders = lib['folders'] as List?;
+ if (folders != null && folders.isNotEmpty) {
+ final folder = folders.firstWhere((f) => f['id'] == folderId, orElse: () => folders.first);
+ final folderPath = folder['fullPath'] as String? ?? '';
+ if (folderPath.isNotEmpty) {
+ final cleanTitle = title.replaceAll(RegExp(r'[\\/:*?"<>|]'), '');
+ podcastPath = '$folderPath/$cleanTitle';
+ }
+ }
+ } catch (_) {}
+
+ final body = <String, dynamic>{
+ 'libraryId': libraryId,
+ 'folderId': folderId,
+ 'path': podcastPath,
+ 'media': {
+ 'metadata': {
+ 'title': title,
+ 'author': podcastData['artistName'] ?? '',
+ 'description': podcastData['description'] ?? podcastData['descriptionPlain'] ?? '',
+ 'releaseDate': podcastData['releaseDate'] ?? '',
+ 'genres': podcastData['genres'] ?? [],
+ 'feedUrl': feedUrl,
+ 'imageUrl': podcastData['cover'] ?? podcastData['imageUrl'] ?? '',
+ 'itunesPageUrl': podcastData['pageUrl'] ?? '',
+ 'itunesId': podcastData['id'],
+ 'itunesArtistId': podcastData['artistId'],
+ 'explicit': podcastData['explicit'] ?? false,
+ 'language': podcastData['language'],
+ },
+ 'autoDownloadEpisodes': autoDownloadEpisodes,
+ 'autoDownloadSchedule': autoDownloadSchedule ?? '0 0 * * 1',
+ },
+ };
+ final bodyJson = jsonEncode(body);
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/podcasts'),
+ headers: _headers,
+ body: bodyJson,
+ ).timeout(const Duration(seconds: 30));
+ if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;
+ } catch (e) { debugPrint('createPodcast error: $e'); }
+ return null;
+ }
+
+ /// Get a podcast's RSS feed episodes by feed URL
+ /// POST /api/podcasts/feed body: { "rssFeed": "https://..." }
+ Future<Map<String, dynamic>?> getPodcastFeed(String rssFeedUrl) async {
+ try {
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/podcasts/feed'),
+ headers: _headers,
+ body: jsonEncode({'rssFeed': rssFeedUrl}),
+ ).timeout(const Duration(seconds: 20));
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body);
+ if (data is Map<String, dynamic>) return data;
+ }
+ } catch (e) { debugPrint('getPodcastFeed error: $e'); }
+ return null;
+ }
+
+ /// Get podcast episode download queue for a library
+ Future<Map<String, dynamic>?> getEpisodeDownloads(String libraryId) async {
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/episode-downloads'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;
+ } catch (e) { debugPrint('getEpisodeDownloads error: $e'); }
+ return null;
+ }
+
+ /// Download specific podcast episodes
+ Future<bool> downloadPodcastEpisodes(String libraryItemId, List<Map<String, dynamic>> episodes) async {
+ try {
+ final r = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/podcasts/$libraryItemId/download-episodes'),
+ headers: _headers, body: jsonEncode(episodes),
+ ).timeout(const Duration(seconds: 30));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('downloadPodcastEpisodes error: $e'); }
+ return false;
+ }
+
+ /// Check for new podcast episodes across all podcasts in a library
+ /// Uses per-podcast check since there's no single library-level endpoint
+ Future<bool> checkNewEpisodes(String libraryId) async {
+ try {
+ // First get all podcast items in the library
+ final items = await getLibraryItems(libraryId, limit: 100);
+ final results = items?['results'] as List? ?? [];
+ if (results.isEmpty) return false;
+
+ // Trigger check on each podcast
+ int success = 0;
+ for (final item in results) {
+ final libItem = item is Map ? (item['libraryItem'] ?? item) : item;
+ final id = libItem is Map ? libItem['id'] as String? : null;
+ if (id == null) continue;
+ try {
+ final r = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/podcasts/$id/checknew'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (r.statusCode == 200) success++;
+ } catch (_) {}
+ }
+ return success > 0;
+ } catch (e) { debugPrint('checkNewEpisodes error: $e'); }
+ return false;
+ }
+
+ /// Delete a podcast episode
+ Future<bool> deletePodcastEpisode(String podcastId, String episodeId) async {
+ try {
+ final r = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/podcasts/$podcastId/episode/$episodeId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('deletePodcastEpisode error: $e'); }
+ return false;
+ }
+}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
new file mode 100644
index 00000000..50d4612b
--- /dev/null
+++ b/lib/services/audio_player_service.dart
@@ -0,0 +1,1592 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:math';
+import 'package:flutter/material.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:audio_service/audio_service.dart';
+import 'package:audio_session/audio_session.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'api_service.dart';
+import 'download_service.dart';
+import 'playback_history_service.dart' hide PlaybackEvent;
+import 'progress_sync_service.dart';
+import 'sleep_timer_service.dart';
+import 'equalizer_service.dart';
+import 'android_auto_service.dart';
+import 'chromecast_service.dart';
+
+// ─── Auto-rewind settings ───
+
+class AutoRewindSettings {
+ final bool enabled;
+ final double minRewind;
+ final double maxRewind;
+ final double activationDelay; // seconds — how long pause must be before rewind kicks in
+
+ const AutoRewindSettings({
+ this.enabled = true,
+ this.minRewind = 1.0,
+ this.maxRewind = 30.0,
+ this.activationDelay = 0.0, // 0 = always rewind on resume
+ });
+
+ static Future<AutoRewindSettings> load() async {
+ final prefs = await SharedPreferences.getInstance();
+ return AutoRewindSettings(
+ enabled: prefs.getBool('autoRewind_enabled') ?? true,
+ minRewind: prefs.getDouble('autoRewind_min') ?? 1.0,
+ maxRewind: prefs.getDouble('autoRewind_max') ?? 30.0,
+ activationDelay: prefs.getDouble('autoRewind_delay') ?? 0.0,
+ );
+ }
+
+ Future<void> save() async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('autoRewind_enabled', enabled);
+ await prefs.setDouble('autoRewind_min', minRewind);
+ await prefs.setDouble('autoRewind_max', maxRewind);
+ await prefs.setDouble('autoRewind_delay', activationDelay);
+ }
+}
+
+class PlayerSettings {
+ /// Notifier that fires when any player setting changes.
+ /// Widgets can listen to this instead of polling SharedPreferences.
+ static final ChangeNotifier settingsChanged = ChangeNotifier();
+ static void _notify() {
+ // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
+ settingsChanged.notifyListeners();
+ }
+
+ // ── Private helpers to eliminate boilerplate ──
+
+ static Future<T> _get<T>(String key, T defaultValue) async {
+ final prefs = await SharedPreferences.getInstance();
+ final value = prefs.get(key);
+ if (value is T) return value;
+ return defaultValue;
+ }
+
+ static Future<void> _set<T>(String key, T value, {bool notify = false}) async {
+ final prefs = await SharedPreferences.getInstance();
+ if (value is bool) {
+ await prefs.setBool(key, value);
+ } else if (value is int) {
+ await prefs.setInt(key, value);
+ } else if (value is double) {
+ await prefs.setDouble(key, value);
+ } else if (value is String) {
+ await prefs.setString(key, value);
+ }
+ if (notify) _notify();
+ }
+
+ // ── General settings ──
+
+ static Future<double> getDefaultSpeed() => _get('defaultSpeed', 1.0);
+ static Future<void> setDefaultSpeed(double speed) => _set('defaultSpeed', speed);
+
+ static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);
+ static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);
+
+ static Future<bool> getAutoContinueSeries() => _get('autoContinueSeries', true);
+ static Future<void> setAutoContinueSeries(bool value) => _set('autoContinueSeries', value);
+
+ // ── Player UI settings (notify listeners on change) ──
+
+ static Future<bool> getShowBookSlider() => _get('showBookSlider', false);
+ static Future<void> setShowBookSlider(bool value) => _set('showBookSlider', value, notify: true);
+
+ static Future<bool> getSpeedAdjustedTime() => _get('speedAdjustedTime', true);
+ static Future<void> setSpeedAdjustedTime(bool value) => _set('speedAdjustedTime', value, notify: true);
+
+ static Future<int> getForwardSkip() => _get('forwardSkip', 30);
+ static Future<void> setForwardSkip(int seconds) => _set('forwardSkip', seconds, notify: true);
+
+ static Future<int> getBackSkip() => _get('backSkip', 10);
+ static Future<void> setBackSkip(int seconds) => _set('backSkip', seconds, notify: true);
+
+ // ── Sleep timer settings ──
+
+ static Future<bool> getShakeToResetSleep() => _get('shakeToResetSleep', true);
+ static Future<void> setShakeToResetSleep(bool value) => _set('shakeToResetSleep', value);
+
+ static Future<int> getShakeAddMinutes() => _get('shakeAddMinutes', 5);
+ static Future<void> setShakeAddMinutes(int minutes) => _set('shakeAddMinutes', minutes);
+
+ static Future<bool> getResetSleepOnPause() => _get('resetSleepOnPause', false);
+ static Future<void> setResetSleepOnPause(bool value) => _set('resetSleepOnPause', value);
+
+ static Future<bool> getHideEbookOnly() => _get('hideEbookOnly', false);
+ static Future<void> setHideEbookOnly(bool value) => _set('hideEbookOnly', value, notify: true);
+
+ static Future<bool> getShowGoodreadsButton() => _get('showGoodreadsButton', false);
+ static Future<void> setShowGoodreadsButton(bool value) => _set('showGoodreadsButton', value);
+
+ /// Check if an item has no audio content.
+ /// For minified responses (library list), duration == 0 means no audio files.
+ /// For full responses (detail sheet), we also check ebookFile + audioFiles.
+ static bool isEbookOnly(Map<String, dynamic> item) {
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ if (duration > 0) return false; // Has audio content
+ // No duration — check if there's any audio indicator at all
+ final audioFiles = media['audioFiles'] as List<dynamic>?;
+ final tracks = media['tracks'] as List<dynamic>?;
+ final numAudioFiles = (media['numAudioFiles'] as num?)?.toInt() ?? 0;
+ if ((audioFiles != null && audioFiles.isNotEmpty) ||
+ (tracks != null && tracks.isNotEmpty) ||
+ numAudioFiles > 0) return false;
+ return true; // No audio by any measure
+ }
+
+ // ── Per-book speed persistence ──
+
+ static Future<double?> getBookSpeed(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getDouble('bookSpeed_$itemId');
+ }
+
+ static Future<void> setBookSpeed(String itemId, double speed) =>
+ _set('bookSpeed_$itemId', speed);
+}
+
+// ─── AudioHandler (runs in background, controls notification) ───
+
+class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
+ final AudioPlayer _player = AudioPlayer(
+ handleInterruptions: false,
+ );
+ AudioPlayerService? _service; // back-reference for auto-rewind
+
+ AudioPlayer get player => _player;
+
+ void bindService(AudioPlayerService service) => _service = service;
+
+ AudioPlayerHandler() {
+ _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
+ }
+
+ PlaybackState _transformEvent(PlaybackEvent event) {
+ return PlaybackState(
+ controls: [
+ MediaControl.rewind,
+ if (_player.playing) MediaControl.pause else MediaControl.play,
+ MediaControl.fastForward,
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ androidCompactActionIndices: const [0, 1, 2],
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: _player.playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ // Report actual speed — always
+ speed: _player.speed,
+ queueIndex: event.currentIndex,
+ );
+ }
+
+ @override
+ Future<void> play() async {
+ debugPrint('[Handler] play() called — routing to service');
+ if (_service != null) {
+ await _service!.play();
+ } else {
+ await _player.play();
+ }
+ }
+
+ @override
+ Future<void> pause() async {
+ debugPrint('[Handler] pause() called — routing to service');
+ if (_service != null) {
+ await _service!.pause();
+ } else {
+ await _player.pause();
+ }
+ }
+
+ @override
+ Future<void> seek(Duration position) {
+ debugPrint('[Handler] seek(${position.inSeconds}s)');
+ return _player.seek(position);
+ }
+
+ @override
+ Future<void> stop() async {
+ debugPrint('[Handler] stop()');
+ await _player.stop();
+ return super.stop();
+ }
+
+ /// Called when the user swipes the app away from recents.
+ @override
+ Future<void> onTaskRemoved() async {
+ debugPrint('[Handler] onTaskRemoved — app swiped away');
+ // Stop playback and sync via the service if available
+ if (_service != null) {
+ await _service!.pause();
+ await _service!.stop();
+ } else {
+ await _player.stop();
+ }
+ await super.onTaskRemoved();
+ }
+
+ @override
+ Future<void> fastForward() async {
+ debugPrint('[Handler] fastForward() — seeking forward');
+ if (_service != null) {
+ final skipAmount = await PlayerSettings.getForwardSkip();
+ await _service!.skipForward(skipAmount);
+ } else {
+ final skipAmount = await PlayerSettings.getForwardSkip();
+ await _player.seek(_player.position + Duration(seconds: skipAmount));
+ }
+ }
+
+ @override
+ Future<void> rewind() async {
+ debugPrint('[Handler] rewind() — seeking back');
+ if (_service != null) {
+ final skipAmount = await PlayerSettings.getBackSkip();
+ await _service!.skipBackward(skipAmount);
+ } else {
+ final skipAmount = await PlayerSettings.getBackSkip();
+ var pos = _player.position - Duration(seconds: skipAmount);
+ if (pos < Duration.zero) pos = Duration.zero;
+ await _player.seek(pos);
+ }
+ }
+
+ // Note: skipToNext/skipToPrevious are intentionally NOT overridden here.
+ // Android Auto renders controls based on which actions the handler declares.
+ // Overriding skip methods causes Auto to show track-skip icons instead
+ // of the rewind/forward circular arrows we want for audiobooks.
+ // Headset button presses route through onClick() below instead.
+
+ // Custom click handler with proper multi-press detection
+ Timer? _clickTimer;
+ int _clickCount = 0;
+ DateTime? _hardwareButtonTime; // cooldown after hardware next/prev
+
+ @override
+ Future<void> click([MediaButton button = MediaButton.media]) async {
+ debugPrint('[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}');
+
+ if (button != MediaButton.media) {
+ // Hardware next/prev button — set cooldown to ignore phantom media click
+ _hardwareButtonTime = DateTime.now();
+ if (button == MediaButton.next) {
+ debugPrint('[Handler] Hardware NEXT button');
+ await fastForward();
+ } else if (button == MediaButton.previous) {
+ debugPrint('[Handler] Hardware PREV button');
+ await rewind();
+ }
+ return;
+ }
+
+ // Ignore phantom media click that follows hardware next/prev within 500ms
+ if (_hardwareButtonTime != null) {
+ final elapsed = DateTime.now().difference(_hardwareButtonTime!).inMilliseconds;
+ if (elapsed < 500) {
+ debugPrint('[Handler] Ignoring phantom media click (${elapsed}ms after hardware button)');
+ _hardwareButtonTime = null;
+ return;
+ }
+ _hardwareButtonTime = null;
+ }
+
+ _clickCount++;
+ _clickTimer?.cancel();
+ _clickTimer = Timer(const Duration(milliseconds: 400), () async {
+ final count = _clickCount;
+ _clickCount = 0;
+ debugPrint('[Handler] click resolved: count=$count playing=${_player.playing}');
+ switch (count) {
+ case 1:
+ if (_player.playing) {
+ debugPrint('[Handler] → single press → PAUSE');
+ await pause();
+ } else {
+ debugPrint('[Handler] → single press → PLAY');
+ await play();
+ }
+ break;
+ case 2:
+ debugPrint('[Handler] → double press → SKIP FORWARD');
+ await fastForward();
+ break;
+ case 3:
+ default:
+ debugPrint('[Handler] → triple press → SKIP BACK');
+ await rewind();
+ break;
+ }
+ });
+ }
+
+ @override
+ Future<void> setSpeed(double speed) => _player.setSpeed(speed);
+
+ // ─── Android Auto browse tree ──────────────────────────────────────
+
+ final _autoService = AndroidAutoService();
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async {
+ debugPrint('[Handler] getChildren($parentMediaId)');
+ // Don't await refresh() here — getChildrenOf() handles it:
+ // downloads are populated instantly, server data loads in background.
+ return _autoService.getChildrenOf(parentMediaId);
+ }
+
+ @override
+ Future<MediaItem?> getMediaItem(String mediaId) async {
+ debugPrint('[Handler] getMediaItem($mediaId)');
+ return _autoService.getMediaItem(mediaId);
+ }
+
+ @override
+ Future<List<MediaItem>> search(String query,
+ [Map<String, dynamic>? extras]) async {
+ debugPrint('[Handler] search("$query")');
+ return _autoService.search(query);
+ }
+
+ @override
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) async {
+ debugPrint('[Handler] prepareFromMediaId($mediaId)');
+ await _playFromAutoMediaId(mediaId);
+ }
+
+ @override
+ Future<void> playFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) async {
+ debugPrint('[Handler] playFromMediaId($mediaId)');
+ await _playFromAutoMediaId(mediaId);
+ }
+
+ Future<void> _playFromAutoMediaId(String mediaId) async {
+ final absId = AutoMediaIds.absItemId(mediaId);
+ if (absId == null) {
+ debugPrint('[Handler] Invalid media ID for playback: $mediaId');
+ return;
+ }
+
+ if (_service == null) {
+ debugPrint('[Handler] No service bound — cannot play');
+ return;
+ }
+
+ final api = await _autoService.getApi();
+ if (api == null) {
+ debugPrint('[Handler] No API credentials — cannot play');
+ return;
+ }
+
+ // Try to find in cached entries first
+ var entry = _autoService.findEntry(absId);
+
+ // If not in cache (e.g. from series/author drilldown or search),
+ // fetch the item details from server
+ if (entry == null) {
+ debugPrint('[Handler] Book not cached, fetching from server: $absId');
+ try {
+ final response = await api.getLibraryItem(absId);
+ if (response != null) {
+ final media = response['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};
+ entry = AutoBookEntry(
+ id: absId,
+ title: metadata['title'] as String? ?? 'Unknown',
+ author: metadata['authorName'] as String? ?? '',
+ duration: (media?['duration'] as num?)?.toDouble() ?? 0,
+ coverUrl: api.getCoverUrl(absId, width: 400),
+ chapters: media?['chapters'] as List<dynamic>? ?? [],
+ );
+ }
+ } catch (e) {
+ debugPrint('[Handler] Error fetching item: $e');
+ }
+ }
+
+ if (entry == null) {
+ debugPrint('[Handler] Book not found: $absId');
+ return;
+ }
+
+ debugPrint('[Handler] Android Auto play: "${entry.title}" by ${entry.author}');
+
+ // Always generate a fresh HTTP cover URL for Now Playing — api is
+ // available here, so use it directly rather than relying on the cached
+ // entry.coverUrl (which may be a content:// URI when offline).
+ final nowPlayingCoverUrl = api.getCoverUrl(absId, width: 400);
+
+ await _service!.playItem(
+ api: api,
+ itemId: entry.id,
+ title: entry.title,
+ author: entry.author,
+ coverUrl: nowPlayingCoverUrl,
+ totalDuration: entry.duration,
+ chapters: entry.chapters,
+ startTime: entry.currentTime ?? 0,
+ );
+ }
+}
+
+// ─── Singleton service ───
+
+class AudioPlayerService extends ChangeNotifier {
+ static final AudioPlayerService _instance = AudioPlayerService._();
+ factory AudioPlayerService() => _instance;
+ AudioPlayerService._();
+
+ /// Called when a book completes naturally (before player state is cleared).
+ /// Register via [setOnBookFinishedCallback]. Used by LibraryProvider to
+ /// update local finished state immediately without waiting for a server refresh.
+ static void Function(String itemId)? _onBookFinishedCallback;
+ static void setOnBookFinishedCallback(void Function(String itemId)? cb) {
+ _onBookFinishedCallback = cb;
+ }
+
+ /// Called when a podcast episode starts playing. Used by AppShell to
+ /// auto-navigate to the Absorbing tab.
+ static void Function()? _onEpisodePlayStartedCallback;
+ static void setOnEpisodePlayStartedCallback(void Function()? cb) {
+ _onEpisodePlayStartedCallback = cb;
+ }
+
+ static AudioPlayerHandler? _handler;
+ AudioPlayer? get _player => _handler?.player;
+
+ String? _currentItemId;
+ String? _currentTitle;
+ String? _currentAuthor;
+ String? _currentCoverUrl;
+ double _totalDuration = 0;
+ List<dynamic> _chapters = [];
+ ApiService? _api;
+ String? _playbackSessionId;
+ bool _isOfflineMode = false;
+ StreamSubscription? _syncSub;
+ // ── Multi-file track offset tracking ──
+ // For ConcatenatingAudioSource, _player.position is track-relative.
+ // We store cumulative start offsets so we can compute absolute book position.
+ List<double> _trackStartOffsets = []; // [0, dur0, dur0+dur1, ...]
+ int _currentTrackIndex = 0;
+ int _lastNotifiedChapterIndex = -1;
+ StreamSubscription? _indexSub;
+
+ /// The last seek target in seconds (absolute book position).
+ /// UI can use this to immediately snap to the target before stream catches up.
+ double? _lastSeekTargetSeconds;
+ DateTime? _lastSeekTime;
+
+ /// If a seek happened within the last 2 seconds, returns the seek target.
+ /// Otherwise returns null (use the stream position).
+ double? get activeSeekTarget {
+ if (_lastSeekTargetSeconds == null || _lastSeekTime == null) return null;
+ final elapsed = DateTime.now().difference(_lastSeekTime!).inMilliseconds;
+ if (elapsed > 2000) {
+ _lastSeekTargetSeconds = null;
+ _lastSeekTime = null;
+ return null;
+ }
+ return _lastSeekTargetSeconds;
+ }
+
+ final _progressSync = ProgressSyncService();
+ final _downloadService = DownloadService();
+ final _history = PlaybackHistoryService();
+
+ /// Log a playback event to history.
+ void _logEvent(PlaybackEventType type, {String? detail}) {
+ if (_currentItemId == null) return;
+ _history.log(
+ itemId: _currentItemId!,
+ type: type,
+ positionSeconds: position.inMilliseconds / 1000.0,
+ detail: detail,
+ );
+ }
+
+ static String _formatPos(Duration d) {
+ final h = d.inHours;
+ final m = d.inMinutes % 60;
+ final s = d.inSeconds % 60;
+ if (h > 0) return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ return '$m:${s.toString().padLeft(2, '0')}';
+ }
+
+ String? get currentItemId => _currentItemId;
+ String? get currentTitle => _currentTitle;
+ String? get currentAuthor => _currentAuthor;
+ String? get currentCoverUrl => _currentCoverUrl;
+ double get totalDuration => _totalDuration;
+ List<dynamic> get chapters => _chapters;
+
+ void updateChapters(List<dynamic> chapters) {
+ _chapters = chapters;
+ notifyListeners();
+ }
+ bool get hasBook => _currentItemId != null;
+ bool get isPlaying => _player?.playing ?? false;
+ bool get isOfflineMode => _isOfflineMode;
+
+ Stream<Duration> get positionStream =>
+ _player?.positionStream ?? const Stream.empty();
+ Stream<Duration?> get durationStream =>
+ _player?.durationStream ?? const Stream.empty();
+ Stream<PlayerState> get playerStateStream =>
+ _player?.playerStateStream ?? const Stream.empty();
+
+ /// Absolute book position (accounts for multi-file track offsets).
+ Duration get position {
+ if (_player == null) return Duration.zero;
+ final trackRelative = _player!.position;
+ if (_trackStartOffsets.length <= 1) return trackRelative; // single file
+ final offsetMs = (_trackStartOffsets[_currentTrackIndex] * 1000).round();
+ final result = trackRelative + Duration(milliseconds: offsetMs);
+ // Don't log every call — this is called very frequently by sync and UI
+ return result;
+ }
+
+ /// Absolute book position stream (adjusted for multi-file offsets).
+ /// IMPORTANT: Always returns a mapped stream that checks offsets at event time.
+ /// Do NOT short-circuit to raw positionStream — the caller may subscribe before
+ /// track offsets are built, and would miss the offset transform forever.
+ Stream<Duration> get absolutePositionStream {
+ if (_player == null) return const Stream.empty();
+ return _player!.positionStream.map((trackRelative) {
+ if (_trackStartOffsets.length <= 1) return trackRelative; // single file, no offset
+ final trackIdx = _currentTrackIndex;
+ final offsetMs = (_trackStartOffsets[trackIdx] * 1000).round();
+ final absolute = trackRelative + Duration(milliseconds: offsetMs);
+ return absolute;
+ });
+ }
+
+ Duration get duration => _player?.duration ?? Duration.zero;
+ double get speed => _player?.speed ?? 1.0;
+
+ /// Build track start offsets from audioTracks list.
+ void _buildTrackOffsets(List<dynamic> audioTracks) {
+ _trackStartOffsets = [0.0];
+ double acc = 0;
+ for (final t in audioTracks) {
+ final track = t as Map<String, dynamic>;
+ final dur = (track['duration'] as num?)?.toDouble() ?? 0;
+ acc += dur;
+ _trackStartOffsets.add(acc);
+ }
+ debugPrint('[Player] Track offsets: $_trackStartOffsets');
+ }
+
+ /// Subscribe to track index changes for multi-file playback.
+ void _subscribeTrackIndex() {
+ _indexSub?.cancel();
+ if (_player == null || _trackStartOffsets.length <= 1) return;
+ _indexSub = _player!.currentIndexStream.listen((index) {
+ if (index != null) {
+ _currentTrackIndex = index.clamp(0, _trackStartOffsets.length - 2);
+ }
+ });
+ }
+
+ /// Seek to an absolute book position, handling multi-file offset conversion.
+ Future<void> _seekAbsolute(double absoluteSeconds) async {
+ if (_player == null) return;
+
+ // Record seek target so UI can snap immediately
+ _lastSeekTargetSeconds = absoluteSeconds;
+ _lastSeekTime = DateTime.now();
+
+ if (_trackStartOffsets.length <= 1) {
+ // Single file — seek directly
+ await _player!.seek(Duration(milliseconds: (absoluteSeconds * 1000).round()));
+ return;
+ }
+ // Multi-file — find the right track and local offset
+ for (int i = 0; i < _trackStartOffsets.length - 1; i++) {
+ final trackStart = _trackStartOffsets[i];
+ final trackEnd = _trackStartOffsets[i + 1];
+ if (absoluteSeconds < trackEnd || i == _trackStartOffsets.length - 2) {
+ final localOffset = absoluteSeconds - trackStart;
+ // Update index BEFORE seeking so positionStream events use the right offset
+ _currentTrackIndex = i;
+ await _player!.seek(Duration(milliseconds: (localOffset * 1000).round()), index: i);
+ return;
+ }
+ }
+ }
+
+ /// MUST be called after Activity is ready.
+ static Future<void> init() async {
+ _handler = await AudioService.init<AudioPlayerHandler>(
+ builder: () => AudioPlayerHandler(),
+ config: AudioServiceConfig(
+ androidNotificationChannelId: 'com.audiobookshelf.app.channel.audio',
+ androidNotificationChannelName: 'Absorb',
+ androidNotificationOngoing: true,
+ androidStopForegroundOnPause: true,
+ androidNotificationIcon: 'drawable/ic_notification',
+ androidBrowsableRootExtras: {
+ AndroidContentStyle.supportedKey: true,
+ AndroidContentStyle.browsableHintKey:
+ AndroidContentStyle.categoryListItemHintValue,
+ AndroidContentStyle.playableHintKey:
+ AndroidContentStyle.gridItemHintValue,
+ 'android.media.browse.SEARCH_SUPPORTED': true,
+ },
+ ),
+ );
+ // Bind service so handler routes play/pause through service (for auto-rewind)
+ _handler!.bindService(_instance);
+ debugPrint('[Player] AudioService initialized');
+
+ // Configure audio session for audiobook playback
+ await _configureAudioSession();
+ }
+
+ static StreamSubscription? _interruptSub;
+ static StreamSubscription? _noisySub;
+
+ static Future<void> _configureAudioSession() async {
+ final session = await AudioSession.instance;
+ await session.configure(const AudioSessionConfiguration.speech());
+
+ _interruptSub?.cancel();
+ _interruptSub = session.interruptionEventStream.listen((event) async {
+ final service = _instance;
+
+ if (event.begin) {
+ if (service.isPlaying) {
+ debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');
+ service._wasPlayingBeforeInterrupt = true;
+ await service.pause();
+ }
+ } else {
+ if (service._wasPlayingBeforeInterrupt) {
+ debugPrint('[AudioSession] Interruption ended — resuming');
+ service._wasPlayingBeforeInterrupt = false;
+ await Future.delayed(const Duration(milliseconds: 300));
+ await service.play();
+ }
+ }
+ });
+
+ // Headphones unplugged — pause, no auto-resume
+ _noisySub?.cancel();
+ _noisySub = session.becomingNoisyEventStream.listen((_) async {
+ final service = _instance;
+ if (service.isPlaying) {
+ debugPrint('[AudioSession] Becoming noisy — pausing');
+ await service.pause();
+ }
+ });
+ }
+
+ String? _currentEpisodeId;
+ String? get currentEpisodeId => _currentEpisodeId;
+
+ String? _currentEpisodeTitle;
+ String? get currentEpisodeTitle => _currentEpisodeTitle;
+
+ Future<bool> playItem({
+ required ApiService api,
+ required String itemId,
+ required String title,
+ required String author,
+ required String? coverUrl,
+ required double totalDuration,
+ required List<dynamic> chapters,
+ double startTime = 0,
+ String? episodeId,
+ String? episodeTitle,
+ }) async {
+ if (_handler == null) {
+ debugPrint('[Player] Handler not initialized!');
+ return false;
+ }
+
+ // Stop Chromecast if currently casting
+ final cast = ChromecastService();
+ if (cast.isCasting) {
+ debugPrint('[Player] Stopping Chromecast before local playback');
+ await cast.stopCasting();
+ }
+
+ _api = api;
+ _currentItemId = itemId;
+ _currentEpisodeId = episodeId;
+ _currentEpisodeTitle = episodeTitle;
+ _currentTitle = title;
+ _currentAuthor = author;
+ _currentCoverUrl = coverUrl;
+ _totalDuration = totalDuration;
+ _chapters = chapters;
+ // New book = fresh session — clear any auto sleep dismissal
+ SleepTimerService().resetDismiss();
+ notifyListeners();
+
+ // Progress key: compound for episodes, plain for books
+ final progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;
+
+ // Check for local saved position (always prefer local — it's the freshest)
+ final localPos = await _progressSync.getSavedPosition(progressKey);
+ if (localPos > 0 && startTime == 0) {
+ startTime = localPos;
+ debugPrint('[Player] Resuming from local position: ${startTime}s');
+ }
+
+ // Check if downloaded — play locally
+ final bool result;
+ if (_downloadService.isDownloaded(progressKey)) {
+ result = await _playFromLocal(progressKey, title, author, coverUrl,
+ totalDuration, chapters, startTime);
+ } else {
+ // Check manual offline — don't stream from server
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ if (manualOffline) {
+ debugPrint('[Player] Manual offline — cannot stream non-downloaded item');
+ _clearState();
+ return false;
+ }
+ // Stream from server
+ result = await _playFromServer(api, itemId, title, author, coverUrl,
+ totalDuration, chapters, startTime);
+ }
+
+ // Auto-navigate to Absorbing tab when an episode starts playing
+ if (result && episodeId != null) {
+ _onEpisodePlayStartedCallback?.call();
+ }
+ return result;
+ }
+
+ /// Hot-swap from streaming to local files without interrupting playback position.
+ /// Called when a download completes for the currently-playing item.
+ Future<bool> switchToLocal(String itemId) async {
+ if (_currentItemId != itemId) return false;
+ if (!_downloadService.isDownloaded(itemId)) return false;
+ if (_player == null) return false;
+
+ final wasPlaying = _player!.playing;
+ final currentAbsolutePos = position; // use absolute position getter
+ final currentSpeed = _player!.speed;
+
+ debugPrint('[Player] Hot-swapping to local files at ${currentAbsolutePos.inSeconds}s');
+
+ final localPaths = _downloadService.getLocalPaths(itemId);
+ if (localPaths == null || localPaths.isEmpty) return false;
+
+ // Get cached session data for track durations (multi-file seeking)
+ final cachedJson = _downloadService.getCachedSessionData(itemId);
+ List<dynamic>? audioTracks;
+ if (cachedJson != null) {
+ try {
+ final session = jsonDecode(cachedJson) as Map<String, dynamic>;
+ audioTracks = session['audioTracks'] as List<dynamic>?;
+ } catch (_) {}
+ }
+
+ // Rebuild track offsets for local files
+ if (audioTracks != null) {
+ _buildTrackOffsets(audioTracks);
+ } else {
+ _trackStartOffsets = [0.0];
+ }
+ _currentTrackIndex = 0;
+
+ try {
+ AudioSource source;
+ if (localPaths.length == 1) {
+ source = AudioSource.file(localPaths.first);
+ } else {
+ final sources = localPaths.map((p) => AudioSource.file(p) as AudioSource).toList();
+ source = ConcatenatingAudioSource(children: sources);
+ }
+
+ await _player!.setAudioSource(source);
+
+ // Seek to the same absolute position
+ final posSeconds = currentAbsolutePos.inMilliseconds / 1000.0;
+ await _seekAbsolute(posSeconds);
+
+ _subscribeTrackIndex();
+
+ // Restore speed
+ await _player!.setSpeed(currentSpeed);
+
+ // Resume if was playing
+ if (wasPlaying) _player!.play();
+
+ _logEvent(PlaybackEventType.play, detail: 'Switched to local playback');
+ debugPrint('[Player] Hot-swap complete — now playing from local files');
+ notifyListeners();
+ return true;
+ } catch (e) {
+ debugPrint('[Player] Hot-swap failed: $e');
+ return false;
+ }
+ }
+
+ Future<bool> _playFromLocal(
+ String itemId,
+ String title,
+ String author,
+ String? coverUrl,
+ double totalDuration,
+ List<dynamic> chapters,
+ double startTime,
+ ) async {
+ debugPrint('[Player] Playing from local files: $title');
+ _isOfflineMode = false; // We still sync to server if possible
+ _playbackSessionId = null;
+
+ // Check if manual offline mode is on
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ debugPrint('[Player] manualOffline=$manualOffline, api=${_api != null}');
+
+ // Try to start a server session for sync (unless manual offline)
+ if (_api != null && !manualOffline) {
+ try {
+ debugPrint('[Player] Starting server session for local playback...');
+ final sessionData = _currentEpisodeId != null
+ ? await _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)
+ : await _api!.startPlaybackSession(itemId);
+ if (sessionData != null) {
+ _playbackSessionId = sessionData['id'] as String?;
+ debugPrint('[Player] Got server session for local playback: $_playbackSessionId');
+
+ // Compare server position vs local position — last-write-wins
+ final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
+ if (serverPos > 0) {
+ // Get local timestamp to compare
+ final localData = await _progressSync.getLocal(itemId);
+ final localTimestamp = (localData?['timestamp'] as num?)?.toInt() ?? 0;
+
+ // Server session has updatedAt in epoch ms
+ final serverTimestamp = (sessionData['updatedAt'] as num?)?.toInt() ?? 0;
+
+ if (serverTimestamp > localTimestamp && (serverPos - startTime).abs() > 1.0) {
+ debugPrint('[Player] Server position is newer: server=${serverPos}s ($serverTimestamp) vs local=${startTime}s ($localTimestamp) — using server');
+ startTime = serverPos;
+ // Update local to match
+ await _progressSync.saveLocal(
+ itemId: itemId,
+ currentTime: serverPos,
+ duration: totalDuration,
+ speed: 1.0,
+ );
+ } else if (startTime == 0 && serverPos > 0) {
+ debugPrint('[Player] No local position, using server: ${serverPos}s');
+ startTime = serverPos;
+ } else {
+ debugPrint('[Player] Local position is newer: local=${startTime}s ($localTimestamp) vs server=${serverPos}s ($serverTimestamp) — keeping local');
+ }
+ }
+ } else {
+ debugPrint('[Player] startPlaybackSession returned null');
+ }
+ } catch (e) {
+ debugPrint('[Player] Could not start server session: $e');
+ }
+ } else {
+ debugPrint('[Player] Skipping server session — manual offline or no API');
+ }
+
+ // If no session, fall back to offline mode
+ if (_playbackSessionId == null) {
+ _isOfflineMode = true;
+ debugPrint('[Player] No server session — true offline mode');
+ }
+
+ final localPaths = _downloadService.getLocalPaths(itemId);
+ if (localPaths == null || localPaths.isEmpty) {
+ debugPrint('[Player] No local files found');
+ _clearState();
+ return false;
+ }
+
+ // Get cached session data for track durations
+ final cachedJson = _downloadService.getCachedSessionData(itemId);
+ List<dynamic>? audioTracks;
+ if (cachedJson != null) {
+ try {
+ final session = jsonDecode(cachedJson) as Map<String, dynamic>;
+ audioTracks = session['audioTracks'] as List<dynamic>?;
+ } catch (_) {}
+ }
+
+ try {
+ // Build multi-file track offsets for absolute position tracking
+ if (audioTracks != null) {
+ _buildTrackOffsets(audioTracks);
+ } else {
+ _trackStartOffsets = [0.0]; // single file fallback
+ }
+ _currentTrackIndex = 0;
+
+ AudioSource source;
+ if (localPaths.length == 1) {
+ source = AudioSource.file(localPaths.first);
+ } else {
+ final sources = localPaths
+ .map((p) => AudioSource.file(p) as AudioSource)
+ .toList();
+ source = ConcatenatingAudioSource(children: sources);
+ }
+
+ await _player!.setAudioSource(source);
+
+ // If the saved position is at (or past) the end, restart from the beginning
+ if (totalDuration > 0 && startTime >= totalDuration - 1.0) startTime = 0;
+ if (startTime > 0) {
+ await _seekAbsolute(startTime);
+ }
+
+ _subscribeTrackIndex();
+ _pushMediaItem(itemId, title, author, coverUrl, totalDuration);
+ final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
+ final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
+ await _player!.setSpeed(speed);
+ debugPrint('[Player] Starting local playback at ${speed}x');
+ _player!.play();
+ notifyListeners();
+ _setupSync();
+ // Fresh session — reset auto sleep dismiss and check
+ final sleepTimer = SleepTimerService();
+ sleepTimer.resetDismiss();
+ sleepTimer.checkAutoSleep();
+ return true;
+ } catch (e, stack) {
+ debugPrint('[Player] Local play error: $e\n$stack');
+ _clearState();
+ return false;
+ }
+ }
+
+ Future<bool> _playFromServer(
+ ApiService api,
+ String itemId,
+ String title,
+ String author,
+ String? coverUrl,
+ double totalDuration,
+ List<dynamic> chapters,
+ double startTime,
+ ) async {
+ debugPrint('[Player] Streaming from server: $title');
+ _isOfflineMode = false;
+
+ // Use episode endpoint if this is a podcast episode
+ final sessionData = _currentEpisodeId != null
+ ? await api.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)
+ : await api.startPlaybackSession(itemId);
+ if (sessionData == null) {
+ debugPrint('[Player] Failed to start playback session');
+ _clearState();
+ return false;
+ }
+
+ _playbackSessionId = sessionData['id'] as String?;
+ final audioTracks = sessionData['audioTracks'] as List<dynamic>?;
+ if (audioTracks == null || audioTracks.isEmpty) {
+ _clearState();
+ return false;
+ }
+
+ // Update totalDuration from session if it was unknown (e.g. podcast episodes
+ // where the embedded recentEpisode didn't include a duration field)
+ if (totalDuration <= 0) {
+ final sessionDur = (sessionData['duration'] as num?)?.toDouble() ?? 0;
+ if (sessionDur > 0) {
+ totalDuration = sessionDur;
+ _totalDuration = sessionDur;
+ debugPrint('[Player] Updated totalDuration from session: ${sessionDur}s');
+ }
+ }
+
+ // Compare server position vs local position — last-write-wins
+ final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
+ if (serverPos > 0) {
+ // Use compound key for podcast episodes to match how progress is saved
+ final progressKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : itemId;
+ final localData = await _progressSync.getLocal(progressKey);
+ final localTimestamp = (localData?['timestamp'] as num?)?.toInt() ?? 0;
+ final serverTimestamp = (sessionData['updatedAt'] as num?)?.toInt() ?? 0;
+
+ if (serverTimestamp > localTimestamp && (serverPos - startTime).abs() > 1.0) {
+ debugPrint('[Player] Server position is newer: server=${serverPos}s ($serverTimestamp) vs local=${startTime}s ($localTimestamp) — using server');
+ startTime = serverPos;
+ } else if (startTime == 0) {
+ debugPrint('[Player] No local position, using server: ${serverPos}s');
+ startTime = serverPos;
+ } else {
+ debugPrint('[Player] Local position is newer: local=${startTime}s ($localTimestamp) vs server=${serverPos}s ($serverTimestamp) — keeping local');
+ }
+ }
+
+ try {
+ // Build multi-file track offsets for absolute position tracking
+ _buildTrackOffsets(audioTracks);
+ _currentTrackIndex = 0;
+
+ final audioHeaders = api.mediaHeaders;
+
+ AudioSource source;
+ if (audioTracks.length == 1) {
+ final track = audioTracks.first as Map<String, dynamic>;
+ final contentUrl = track['contentUrl'] as String? ?? '';
+ final fullUrl = api.buildTrackUrl(contentUrl);
+ source = AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders);
+ } else {
+ final sources = <AudioSource>[];
+ for (final t in audioTracks) {
+ final track = t as Map<String, dynamic>;
+ final contentUrl = track['contentUrl'] as String? ?? '';
+ final fullUrl = api.buildTrackUrl(contentUrl);
+ sources.add(AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders));
+ }
+ source = ConcatenatingAudioSource(children: sources);
+ }
+
+ await _player!.setAudioSource(source);
+
+ // If the saved position is at (or past) the end, restart from the beginning
+ if (totalDuration > 0 && startTime >= totalDuration - 1.0) startTime = 0;
+ if (startTime > 0) {
+ await _seekAbsolute(startTime);
+ }
+
+ _subscribeTrackIndex();
+ _pushMediaItem(itemId, title, author, coverUrl, totalDuration);
+ final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
+ final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
+ await _player!.setSpeed(speed);
+ debugPrint('[Player] Starting stream playback at ${speed}x');
+ _player!.play();
+ notifyListeners();
+ _setupSync();
+ // Fresh session — reset auto sleep dismiss and check
+ final sleepTimer = SleepTimerService();
+ sleepTimer.resetDismiss();
+ sleepTimer.checkAutoSleep();
+ return true;
+ } catch (e, stack) {
+ debugPrint('[Player] Stream error: $e\n$stack');
+ _clearState();
+ return false;
+ }
+ }
+
+ /// Content provider authority — must match CoverContentProvider and AndroidManifest.
+ static const _coverAuthority = 'com.barnabas.absorb.covers';
+
+ void _pushMediaItem(String itemId, String title, String author,
+ String? coverUrl, double totalDuration, {String? chapter}) {
+ // When offline, use local content:// URI so the Now Playing cover still shows.
+ // When online, pass the HTTP URL through for better palette extraction.
+ String? effectiveCoverUrl = coverUrl;
+ if (_isOfflineMode && DownloadService().isDownloaded(itemId)) {
+ effectiveCoverUrl = 'content://$_coverAuthority/cover/$itemId';
+ }
+ _updateNotificationMediaItem(itemId, title, author, effectiveCoverUrl, totalDuration, chapter: chapter);
+ }
+
+ void _updateNotificationMediaItem(String itemId, String title, String author,
+ String? coverUrl, double totalDuration, {String? chapter}) {
+ final displayArtist = chapter != null && chapter.isNotEmpty
+ ? '$author · $chapter'
+ : author;
+ _handler!.mediaItem.add(MediaItem(
+ id: itemId,
+ title: title,
+ artist: displayArtist,
+ album: title,
+ duration: Duration(seconds: totalDuration.round()),
+ artUri: coverUrl != null ? Uri.tryParse(coverUrl) : null,
+ ));
+ }
+
+ void _clearState() {
+ _currentItemId = null;
+ _currentEpisodeId = null;
+ _currentEpisodeTitle = null;
+ _currentTitle = null;
+ _currentAuthor = null;
+ _currentCoverUrl = null;
+ _playbackSessionId = null;
+ _isOfflineMode = false;
+ _trackStartOffsets = [];
+ _currentTrackIndex = 0;
+ _lastNotifiedChapterIndex = -1;
+ _lastSeekTargetSeconds = null;
+ _lastSeekTime = null;
+ _indexSub?.cancel();
+ _indexSub = null;
+ _syncSub?.cancel();
+ _syncSub = null;
+ _eqSessionSub?.cancel();
+ _eqSessionSub = null;
+ notifyListeners();
+ }
+
+ int _lastSyncSecond = -1;
+
+ StreamSubscription? _eqSessionSub;
+
+ void _attachEqualizer() {
+ _eqSessionSub?.cancel();
+ _eqSessionSub = null;
+ if (_player == null) return;
+
+ // Try immediately — works if audio source is already set
+ final sessionId = _player!.androidAudioSessionId;
+ if (sessionId != null && sessionId > 0) {
+ EqualizerService().attachToSession(sessionId);
+ return;
+ }
+
+ // Not available yet — poll briefly after playback starts
+ // (safer than androidAudioSessionIdStream which may not exist in all versions)
+ Future.delayed(const Duration(milliseconds: 500), () {
+ if (_player == null) return;
+ final id = _player!.androidAudioSessionId;
+ if (id != null && id > 0) {
+ debugPrint('[Player] Got audio session ID (delayed): $id');
+ EqualizerService().attachToSession(id);
+ } else {
+ // Try once more after another second
+ Future.delayed(const Duration(seconds: 1), () {
+ if (_player == null) return;
+ final id2 = _player!.androidAudioSessionId;
+ if (id2 != null && id2 > 0) {
+ debugPrint('[Player] Got audio session ID (retry): $id2');
+ EqualizerService().attachToSession(id2);
+ }
+ });
+ }
+ });
+ }
+
+ void _setupSync() {
+ _syncSub?.cancel();
+ _lastSyncSecond = -1;
+
+ // Attach equalizer to current audio session
+ _attachEqualizer();
+
+ _syncSub = _player?.positionStream.listen((trackRelativePos) async {
+ // Convert track-relative position to absolute book position
+ final absolutePos = position; // uses the getter which adds track offset
+ final sec = absolutePos.inSeconds;
+ if (sec <= 0) return;
+
+ // ─── Chapter change detection ──────────────────────────
+ // Update notification subtitle when the chapter changes
+ if (_chapters.isNotEmpty && _currentItemId != null) {
+ final posSeconds = absolutePos.inMilliseconds / 1000.0;
+ int chapterIdx = -1;
+ String? chapterTitle;
+ for (int i = 0; i < _chapters.length; i++) {
+ final ch = _chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ if (posSeconds >= start && posSeconds < end) {
+ chapterIdx = i;
+ chapterTitle = ch['title'] as String?;
+ break;
+ }
+ }
+ if (chapterIdx >= 0 && chapterIdx != _lastNotifiedChapterIndex) {
+ _lastNotifiedChapterIndex = chapterIdx;
+ _pushMediaItem(
+ _currentItemId!, _currentTitle ?? '', _currentAuthor ?? '',
+ _currentCoverUrl, _totalDuration,
+ chapter: chapterTitle,
+ );
+ }
+ }
+
+ // ─── Completion detection ─────────────────────────────
+ // Check if we've reached the end of the book
+ final posSeconds = absolutePos.inMilliseconds / 1000.0;
+ if (_totalDuration > 0 && posSeconds >= _totalDuration - 1.0) {
+ _onPlaybackComplete();
+ return;
+ }
+
+ // Save locally every 5 seconds (always works, even offline)
+ if (sec % 5 == 0 && sec != _lastSyncSecond && _currentItemId != null) {
+ _lastSyncSecond = sec;
+ _saveProgressLocal(absolutePos);
+
+ // Also sync to server every 15 seconds (unless manual offline)
+ if (sec % 15 == 0) {
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+
+ if (manualOffline) {
+ // Manual offline — local save only, no server sync
+ } else if (!_isOfflineMode && _playbackSessionId != null) {
+ // Streaming/local with session: sync via session
+ _syncToServer(absolutePos);
+ } else if (!_isOfflineMode && _api != null && _currentItemId != null) {
+ // No session but online — sync via progress update endpoint
+ debugPrint('[Player] No-session sync — sending to server at ${absolutePos.inSeconds}s');
+ try {
+ final syncKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ final ok = await _progressSync.syncToServer(
+ api: _api!, itemId: syncKey);
+ if (ok) {
+ debugPrint('[Player] No-session sync succeeded');
+ } else {
+ debugPrint('[Player] No-session sync returned false');
+ }
+ } catch (e) {
+ debugPrint('[Player] No-session sync error: $e');
+ }
+ }
+ }
+ }
+ });
+ }
+
+ bool _isCompletingBook = false;
+
+ Future<void> _onPlaybackComplete() async {
+ if (_isCompletingBook) return; // prevent re-entry
+ _isCompletingBook = true;
+
+ debugPrint('[Player] Book complete: $_currentTitle');
+ _logEvent(PlaybackEventType.pause, detail: 'Book finished');
+
+ // Pause immediately so audio doesn't keep running
+ await _player?.pause();
+
+ // Mark as finished on the server
+ final itemId = _currentItemId;
+ final episodeId = _currentEpisodeId;
+ if (itemId != null && _api != null) {
+ try {
+ if (episodeId != null) {
+ await _api!.updateEpisodeProgress(
+ itemId, episodeId,
+ currentTime: _totalDuration,
+ duration: _totalDuration,
+ isFinished: true,
+ );
+ } else {
+ await _api!.markFinished(itemId, _totalDuration);
+ }
+ debugPrint('[Player] Marked as finished on server');
+ } catch (e) {
+ debugPrint('[Player] Failed to mark finished: $e');
+ }
+ }
+
+ // Also save locally as finished (use compound key for episodes)
+ if (itemId != null) {
+ final progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;
+ await _progressSync.saveLocal(
+ itemId: progressKey,
+ currentTime: _totalDuration,
+ duration: _totalDuration,
+ speed: speed,
+ );
+ }
+
+ // Close the playback session
+ if (_playbackSessionId != null && _api != null) {
+ try {
+ await _api!.closePlaybackSession(_playbackSessionId!);
+ } catch (_) {}
+ }
+
+ // Notify LibraryProvider before clearing state so it can update isFinished locally.
+ // Episodes don't mark the whole show as finished.
+ if (itemId != null && episodeId == null) {
+ _onBookFinishedCallback?.call(itemId);
+ }
+
+ // Stop and clear state
+ await _player?.stop();
+ _clearState();
+ _chapters = [];
+ _isCompletingBook = false;
+ notifyListeners();
+ }
+
+ Future<void> _saveProgressLocal(Duration pos) async {
+ if (_currentItemId == null) return;
+ final ct = pos.inMilliseconds / 1000.0;
+ // Use compound key for podcast episodes
+ final progressKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ await _progressSync.saveLocal(
+ itemId: progressKey,
+ currentTime: ct,
+ duration: _totalDuration,
+ speed: speed,
+ );
+ // _logEvent(PlaybackEventType.syncLocal); // too noisy for history
+ }
+
+ Future<void> _syncToServer(Duration pos) async {
+ if (_api == null || _playbackSessionId == null) return;
+ final ct = pos.inMilliseconds / 1000.0;
+ try {
+ await _api!.syncPlaybackSession(
+ _playbackSessionId!,
+ currentTime: ct,
+ duration: _totalDuration,
+ );
+ // _logEvent(PlaybackEventType.syncServer); // too noisy for history
+ } catch (_) {}
+ }
+
+ DateTime? _lastPauseTime;
+ bool _wasPlayingBeforeInterrupt = false;
+
+ /// Auto-rewind calculation using linear scaling.
+ /// Scales linearly from minRewind at activationDelay to maxRewind at 1 hour.
+ /// activationDelay = minimum pause before rewind kicks in (0 = always).
+ static double calculateAutoRewind(
+ Duration pauseDuration, double minRewind, double maxRewind,
+ {double activationDelay = 0}) {
+ final pauseSeconds = pauseDuration.inSeconds.toDouble();
+
+ // Don't rewind if pause is shorter than activation delay
+ if (pauseSeconds < activationDelay) return 0;
+
+ // Linear from min to max over 1 hour of pause time
+ const maxPause = 3600.0; // 1 hour = full rewind
+ final effectivePause = (pauseSeconds - activationDelay).clamp(0.0, maxPause);
+ final t = effectivePause / maxPause;
+ final rewind = minRewind + (maxRewind - minRewind) * t;
+ return rewind.clamp(minRewind, maxRewind);
+ }
+
+ Future<void> play() async {
+ debugPrint('[Service] play() called — lastPause=${_lastPauseTime != null}');
+ // Auto-rewind on resume if enabled
+ if (_lastPauseTime != null && _player != null) {
+ final settings = await AutoRewindSettings.load();
+ if (settings.enabled) {
+ final pauseDuration = DateTime.now().difference(_lastPauseTime!);
+ final rewindSeconds = calculateAutoRewind(
+ pauseDuration, settings.minRewind, settings.maxRewind,
+ activationDelay: settings.activationDelay);
+ if (rewindSeconds > 0.5) {
+ final currentAbsolutePos = position.inMilliseconds / 1000.0;
+ var newPosSeconds = currentAbsolutePos - rewindSeconds;
+ if (newPosSeconds < 0) newPosSeconds = 0;
+ await _seekAbsolute(newPosSeconds);
+ _logEvent(PlaybackEventType.autoRewind,
+ detail: '${rewindSeconds.toStringAsFixed(1)}s rewind');
+ debugPrint(
+ '[Player] Auto-rewind ${rewindSeconds.toStringAsFixed(1)}s '
+ '(paused ${pauseDuration.inSeconds}s)');
+ }
+ }
+ }
+ _lastPauseTime = null;
+ _player?.play();
+ _logEvent(PlaybackEventType.play);
+ // Check auto sleep on every resume — catches window entry between pauses
+ SleepTimerService().checkAutoSleep();
+ notifyListeners();
+ }
+
+ Future<void> pause() async {
+ debugPrint('[Service] pause() called');
+ _lastPauseTime = DateTime.now();
+ await _player?.pause();
+ _logEvent(PlaybackEventType.pause);
+ notifyListeners();
+ _saveProgressLocal(position);
+
+ // Check manual offline before syncing
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ if (manualOffline) return;
+
+ if (!_isOfflineMode && _playbackSessionId != null) {
+ _syncToServer(position);
+ } else if (!_isOfflineMode && _currentItemId != null && _api != null) {
+ final syncKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ _progressSync.syncToServer(api: _api!, itemId: syncKey);
+ }
+ }
+
+ Future<void> togglePlayPause() async {
+ debugPrint('[Service] togglePlayPause() — isPlaying=$isPlaying');
+ if (isPlaying) {
+ await pause();
+ } else {
+ await play();
+ }
+ }
+
+ Future<void> seekTo(Duration pos) async {
+ await _seekAbsolute(pos.inMilliseconds / 1000.0);
+ _logEvent(PlaybackEventType.seek,
+ detail: 'to ${_formatPos(pos)}');
+ notifyListeners();
+ }
+
+ Future<void> skipForward([int seconds = 30]) async {
+ if (_player == null) return;
+ debugPrint('[Service] skipForward(${seconds}s) — playing=${_player!.playing}');
+ final newPos = position + Duration(seconds: seconds);
+ await _seekAbsolute(newPos.inMilliseconds / 1000.0);
+ _logEvent(PlaybackEventType.skipForward, detail: '+${seconds}s');
+ debugPrint('[Service] skipForward done — playing=${_player!.playing}');
+ }
+
+ Future<void> skipBackward([int seconds = 10]) async {
+ if (_player == null) return;
+ debugPrint('[Service] skipBackward(${seconds}s) — playing=${_player!.playing}');
+ var n = position - Duration(seconds: seconds);
+ if (n < Duration.zero) n = Duration.zero;
+ await _seekAbsolute(n.inMilliseconds / 1000.0);
+ _logEvent(PlaybackEventType.skipBackward, detail: '-${seconds}s');
+ debugPrint('[Service] skipBackward done — playing=${_player!.playing}');
+ }
+
+ Future<void> skipToNextChapter() async {
+ if (_player == null || _chapters.isEmpty) return;
+ final posS = position.inMilliseconds / 1000.0;
+ for (int i = 0; i < _chapters.length; i++) {
+ final start = (_chapters[i]['start'] as num?)?.toDouble() ?? 0;
+ if (start > posS + 1.0) {
+ debugPrint('[Service] skipToNextChapter → chapter $i at ${start}s');
+ await _seekAbsolute(start);
+ _logEvent(PlaybackEventType.seek, detail: 'next chapter');
+ notifyListeners();
+ return;
+ }
+ }
+ }
+
+ Future<void> skipToPreviousChapter() async {
+ if (_player == null || _chapters.isEmpty) return;
+ final posS = position.inMilliseconds / 1000.0;
+ // If more than 3s into current chapter, go to start of current chapter
+ // Otherwise go to previous chapter
+ for (int i = _chapters.length - 1; i >= 0; i--) {
+ final start = (_chapters[i]['start'] as num?)?.toDouble() ?? 0;
+ if (start < posS - 3.0) {
+ debugPrint('[Service] skipToPreviousChapter → chapter $i at ${start}s');
+ await _seekAbsolute(start);
+ _logEvent(PlaybackEventType.seek, detail: 'prev chapter');
+ notifyListeners();
+ return;
+ }
+ }
+ // If at the very start, seek to 0
+ await _seekAbsolute(0);
+ notifyListeners();
+ }
+
+ Future<void> setSpeed(double s) async {
+ if (_player == null) return;
+ debugPrint('[Service] setSpeed(${s}x) — before: ${_player!.speed}x');
+ await _player!.setSpeed(s);
+ debugPrint('[Service] setSpeed done — after: ${_player!.speed}x');
+ _logEvent(PlaybackEventType.speedChange, detail: '${s.toStringAsFixed(2)}x');
+ if (_currentItemId != null) {
+ PlayerSettings.setBookSpeed(_currentItemId!, s);
+ }
+ notifyListeners();
+ }
+
+ Map<String, dynamic>? get currentChapter {
+ if (_chapters.isEmpty || _player == null) return null;
+ final pos = position.inMilliseconds / 1000.0; // absolute book position
+ for (final ch in _chapters) {
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ if (pos >= start && pos < end) return ch as Map<String, dynamic>;
+ }
+ return null;
+ }
+
+ Future<void> stop() async {
+ // Save final position locally
+ if (_currentItemId != null) {
+ await _saveProgressLocal(position);
+ }
+
+ // Check manual offline before syncing
+ final prefs = await SharedPreferences.getInstance();
+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+
+ if (!manualOffline) {
+ // Try server sync
+ if (_playbackSessionId != null && _api != null) {
+ await _syncToServer(position);
+ try {
+ await _api!.closePlaybackSession(_playbackSessionId!);
+ } catch (_) {}
+ } else if (_currentItemId != null && _api != null) {
+ await _progressSync.syncToServer(api: _api!, itemId: _currentItemId!);
+ }
+ }
+
+ await _player?.stop();
+ _clearState();
+ _chapters = [];
+ // Cancel sleep timer when playback is stopped
+ if (SleepTimerService().isActive) {
+ SleepTimerService().cancel();
+ }
+ }
+
+ /// Stop playback without saving progress — used by reset progress.
+ Future<void> stopWithoutSaving() async {
+ // Close server session without syncing position
+ if (_playbackSessionId != null && _api != null) {
+ try {
+ await _api!.closePlaybackSession(_playbackSessionId!);
+ } catch (_) {}
+ }
+ await _player?.stop();
+ _clearState();
+ _chapters = [];
+ }
+
+ @override
+ void dispose() {
+ _syncSub?.cancel();
+ _indexSub?.cancel();
+ _player?.dispose();
+ super.dispose();
+ }
+}
diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dart
new file mode 100644
index 00000000..df872ce9
--- /dev/null
+++ b/lib/services/bookmark_service.dart
@@ -0,0 +1,175 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+/// A single bookmark in an audiobook.
+class Bookmark {
+ final String id;
+ final double positionSeconds;
+ final DateTime created;
+ String title;
+ String? note;
+
+ Bookmark({
+ required this.id,
+ required this.positionSeconds,
+ required this.created,
+ required this.title,
+ this.note,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'id': id,
+ 'pos': positionSeconds,
+ 'ts': created.millisecondsSinceEpoch,
+ 'title': title,
+ if (note != null && note!.isNotEmpty) 'note': note,
+ };
+
+ factory Bookmark.fromJson(Map<String, dynamic> json) {
+ return Bookmark(
+ id: json['id'] as String,
+ positionSeconds: (json['pos'] as num).toDouble(),
+ created: DateTime.fromMillisecondsSinceEpoch(json['ts'] as int),
+ title: json['title'] as String? ?? 'Bookmark',
+ note: json['note'] as String?,
+ );
+ }
+
+ String get formattedPosition {
+ final h = positionSeconds ~/ 3600;
+ final m = (positionSeconds % 3600) ~/ 60;
+ final s = positionSeconds.toInt() % 60;
+ if (h > 0) {
+ return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ }
+ return '$m:${s.toString().padLeft(2, '0')}';
+ }
+}
+
+/// Stores per-book bookmarks in SharedPreferences.
+class BookmarkService {
+ static final BookmarkService _instance = BookmarkService._();
+ factory BookmarkService() => _instance;
+ BookmarkService._();
+
+ static const int _maxBookmarksPerBook = 100;
+
+ String _key(String itemId) => 'bookmarks_$itemId';
+
+ /// Get all bookmarks for a book, sorted by position.
+ Future<List<Bookmark>> getBookmarks(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ final stored = prefs.getStringList(_key(itemId)) ?? [];
+
+ final bookmarks = <Bookmark>[];
+ for (final json in stored) {
+ try {
+ bookmarks.add(Bookmark.fromJson(jsonDecode(json)));
+ } catch (e) {
+ debugPrint('[Bookmarks] Failed to parse: $e');
+ }
+ }
+
+ bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));
+ return bookmarks;
+ }
+
+ /// Add a bookmark. Returns the new bookmark.
+ Future<Bookmark> addBookmark({
+ required String itemId,
+ required double positionSeconds,
+ required String title,
+ String? note,
+ }) async {
+ final bookmark = Bookmark(
+ id: '${DateTime.now().millisecondsSinceEpoch}',
+ positionSeconds: positionSeconds,
+ created: DateTime.now(),
+ title: title,
+ note: note,
+ );
+
+ final prefs = await SharedPreferences.getInstance();
+ final key = _key(itemId);
+ final existing = prefs.getStringList(key) ?? [];
+
+ existing.add(jsonEncode(bookmark.toJson()));
+
+ // Trim to max
+ if (existing.length > _maxBookmarksPerBook) {
+ existing.removeRange(0, existing.length - _maxBookmarksPerBook);
+ }
+
+ await prefs.setStringList(key, existing);
+ debugPrint('[Bookmarks] Added "${bookmark.title}" at ${bookmark.formattedPosition}');
+ return bookmark;
+ }
+
+ /// Update a bookmark's title and/or note.
+ Future<void> updateBookmark({
+ required String itemId,
+ required String bookmarkId,
+ String? title,
+ String? note,
+ }) async {
+ final prefs = await SharedPreferences.getInstance();
+ final key = _key(itemId);
+ final stored = prefs.getStringList(key) ?? [];
+
+ final updated = <String>[];
+ for (final json in stored) {
+ try {
+ final bm = Bookmark.fromJson(jsonDecode(json));
+ if (bm.id == bookmarkId) {
+ if (title != null) bm.title = title;
+ bm.note = note ?? bm.note;
+ updated.add(jsonEncode(bm.toJson()));
+ } else {
+ updated.add(json);
+ }
+ } catch (_) {
+ updated.add(json);
+ }
+ }
+
+ await prefs.setStringList(key, updated);
+ }
+
+ /// Delete a bookmark.
+ Future<void> deleteBookmark({
+ required String itemId,
+ required String bookmarkId,
+ }) async {
+ final prefs = await SharedPreferences.getInstance();
+ final key = _key(itemId);
+ final stored = prefs.getStringList(key) ?? [];
+
+ final updated = <String>[];
+ for (final json in stored) {
+ try {
+ final bm = Bookmark.fromJson(jsonDecode(json));
+ if (bm.id != bookmarkId) {
+ updated.add(json);
+ }
+ } catch (_) {
+ updated.add(json);
+ }
+ }
+
+ await prefs.setStringList(key, updated);
+ debugPrint('[Bookmarks] Deleted bookmark $bookmarkId');
+ }
+
+ /// Get bookmark count for a book.
+ Future<int> getCount(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ return (prefs.getStringList(_key(itemId)) ?? []).length;
+ }
+
+ /// Clear all bookmarks for a book.
+ Future<void> clearBookmarks(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove(_key(itemId));
+ }
+}
diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dart
new file mode 100644
index 00000000..0cc21ca8
--- /dev/null
+++ b/lib/services/chromecast_service.dart
@@ -0,0 +1,504 @@
+import 'dart:async';
+import 'package:flutter/material.dart';
+import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';
+import 'api_service.dart';
+import 'audio_player_service.dart';
+import 'progress_sync_service.dart';
+
+enum CastConnectionState { disconnected, connecting, connected }
+enum CastPlaybackState { idle, loading, playing, paused, buffering }
+
+class ChromecastService extends ChangeNotifier {
+ static final ChromecastService _instance = ChromecastService._();
+ factory ChromecastService() => _instance;
+ ChromecastService._();
+
+ CastConnectionState _connectionState = CastConnectionState.disconnected;
+ CastPlaybackState _playbackState = CastPlaybackState.idle;
+
+ CastConnectionState get connectionState => _connectionState;
+ CastPlaybackState get playbackState => _playbackState;
+ bool get isConnected => _connectionState == CastConnectionState.connected;
+ bool get isCasting => isConnected && _playbackState != CastPlaybackState.idle;
+ bool get isPlaying => _playbackState == CastPlaybackState.playing;
+
+ String? _castingItemId, _castingTitle, _castingAuthor, _castingCoverUrl;
+ double _castingDuration = 0;
+ List<dynamic> _castingChapters = [];
+ ApiService? _api;
+ Duration _castPosition = Duration.zero;
+ String? _connectedDeviceName;
+
+ String? get castingItemId => _castingItemId;
+ String? get castingTitle => _castingTitle;
+ String? get castingAuthor => _castingAuthor;
+ String? get castingCoverUrl => _castingCoverUrl;
+ double get castingDuration => _castingDuration;
+ List<dynamic> get castingChapters => _castingChapters;
+ Duration get castPosition => _castPosition;
+ String? get connectedDeviceName => _connectedDeviceName;
+
+ StreamSubscription? _sessionSub, _mediaStatusSub, _positionSub;
+ Timer? _syncTimer;
+ final _progressSync = ProgressSyncService();
+ bool _initialized = false;
+
+ // ── Init ──
+
+ Future<void> init() async {
+ if (_initialized) return;
+ _initialized = true;
+ debugPrint('[Cast] >>> init() called');
+ try {
+ const appId = GoogleCastDiscoveryCriteria.kDefaultApplicationId;
+ debugPrint('[Cast] Using appId: $appId');
+ final options = GoogleCastOptionsAndroid(appId: appId);
+ GoogleCastContext.instance.setSharedInstanceWithOptions(options);
+ debugPrint('[Cast] Context initialized OK');
+ } catch (e, st) {
+ debugPrint('[Cast] Init error: $e\n$st');
+ _initialized = false;
+ return;
+ }
+ _listenToSessionChanges();
+
+ try {
+ await GoogleCastDiscoveryManager.instance.startDiscovery();
+ debugPrint('[Cast] Discovery started');
+ } catch (e) {
+ debugPrint('[Cast] Discovery start error: $e');
+ }
+ }
+
+ // ── Session ──
+
+ void _listenToSessionChanges() {
+ debugPrint('[Cast] >>> _listenToSessionChanges() subscribing');
+ _sessionSub?.cancel();
+ _sessionSub = GoogleCastSessionManager.instance.currentSessionStream.listen(
+ (session) {
+ final state = GoogleCastSessionManager.instance.connectionState;
+ debugPrint('[Cast] SESSION EVENT — connectionState: $state, session: ${session?.device?.friendlyName ?? "null"}');
+ if (state == GoogleCastConnectState.connected) {
+ _connectionState = CastConnectionState.connected;
+ _connectedDeviceName = session?.device?.friendlyName;
+ debugPrint('[Cast] ✓ CONNECTED to: $_connectedDeviceName');
+ _listenToMediaStatus();
+ _listenToPosition();
+ _updateVolumeFromSession();
+ } else if (state == GoogleCastConnectState.disconnected) {
+ debugPrint('[Cast] ✗ DISCONNECTED');
+ _onDisconnected();
+ } else {
+ debugPrint('[Cast] ~ CONNECTING...');
+ _connectionState = CastConnectionState.connecting;
+ }
+ notifyListeners();
+ },
+ onError: (e) => debugPrint('[Cast] Session stream ERROR: $e'),
+ onDone: () => debugPrint('[Cast] Session stream DONE (closed)'),
+ );
+ debugPrint('[Cast] Session stream subscription active');
+ }
+
+ void _onDisconnected() {
+ if (_castingItemId != null && _castPosition > Duration.zero) _saveProgressLocal();
+ _connectionState = CastConnectionState.disconnected;
+ _playbackState = CastPlaybackState.idle;
+ _connectedDeviceName = null;
+ _castingItemId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
+ _castingDuration = 0;
+ _castingChapters = [];
+ _castPosition = Duration.zero;
+ _mediaStatusSub?.cancel();
+ _positionSub?.cancel();
+ _syncTimer?.cancel();
+ notifyListeners();
+ }
+
+ void _listenToMediaStatus() {
+ _mediaStatusSub?.cancel();
+ _mediaStatusSub = GoogleCastRemoteMediaClient.instance.mediaStatusStream.listen((status) {
+ if (status == null) {
+ _playbackState = CastPlaybackState.idle;
+ } else {
+ debugPrint('[Cast] Media status: ${status.playerState}');
+ switch (status.playerState) {
+ case CastMediaPlayerState.playing: _playbackState = CastPlaybackState.playing; break;
+ case CastMediaPlayerState.paused: _playbackState = CastPlaybackState.paused; break;
+ case CastMediaPlayerState.buffering: _playbackState = CastPlaybackState.buffering; break;
+ case CastMediaPlayerState.loading: _playbackState = CastPlaybackState.loading; break;
+ default: _playbackState = CastPlaybackState.idle;
+ }
+ }
+ notifyListeners();
+ });
+ }
+
+ void _listenToPosition() {
+ _positionSub?.cancel();
+ _positionSub = GoogleCastRemoteMediaClient.instance.playerPositionStream?.listen((pos) {
+ if (pos != null) _castPosition = pos;
+ });
+ _syncTimer?.cancel();
+ _syncTimer = Timer.periodic(const Duration(seconds: 15), (_) {
+ if (isCasting && _castingItemId != null) {
+ _saveProgressLocal();
+ _syncProgressToServer();
+ }
+ });
+ }
+
+ Stream<Duration>? get castPositionStream =>
+ GoogleCastRemoteMediaClient.instance.playerPositionStream;
+
+ // ── Discovery / Connection ──
+
+ Stream<List<GoogleCastDevice>> get devicesStream =>
+ GoogleCastDiscoveryManager.instance.devicesStream;
+
+ Future<void> connectToDevice(GoogleCastDevice device) async {
+ debugPrint('[Cast] >>> connectToDevice() — ${device.friendlyName}');
+ debugPrint('[Cast] Current connectionState before connect: $_connectionState');
+ _connectionState = CastConnectionState.connecting;
+ notifyListeners();
+ try {
+ debugPrint('[Cast] Calling startSessionWithDevice...');
+ await GoogleCastSessionManager.instance.startSessionWithDevice(device);
+ debugPrint('[Cast] startSessionWithDevice returned (awaited)');
+ } catch (e, st) {
+ debugPrint('[Cast] Connect error: $e\n$st');
+ _connectionState = CastConnectionState.disconnected;
+ notifyListeners();
+ }
+ }
+
+ Future<void> disconnect() async {
+ if (_castingItemId != null && _castPosition > Duration.zero) {
+ await _saveProgressLocal();
+ await _syncProgressToServer();
+ }
+ try {
+ await GoogleCastSessionManager.instance.endSessionAndStopCasting();
+ } catch (e) { debugPrint('[Cast] Disconnect error: $e'); }
+ }
+
+ // ── Media Loading ──
+
+ Future<bool> castItem({
+ required ApiService api, required String itemId,
+ required String title, required String author,
+ required String? coverUrl, required double totalDuration,
+ required List<dynamic> chapters, double startTime = 0,
+ }) async {
+ debugPrint('[Cast] >>> castItem() — "$title" (id: $itemId)');
+ debugPrint('[Cast] isConnected=$isConnected, connectionState=$_connectionState');
+ if (!isConnected) {
+ debugPrint('[Cast] NOT CONNECTED — aborting castItem');
+ return false;
+ }
+
+ final localPlayer = AudioPlayerService();
+ if (localPlayer.hasBook) {
+ debugPrint('[Cast] Stopping local player');
+ await localPlayer.stop();
+ }
+
+ _api = api;
+ _castingItemId = itemId;
+ _castingTitle = title;
+ _castingAuthor = author;
+ _castingCoverUrl = coverUrl;
+ _castingDuration = totalDuration;
+ _castingChapters = chapters;
+ _playbackState = CastPlaybackState.loading;
+ notifyListeners();
+
+ final localPos = await _progressSync.getSavedPosition(itemId);
+ debugPrint('[Cast] Local saved position: $localPos');
+ if (localPos > 0 && startTime == 0) startTime = localPos;
+
+ try {
+ debugPrint('[Cast] Starting playback session with server...');
+ final sessionData = await api.startPlaybackSession(itemId);
+ if (sessionData == null) {
+ debugPrint('[Cast] Server returned null session — aborting');
+ _playbackState = CastPlaybackState.idle; notifyListeners(); return false;
+ }
+ debugPrint('[Cast] Got session data, keys: ${sessionData.keys.toList()}');
+
+ final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
+ debugPrint('[Cast] Server position: $serverPos');
+ if (serverPos > 0) {
+ final localData = await _progressSync.getLocal(itemId);
+ final lt = (localData?['timestamp'] as num?)?.toInt() ?? 0;
+ final st = (sessionData['updatedAt'] as num?)?.toInt() ?? 0;
+ if (st > lt && (serverPos - startTime).abs() > 1.0) startTime = serverPos;
+ else if (startTime == 0 && serverPos > 0) startTime = serverPos;
+ }
+
+ final audioTracks = sessionData['audioTracks'] as List<dynamic>?;
+ debugPrint('[Cast] Audio tracks count: ${audioTracks?.length ?? 0}');
+ if (audioTracks == null || audioTracks.isEmpty) {
+ debugPrint('[Cast] No audio tracks — aborting');
+ _playbackState = CastPlaybackState.idle; notifyListeners(); return false;
+ }
+
+ final sid = sessionData['id'] as String?;
+ if (sid != null) try { await api.closePlaybackSession(sid); } catch (_) {}
+
+ debugPrint('[Cast] Starting from position: ${startTime}s');
+ if (audioTracks.length == 1) {
+ debugPrint('[Cast] Single track mode');
+ return _loadSingleTrack(api, audioTracks.first, title, author, coverUrl, totalDuration, startTime);
+ } else {
+ debugPrint('[Cast] Multi-track queue mode (${audioTracks.length} tracks)');
+ return _loadMultiTrackQueue(api, audioTracks, title, author, coverUrl, totalDuration, chapters, startTime);
+ }
+ } catch (e, st) {
+ debugPrint('[Cast] castItem error: $e\n$st');
+ _playbackState = CastPlaybackState.idle; notifyListeners(); return false;
+ }
+ }
+
+ Future<bool> _loadSingleTrack(ApiService api, dynamic track, String title,
+ String author, String? coverUrl, double totalDuration, double startTime) async {
+ final m = track as Map<String, dynamic>;
+ final fullUrl = api.buildTrackUrl(m['contentUrl'] as String? ?? '');
+ debugPrint('[Cast] Loading single track URL: $fullUrl');
+ final subtitle = _buildSubtitle(author, startTime);
+ try {
+ await GoogleCastRemoteMediaClient.instance.loadMedia(
+ GoogleCastMediaInformation(
+ contentId: fullUrl,
+ streamType: CastMediaStreamType.buffered,
+ contentUrl: Uri.parse(fullUrl),
+ contentType: _contentType(fullUrl),
+ metadata: GoogleCastGenericMediaMetadata(
+ title: title,
+ subtitle: subtitle,
+ images: coverUrl != null ? [GoogleCastImage(url: Uri.parse(coverUrl), height: 400, width: 400)] : null,
+ ),
+ duration: Duration(seconds: totalDuration.round()),
+ ),
+ autoPlay: true,
+ playPosition: Duration(milliseconds: (startTime * 1000).round()),
+ );
+ debugPrint('[Cast] ✓ loadMedia completed');
+ _castPosition = Duration(milliseconds: (startTime * 1000).round());
+ return true;
+ } catch (e, st) {
+ debugPrint('[Cast] loadMedia error: $e\n$st');
+ _playbackState = CastPlaybackState.idle; notifyListeners(); return false;
+ }
+ }
+
+ Future<bool> _loadMultiTrackQueue(ApiService api, List<dynamic> tracks, String title,
+ String author, String? coverUrl, double totalDuration, List<dynamic> chapters, double startTime) async {
+ final offsets = <double>[0.0];
+ for (final t in tracks) {
+ final dur = ((t as Map<String, dynamic>)['duration'] as num?)?.toDouble() ?? 0.0;
+ offsets.add(offsets.last + dur);
+ }
+
+ double localStart = startTime;
+ for (int i = 0; i < offsets.length - 1; i++) {
+ if (startTime < offsets[i + 1] || i == offsets.length - 2) {
+ localStart = startTime - offsets[i];
+ break;
+ }
+ }
+
+ debugPrint('[Cast] Multi-track: startTime=$startTime, localStart=$localStart');
+ try {
+ final items = <GoogleCastQueueItem>[];
+ for (int i = 0; i < tracks.length; i++) {
+ final m = tracks[i] as Map<String, dynamic>;
+ final fullUrl = api.buildTrackUrl(m['contentUrl'] as String? ?? '');
+ debugPrint('[Cast] Track $i URL: $fullUrl');
+ items.add(GoogleCastQueueItem(
+ mediaInformation: GoogleCastMediaInformation(
+ contentId: fullUrl,
+ streamType: CastMediaStreamType.buffered,
+ contentUrl: Uri.parse(fullUrl),
+ contentType: _contentType(fullUrl),
+ metadata: GoogleCastGenericMediaMetadata(
+ title: title,
+ subtitle: '$author · Track ${i + 1} of ${tracks.length}',
+ images: coverUrl != null ? [GoogleCastImage(url: Uri.parse(coverUrl), height: 400, width: 400)] : null,
+ ),
+ ),
+ ));
+ }
+ debugPrint('[Cast] Calling queueLoadItems with ${items.length} items...');
+ await GoogleCastRemoteMediaClient.instance.queueLoadItems(items);
+ debugPrint('[Cast] ✓ queueLoadItems completed');
+
+ if (localStart > 0.5) {
+ await Future.delayed(const Duration(milliseconds: 500));
+ debugPrint('[Cast] Seeking to $localStart...');
+ await GoogleCastRemoteMediaClient.instance.seek(
+ GoogleCastMediaSeekOption(position: Duration(milliseconds: (localStart * 1000).round())),
+ );
+ debugPrint('[Cast] ✓ Seek completed');
+ }
+ _castPosition = Duration(milliseconds: (startTime * 1000).round());
+ return true;
+ } catch (e, st) {
+ debugPrint('[Cast] Queue error: $e\n$st');
+ _playbackState = CastPlaybackState.idle; notifyListeners(); return false;
+ }
+ }
+
+ String _contentType(String url) {
+ final l = url.toLowerCase();
+ if (l.contains('.m4b') || l.contains('.m4a') || l.contains('.aac')) return 'audio/mp4';
+ if (l.contains('.ogg') || l.contains('.opus')) return 'audio/ogg';
+ if (l.contains('.flac')) return 'audio/flac';
+ return 'audio/mpeg';
+ }
+
+ /// Build a subtitle string with author + current chapter name
+ String _buildSubtitle(String author, double position) {
+ if (_castingChapters.isEmpty) return author;
+ for (final ch in _castingChapters) {
+ final m = ch as Map<String, dynamic>;
+ final s = (m['start'] as num?)?.toDouble() ?? 0;
+ final e = (m['end'] as num?)?.toDouble() ?? 0;
+ if (position >= s && position < e) {
+ final chTitle = m['title'] as String?;
+ if (chTitle != null && chTitle.isNotEmpty) return '$author · $chTitle';
+ break;
+ }
+ }
+ return author;
+ }
+
+ /// Get the current chapter title based on cast position
+ String? get currentChapterTitle {
+ final ch = currentChapter;
+ return ch?['title'] as String?;
+ }
+
+ // ── Volume ──
+
+ double _volume = 1.0;
+ double get volume => _volume;
+
+ void _updateVolumeFromSession() {
+ try {
+ final session = GoogleCastSessionManager.instance.currentSession;
+ if (session != null) {
+ _volume = session.currentDeviceVolume.clamp(0.0, 1.0);
+ }
+ } catch (_) {}
+ }
+
+ Future<void> setVolume(double value) async {
+ _volume = value.clamp(0.0, 1.0);
+ notifyListeners();
+ try {
+ GoogleCastSessionManager.instance.setDeviceVolume(value);
+ } catch (e) {
+ debugPrint('[Cast] setDeviceVolume error: $e');
+ }
+ }
+
+ // ── Controls ──
+
+ Future<void> play() async { if (isConnected) try { await GoogleCastRemoteMediaClient.instance.play(); } catch (_) {} }
+ Future<void> pause() async { if (isConnected) try { await GoogleCastRemoteMediaClient.instance.pause(); _saveProgressLocal(); _syncProgressToServer(); } catch (_) {} }
+ Future<void> togglePlayPause() async { isPlaying ? await pause() : await play(); }
+
+ Future<void> seekTo(Duration position) async {
+ if (!isConnected) return;
+ try {
+ await GoogleCastRemoteMediaClient.instance.seek(GoogleCastMediaSeekOption(position: position));
+ _castPosition = position;
+ notifyListeners();
+ } catch (_) {}
+ }
+
+ Future<void> skipForward([int s = 30]) => seekTo(_castPosition + Duration(seconds: s));
+ Future<void> skipBackward([int s = 10]) async {
+ var p = _castPosition - Duration(seconds: s);
+ if (p < Duration.zero) p = Duration.zero;
+ await seekTo(p);
+ }
+
+ // ── Speed ──
+
+ double _castSpeed = 1.0;
+ double get castSpeed => _castSpeed;
+
+ Future<void> setSpeed(double speed) async {
+ _castSpeed = speed.clamp(0.5, 3.0);
+ if (!isConnected) return;
+ try {
+ await GoogleCastRemoteMediaClient.instance.setPlaybackRate(speed);
+ debugPrint('[Cast] Speed set to ${speed}x');
+ } catch (e) {
+ debugPrint('[Cast] setPlaybackRate error (may not be supported): $e');
+ }
+ notifyListeners();
+ }
+
+ Future<void> stopCasting() async {
+ if (!isConnected) return;
+ await _saveProgressLocal();
+ await _syncProgressToServer();
+ try { await GoogleCastRemoteMediaClient.instance.stop(); } catch (_) {}
+ _playbackState = CastPlaybackState.idle;
+ _castingItemId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
+ _castingDuration = 0; _castingChapters = [];
+ notifyListeners();
+ }
+
+ // ── Sync ──
+
+ Future<void> _saveProgressLocal() async {
+ if (_castingItemId == null) return;
+ final ct = _castPosition.inMilliseconds / 1000.0;
+ if (ct <= 0) return;
+ await _progressSync.saveLocal(itemId: _castingItemId!, currentTime: ct, duration: _castingDuration, speed: 1.0);
+ }
+
+ Future<void> _syncProgressToServer() async {
+ if (_castingItemId == null || _api == null) return;
+ try { await _progressSync.syncToServer(api: _api!, itemId: _castingItemId!); } catch (_) {}
+ }
+
+ // ── Chapters ──
+
+ Map<String, dynamic>? get currentChapter {
+ if (_castingChapters.isEmpty) return null;
+ final p = _castPosition.inMilliseconds / 1000.0;
+ for (final ch in _castingChapters) {
+ final m = ch as Map<String, dynamic>;
+ if (p >= ((m['start'] as num?)?.toDouble() ?? 0) && p < ((m['end'] as num?)?.toDouble() ?? 0)) return m;
+ }
+ return null;
+ }
+
+ Future<void> skipToNextChapter() async {
+ if (_castingChapters.isEmpty) return;
+ final p = _castPosition.inMilliseconds / 1000.0;
+ for (final ch in _castingChapters) {
+ final s = ((ch as Map)['start'] as num?)?.toDouble() ?? 0;
+ if (s > p + 1.0) { await seekTo(Duration(milliseconds: (s * 1000).round())); return; }
+ }
+ }
+
+ Future<void> skipToPreviousChapter() async {
+ if (_castingChapters.isEmpty) return;
+ final p = _castPosition.inMilliseconds / 1000.0;
+ for (int i = _castingChapters.length - 1; i >= 0; i--) {
+ final s = ((_castingChapters[i] as Map)['start'] as num?)?.toDouble() ?? 0;
+ if (s < p - 3.0) { await seekTo(Duration(milliseconds: (s * 1000).round())); return; }
+ }
+ await seekTo(Duration.zero);
+ }
+
+ @override
+ void dispose() { _sessionSub?.cancel(); _mediaStatusSub?.cancel(); _positionSub?.cancel(); _syncTimer?.cancel(); super.dispose(); }
+}
diff --git a/lib/services/download_notification_service.dart b/lib/services/download_notification_service.dart
new file mode 100644
index 00000000..7268b100
--- /dev/null
+++ b/lib/services/download_notification_service.dart
@@ -0,0 +1,249 @@
+import 'dart:io';
+import 'package:flutter/foundation.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+
+/// Manages notifications for audiobook downloads.
+/// Uses an Android **foreground service** for progress so the OS won't kill
+/// the download when the app is backgrounded or the screen is locked.
+/// A separate high-importance channel handles completion/error alerts.
+class DownloadNotificationService {
+ // Singleton
+ static final DownloadNotificationService _instance = DownloadNotificationService._();
+ factory DownloadNotificationService() => _instance;
+ DownloadNotificationService._();
+
+ final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
+ bool _initialized = false;
+ bool _foregroundActive = false;
+
+ // Foreground service / progress channel
+ static const _progressChannelId = 'absorb_downloads';
+ static const _progressChannelName = 'Download Progress';
+ static const _progressChannelDesc = 'Shows progress during audiobook downloads';
+ static const _progressNotifId = 9001;
+
+ // Alert channel for completion / error (heads-up + sound)
+ static const _alertChannelId = 'absorb_download_alerts';
+ static const _alertChannelName = 'Download Alerts';
+ static const _alertChannelDesc = 'Notifications when downloads finish or fail';
+ static const _alertNotifId = 9002;
+
+ Future<void> init() async {
+ if (_initialized) return;
+
+ const androidSettings = AndroidInitializationSettings('drawable/ic_notification');
+ const settings = InitializationSettings(android: androidSettings);
+ await _plugin.initialize(settings);
+
+ // Create notification channels (Android 8+)
+ final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin>();
+ if (androidPlugin != null) {
+ // Progress channel — default importance so the foreground service
+ // notification stays visible in the shade without making noise.
+ await androidPlugin.createNotificationChannel(
+ const AndroidNotificationChannel(
+ _progressChannelId,
+ _progressChannelName,
+ description: _progressChannelDesc,
+ importance: Importance.defaultImportance,
+ showBadge: false,
+ ),
+ );
+
+ // High-importance alert channel for completion / errors
+ await androidPlugin.createNotificationChannel(
+ const AndroidNotificationChannel(
+ _alertChannelId,
+ _alertChannelName,
+ description: _alertChannelDesc,
+ importance: Importance.high,
+ showBadge: true,
+ ),
+ );
+
+ // Request notification permission (Android 13+)
+ await androidPlugin.requestNotificationsPermission();
+ }
+
+ _initialized = true;
+ }
+
+ /// Start the foreground service and show initial progress notification.
+ /// Call once at the start of a download.
+ Future<void> startForeground({
+ required String title,
+ String? author,
+ }) async {
+ if (!_initialized) await init();
+
+ final subtitle = author != null && author.isNotEmpty
+ ? '$author • Starting…'
+ : 'Starting…';
+
+ final androidDetails = AndroidNotificationDetails(
+ _progressChannelId,
+ _progressChannelName,
+ channelDescription: _progressChannelDesc,
+ importance: Importance.defaultImportance,
+ priority: Priority.defaultPriority,
+ showProgress: true,
+ maxProgress: 100,
+ progress: 0,
+ ongoing: true,
+ autoCancel: false,
+ onlyAlertOnce: true,
+ category: AndroidNotificationCategory.progress,
+ icon: 'drawable/ic_notification',
+ );
+
+ // Start as a foreground service — this prevents Android from killing
+ // the process while the download is active.
+ final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin>();
+ if (androidPlugin != null) {
+ try {
+ await androidPlugin.startForegroundService(
+ _progressNotifId,
+ 'Downloading: $title',
+ subtitle,
+ notificationDetails: androidDetails,
+ payload: 'download',
+ );
+ _foregroundActive = true;
+ debugPrint('[DownloadNotif] Foreground service started');
+ } catch (e) {
+ debugPrint('[DownloadNotif] Foreground service failed, falling back: $e');
+ // Fall back to a regular notification
+ await _plugin.show(
+ _progressNotifId,
+ 'Downloading: $title',
+ subtitle,
+ NotificationDetails(android: androidDetails),
+ );
+ _foregroundActive = false;
+ }
+ }
+ }
+
+ /// Show or update the download progress notification.
+ Future<void> showProgress({
+ required String title,
+ required double progress,
+ String? author,
+ }) async {
+ if (!_initialized) await init();
+
+ final percent = (progress * 100).round().clamp(0, 100);
+ final subtitle = author != null && author.isNotEmpty
+ ? '$author • $percent%'
+ : '$percent%';
+
+ final androidDetails = AndroidNotificationDetails(
+ _progressChannelId,
+ _progressChannelName,
+ channelDescription: _progressChannelDesc,
+ importance: Importance.defaultImportance,
+ priority: Priority.defaultPriority,
+ showProgress: true,
+ maxProgress: 100,
+ progress: percent,
+ ongoing: true,
+ autoCancel: false,
+ onlyAlertOnce: true,
+ category: AndroidNotificationCategory.progress,
+ icon: 'drawable/ic_notification',
+ );
+
+ await _plugin.show(
+ _progressNotifId,
+ 'Downloading: $title',
+ subtitle,
+ NotificationDetails(android: androidDetails),
+ );
+ }
+
+ /// Stop the foreground service and clear the progress notification.
+ Future<void> stopForeground() async {
+ if (_foregroundActive) {
+ final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin>();
+ if (androidPlugin != null) {
+ try {
+ await androidPlugin.stopForegroundService();
+ debugPrint('[DownloadNotif] Foreground service stopped');
+ } catch (e) {
+ debugPrint('[DownloadNotif] Stop foreground failed: $e');
+ }
+ }
+ _foregroundActive = false;
+ }
+ await _plugin.cancel(_progressNotifId);
+ }
+
+ /// Show a heads-up completion notification with sound.
+ /// Stops the foreground service and dismisses the progress notification first.
+ Future<void> showComplete({required String title}) async {
+ if (!_initialized) await init();
+
+ // Stop the foreground service + clear progress
+ await stopForeground();
+
+ const androidDetails = AndroidNotificationDetails(
+ _alertChannelId,
+ _alertChannelName,
+ channelDescription: _alertChannelDesc,
+ importance: Importance.high,
+ priority: Priority.high,
+ ongoing: false,
+ autoCancel: true,
+ icon: 'drawable/ic_notification',
+ ticker: 'Download complete',
+ category: AndroidNotificationCategory.status,
+ visibility: NotificationVisibility.public,
+ );
+
+ await _plugin.show(
+ _alertNotifId,
+ 'Download Complete',
+ '$title is ready to listen offline',
+ const NotificationDetails(android: androidDetails),
+ );
+ }
+
+ /// Show a heads-up error notification with sound.
+ /// Stops the foreground service and dismisses the progress notification first.
+ Future<void> showError({required String title, String? message}) async {
+ if (!_initialized) await init();
+
+ // Stop the foreground service + clear progress
+ await stopForeground();
+
+ const androidDetails = AndroidNotificationDetails(
+ _alertChannelId,
+ _alertChannelName,
+ channelDescription: _alertChannelDesc,
+ importance: Importance.high,
+ priority: Priority.high,
+ ongoing: false,
+ autoCancel: true,
+ icon: 'drawable/ic_notification',
+ ticker: 'Download failed',
+ category: AndroidNotificationCategory.status,
+ visibility: NotificationVisibility.public,
+ );
+
+ await _plugin.show(
+ _alertNotifId,
+ 'Download Failed',
+ message ?? title,
+ const NotificationDetails(android: androidDetails),
+ );
+ }
+
+ /// Dismiss all download notifications and stop the foreground service.
+ Future<void> dismiss() async {
+ await stopForeground();
+ await _plugin.cancel(_alertNotifId);
+ }
+}
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
new file mode 100644
index 00000000..03779efb
--- /dev/null
+++ b/lib/services/download_service.dart
@@ -0,0 +1,604 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:connectivity_plus/connectivity_plus.dart';
+import 'package:http/http.dart' as http;
+import 'api_service.dart';
+import 'audio_player_service.dart';
+import 'download_notification_service.dart';
+
+enum DownloadStatus { none, downloading, downloaded, error }
+
+class DownloadInfo {
+ final String itemId;
+ final DownloadStatus status;
+ final double progress;
+ final List<String> localPaths;
+ final String? sessionData;
+ // Metadata for offline display
+ final String? title;
+ final String? author;
+ final String? coverUrl;
+ final String? localCoverPath;
+
+ DownloadInfo({
+ required this.itemId,
+ this.status = DownloadStatus.none,
+ this.progress = 0,
+ this.localPaths = const [],
+ this.sessionData,
+ this.title,
+ this.author,
+ this.coverUrl,
+ this.localCoverPath,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'itemId': itemId,
+ 'status': status.index,
+ 'localPaths': localPaths,
+ 'sessionData': sessionData,
+ 'title': title,
+ 'author': author,
+ 'coverUrl': coverUrl,
+ 'localCoverPath': localCoverPath,
+ };
+
+ factory DownloadInfo.fromJson(Map<String, dynamic> json) {
+ String? title = json['title'] as String?;
+ String? author = json['author'] as String?;
+ String? coverUrl = json['coverUrl'] as String?;
+
+ // Fallback: extract metadata from cached sessionData for old downloads
+ if ((title == null || title.isEmpty) && json['sessionData'] != null) {
+ try {
+ final session = jsonDecode(json['sessionData'] as String) as Map<String, dynamic>;
+ // Try session-level metadata first
+ final sessionMeta = session['mediaMetadata'] as Map<String, dynamic>?;
+ if (sessionMeta != null) {
+ title ??= sessionMeta['title'] as String?;
+ author ??= sessionMeta['authorName'] as String?;
+ }
+ // Try libraryItem path
+ if (title == null || title.isEmpty) {
+ final libItem = session['libraryItem'] as Map<String, dynamic>? ?? {};
+ final media = libItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ title ??= metadata['title'] as String?;
+ author ??= metadata['authorName'] as String?;
+ }
+ // Try direct displayTitle/displayAuthor
+ title ??= session['displayTitle'] as String?;
+ author ??= session['displayAuthor'] as String?;
+ } catch (_) {}
+ }
+
+ return DownloadInfo(
+ itemId: json['itemId'] as String,
+ status: DownloadStatus.values[json['status'] as int? ?? 0],
+ localPaths: (json['localPaths'] as List<dynamic>?)
+ ?.map((e) => e as String)
+ .toList() ??
+ [],
+ sessionData: json['sessionData'] as String?,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ localCoverPath: json['localCoverPath'] as String?,
+ );
+ }
+}
+
+class DownloadService extends ChangeNotifier {
+ static final DownloadService _instance = DownloadService._();
+ factory DownloadService() => _instance;
+ DownloadService._();
+
+ final Map<String, DownloadInfo> _downloads = {};
+ String? _activeDownloadId;
+ http.Client? _httpClient;
+ String? _customDownloadPath;
+
+ /// The current download directory path, or null if using default.
+ String? get customDownloadPath => _customDownloadPath;
+
+ /// Get the effective download base directory.
+ Future<String> get downloadBasePath async {
+ if (_customDownloadPath != null && _customDownloadPath!.isNotEmpty) {
+ return _customDownloadPath!;
+ }
+ final appDir = await getApplicationDocumentsDirectory();
+ return '${appDir.path}/downloads';
+ }
+
+ /// Set a custom download location. Pass null to revert to default.
+ Future<void> setCustomDownloadPath(String? path) async {
+ _customDownloadPath = path;
+ final prefs = await SharedPreferences.getInstance();
+ if (path != null && path.isNotEmpty) {
+ await prefs.setString('custom_download_path', path);
+ } else {
+ await prefs.remove('custom_download_path');
+ }
+ notifyListeners();
+ }
+
+ /// Get a human-readable label for the current download location.
+ Future<String> get downloadLocationLabel async {
+ if (_customDownloadPath != null && _customDownloadPath!.isNotEmpty) {
+ // Shorten the path for display
+ final path = _customDownloadPath!;
+ // Try to show a friendly path relative to common roots
+ if (path.contains('/emulated/0/')) {
+ return path.split('/emulated/0/').last;
+ }
+ if (path.contains('/storage/')) {
+ return path.split('/storage/').last;
+ }
+ // Last two segments
+ final segments = path.split('/').where((s) => s.isNotEmpty).toList();
+ if (segments.length >= 2) {
+ return '${segments[segments.length - 2]}/${segments.last}';
+ }
+ return path;
+ }
+ return 'App Internal Storage (Default)';
+ }
+
+ /// Calculate total size of all downloaded files.
+ Future<int> get totalDownloadSize async {
+ int total = 0;
+ for (final info in _downloads.values) {
+ if (info.status == DownloadStatus.downloaded) {
+ for (final path in info.localPaths) {
+ try {
+ final file = File(path);
+ if (file.existsSync()) {
+ total += file.lengthSync();
+ }
+ } catch (_) {}
+ }
+ }
+ }
+ return total;
+ }
+
+ DownloadInfo getInfo(String itemId) =>
+ _downloads[itemId] ?? DownloadInfo(itemId: itemId);
+
+ bool isDownloaded(String itemId) =>
+ _downloads[itemId]?.status == DownloadStatus.downloaded;
+
+ bool isDownloading(String itemId) =>
+ _downloads[itemId]?.status == DownloadStatus.downloading;
+
+ double downloadProgress(String itemId) =>
+ _downloads[itemId]?.progress ?? 0;
+
+ /// Get all downloaded items (for home screen display).
+ List<DownloadInfo> get downloadedItems =>
+ _downloads.values
+ .where((d) => d.status == DownloadStatus.downloaded)
+ .toList();
+
+ Future<void> init() async {
+ final prefs = await SharedPreferences.getInstance();
+ _customDownloadPath = prefs.getString('custom_download_path');
+ final json = prefs.getString('downloads');
+ if (json != null) {
+ try {
+ final map = jsonDecode(json) as Map<String, dynamic>;
+ for (final entry in map.entries) {
+ final info =
+ DownloadInfo.fromJson(entry.value as Map<String, dynamic>);
+ debugPrint('[Download] Loaded: ${entry.key} '
+ 'title="${info.title}" author="${info.author}" '
+ 'cover=${info.coverUrl != null ? "yes" : "null"} '
+ 'sessionData=${info.sessionData != null ? "${info.sessionData!.length} chars" : "null"}');
+ if (info.status == DownloadStatus.downloaded) {
+ bool allExist = true;
+ for (final path in info.localPaths) {
+ if (!File(path).existsSync()) {
+ allExist = false;
+ break;
+ }
+ }
+ if (allExist) {
+ _downloads[entry.key] = info;
+ }
+ }
+ }
+ } catch (e) {
+ debugPrint('[Download] Init error: $e');
+ }
+ }
+ // Re-save to persist any metadata extracted from sessionData
+ if (_downloads.isNotEmpty) await _save();
+ notifyListeners();
+ }
+
+ /// Try to fill in missing metadata from the API (for old downloads).
+ Future<void> enrichMetadata(ApiService api) async {
+ bool changed = false;
+ final entries = Map<String, DownloadInfo>.from(_downloads);
+ for (final entry in entries.entries) {
+ final info = entry.value;
+ if (info.status != DownloadStatus.downloaded) continue;
+
+ bool needsUpdate = false;
+ String? title = info.title;
+ String? author = info.author;
+ String? coverUrl = info.coverUrl;
+ String? localCoverPath = info.localCoverPath;
+
+ // For podcast episodes, the itemId is a composite "showId-episodeId".
+ // Extract the library item ID for API calls.
+ final apiItemId = info.itemId.contains('-ep_')
+ ? info.itemId.substring(0, info.itemId.indexOf('-ep_'))
+ : info.itemId;
+
+ // Enrich missing title/author from server
+ if (title == null || title.isEmpty) {
+ try {
+ final item = await api.getLibraryItem(apiItemId);
+ if (item != null) {
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ title = metadata['title'] as String? ?? title;
+ author = metadata['authorName'] as String? ?? author;
+ coverUrl = api.getCoverUrl(apiItemId);
+ needsUpdate = true;
+ debugPrint('[Download] Enriched metadata for ${info.itemId}: $title');
+ }
+ } catch (e) {
+ debugPrint('[Download] Enrich failed for ${info.itemId}: $e');
+ }
+ }
+
+ // Cache cover locally if not already cached
+ if (localCoverPath == null || !File(localCoverPath).existsSync()) {
+ final basePath = await downloadBasePath;
+ final existingCover = File('$basePath/${info.itemId}/cover.jpg');
+ if (existingCover.existsSync()) {
+ // Already on disk from a previous download, just not tracked
+ localCoverPath = existingCover.path;
+ needsUpdate = true;
+ } else {
+ // Try to download from server
+ final url = coverUrl ?? api.getCoverUrl(apiItemId);
+ try {
+ final resp = await http.get(Uri.parse(url), headers: api.mediaHeaders)
+ .timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200 && resp.bodyBytes.isNotEmpty) {
+ final dir = Directory('$basePath/${info.itemId}');
+ if (!dir.existsSync()) dir.createSync(recursive: true);
+ final coverFile = File('${dir.path}/cover.jpg');
+ await coverFile.writeAsBytes(resp.bodyBytes);
+ localCoverPath = coverFile.path;
+ needsUpdate = true;
+ debugPrint('[Download] Cached cover for ${info.itemId}');
+ }
+ } catch (e) {
+ debugPrint('[Download] Cover cache failed for ${info.itemId}: $e');
+ }
+ }
+ }
+
+ if (needsUpdate) {
+ _downloads[entry.key] = DownloadInfo(
+ itemId: info.itemId,
+ status: info.status,
+ localPaths: info.localPaths,
+ sessionData: info.sessionData,
+ title: title ?? info.title,
+ author: author ?? info.author,
+ coverUrl: coverUrl ?? info.coverUrl,
+ localCoverPath: localCoverPath,
+ );
+ changed = true;
+ }
+ }
+ if (changed) {
+ await _save();
+ notifyListeners();
+ }
+ }
+
+ Future<void> _save() async {
+ final prefs = await SharedPreferences.getInstance();
+ final map = <String, dynamic>{};
+ for (final entry in _downloads.entries) {
+ if (entry.value.status == DownloadStatus.downloaded) {
+ map[entry.key] = entry.value.toJson();
+ }
+ }
+ await prefs.setString('downloads', jsonEncode(map));
+ }
+
+ List<String>? getLocalPaths(String itemId) {
+ final info = _downloads[itemId];
+ if (info == null || info.status != DownloadStatus.downloaded) return null;
+ return info.localPaths;
+ }
+
+ String? getCachedSessionData(String itemId) {
+ return _downloads[itemId]?.sessionData;
+ }
+
+ /// Get the local cover file path for a downloaded item.
+ /// Checks the persisted path first, then probes disk for cover.jpg.
+ Future<String?> getLocalCoverPath(String itemId) async {
+ final info = _downloads[itemId];
+ if (info == null || info.status != DownloadStatus.downloaded) return null;
+
+ // Check persisted path
+ if (info.localCoverPath != null && File(info.localCoverPath!).existsSync()) {
+ return info.localCoverPath;
+ }
+
+ // Probe disk (handles old downloads before cover caching was added)
+ final basePath = await downloadBasePath;
+ final coverFile = File('$basePath/$itemId/cover.jpg');
+ if (coverFile.existsSync()) return coverFile.path;
+
+ return null;
+ }
+
+ /// Returns null on success, error message string on failure.
+ /// For podcast episodes, pass [episodeId] so the correct API endpoint is used.
+ Future<String?> downloadItem({
+ required ApiService api,
+ required String itemId,
+ required String title,
+ String? author,
+ String? coverUrl,
+ String? episodeId,
+ }) async {
+ if (_activeDownloadId == itemId) return null;
+ if (isDownloaded(itemId)) return null;
+
+ // Check wifi-only setting
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (wifiOnly) {
+ final connectivity = await Connectivity().checkConnectivity();
+ if (!connectivity.contains(ConnectivityResult.wifi)) {
+ return 'Downloads are set to Wi-Fi only. Connect to Wi-Fi or change this in Settings.';
+ }
+ }
+
+ _activeDownloadId = itemId;
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloading,
+ progress: 0,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ );
+ notifyListeners();
+
+ // Show persistent download notification via foreground service
+ final notif = DownloadNotificationService();
+ await notif.startForeground(title: title, author: author);
+
+ try {
+ // For episodes, itemId is a composite key like 'podcastId-episodeId'.
+ // Extract the real library item ID for the API call.
+ final apiItemId = episodeId != null
+ ? itemId.substring(0, itemId.length - episodeId.length - 1)
+ : itemId;
+ final sessionData = episodeId != null
+ ? await api.startEpisodePlaybackSession(apiItemId, episodeId)
+ : await api.startPlaybackSession(apiItemId);
+ if (sessionData == null) throw Exception('Failed to start session');
+
+ final audioTracks = sessionData['audioTracks'] as List<dynamic>?;
+ if (audioTracks == null || audioTracks.isEmpty) {
+ throw Exception('No audio tracks');
+ }
+
+ final basePath = await downloadBasePath;
+ final bookDir = Directory('$basePath/$itemId');
+ if (!bookDir.existsSync()) {
+ bookDir.createSync(recursive: true);
+ }
+
+ // Cache the cover image locally for offline use (Android Auto, etc.)
+ String? localCoverPath;
+ if (coverUrl != null && coverUrl.isNotEmpty) {
+ try {
+ final coverResp = await http.get(Uri.parse(coverUrl), headers: api.mediaHeaders)
+ .timeout(const Duration(seconds: 10));
+ if (coverResp.statusCode == 200 && coverResp.bodyBytes.isNotEmpty) {
+ final coverFile = File('${bookDir.path}/cover.jpg');
+ await coverFile.writeAsBytes(coverResp.bodyBytes);
+ localCoverPath = coverFile.path;
+ debugPrint('[Download] Cached cover image: $localCoverPath');
+ }
+ } catch (e) {
+ debugPrint('[Download] Cover cache failed (non-fatal): $e');
+ }
+ }
+
+ final localPaths = List<String?>.filled(audioTracks.length, null);
+ _httpClient = http.Client();
+
+ // Track progress per-track for overall calculation
+ final trackProgress = List<double>.filled(audioTracks.length, 0.0);
+ int _lastNotifPercent = -1;
+ DateTime _lastUIUpdate = DateTime.now();
+
+ void _updateProgress() {
+ final overall = trackProgress.reduce((a, b) => a + b) / audioTracks.length;
+ final now = DateTime.now();
+ // Throttle UI updates to max ~4/sec
+ if (now.difference(_lastUIUpdate).inMilliseconds > 250) {
+ _lastUIUpdate = now;
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloading,
+ progress: overall,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ );
+ notifyListeners();
+ }
+ // Throttle notification to every 2%
+ final pct = (overall * 50).round();
+ if (pct != _lastNotifPercent) {
+ _lastNotifPercent = pct;
+ notif.showProgress(title: title, author: author, progress: overall);
+ }
+ }
+
+ Future<void> _downloadTrack(int i) async {
+ final track = audioTracks[i] as Map<String, dynamic>;
+ final contentUrl = track['contentUrl'] as String? ?? '';
+ final fullUrl = api.buildTrackUrl(contentUrl);
+
+ final mimeType = track['mimeType'] as String? ?? 'audio/mpeg';
+ final ext = mimeType.contains('mp4')
+ ? 'm4a'
+ : mimeType.contains('flac')
+ ? 'flac'
+ : mimeType.contains('ogg')
+ ? 'ogg'
+ : 'mp3';
+
+ final filePath =
+ '${bookDir.path}/track_${i.toString().padLeft(3, '0')}.$ext';
+ final file = File(filePath);
+
+ debugPrint('[Download] Track ${i + 1}/${audioTracks.length}: $fullUrl');
+
+ final request = http.Request('GET', Uri.parse(fullUrl));
+ api.mediaHeaders.forEach((key, value) => request.headers[key] = value);
+ final response = await _httpClient!.send(request);
+
+ if (response.statusCode != 200) {
+ throw Exception('HTTP ${response.statusCode} for track ${i + 1}');
+ }
+
+ final totalBytes = response.contentLength ?? -1;
+ int receivedBytes = 0;
+ final sink = file.openWrite();
+
+ await for (final chunk in response.stream) {
+ sink.add(chunk);
+ receivedBytes += chunk.length;
+ trackProgress[i] = totalBytes > 0 ? receivedBytes / totalBytes : 0.5;
+ _updateProgress();
+ }
+
+ await sink.close();
+ localPaths[i] = filePath;
+ }
+
+ // Download tracks in parallel batches of 3
+ const concurrency = 3;
+ for (int batch = 0; batch < audioTracks.length; batch += concurrency) {
+ final end = (batch + concurrency).clamp(0, audioTracks.length);
+ await Future.wait([
+ for (int i = batch; i < end; i++) _downloadTrack(i),
+ ]);
+ }
+
+ // Final UI update
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloading,
+ progress: 1.0,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ );
+ notifyListeners();
+
+ final completedPaths = localPaths.whereType<String>().toList();
+
+ final sessionId = sessionData['id'] as String?;
+ if (sessionId != null) {
+ try {
+ await api.closePlaybackSession(sessionId);
+ } catch (_) {}
+ }
+
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloaded,
+ localPaths: completedPaths,
+ sessionData: jsonEncode(sessionData),
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ localCoverPath: localCoverPath,
+ );
+ await _save();
+
+ // Show completion notification
+ await notif.showComplete(title: title);
+
+ // If this book is currently streaming, hot-swap to local files
+ final player = AudioPlayerService();
+ if (player.currentItemId == itemId && player.hasBook) {
+ await player.switchToLocal(itemId);
+ }
+
+ debugPrint('[Download] Complete: $title (${completedPaths.length} files)');
+ } catch (e) {
+ debugPrint('[Download] Error: $e');
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.error,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ );
+ // Show error notification
+ await notif.showError(title: title, message: 'Download failed: $title');
+ }
+
+ _activeDownloadId = null;
+ _httpClient = null;
+
+ notifyListeners();
+ return null;
+ }
+
+ Future<void> deleteDownload(String itemId) async {
+ final info = _downloads[itemId];
+ if (info == null) return;
+
+ for (final path in info.localPaths) {
+ try {
+ final file = File(path);
+ if (file.existsSync()) file.deleteSync();
+ } catch (_) {}
+ }
+
+ try {
+ final basePath = await downloadBasePath;
+ final bookDir = Directory('$basePath/$itemId');
+ if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);
+ } catch (_) {}
+
+ _downloads.remove(itemId);
+ await _save();
+ notifyListeners();
+ }
+
+ void cancelDownload(String itemId) {
+ if (_activeDownloadId == itemId) {
+ _httpClient?.close();
+ _httpClient = null;
+ _activeDownloadId = null;
+ DownloadNotificationService().dismiss();
+ }
+ _downloads.remove(itemId);
+ notifyListeners();
+ }
+}
diff --git a/lib/services/equalizer_service.dart b/lib/services/equalizer_service.dart
new file mode 100644
index 00000000..210ee695
--- /dev/null
+++ b/lib/services/equalizer_service.dart
@@ -0,0 +1,258 @@
+import 'dart:async';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+/// Android AudioEffect equalizer bands and presets via platform channels.
+/// Falls back gracefully on unsupported devices.
+class EqualizerService extends ChangeNotifier {
+ static final EqualizerService _instance = EqualizerService._();
+ factory EqualizerService() => _instance;
+ EqualizerService._();
+
+ static const _channel = MethodChannel('com.absorb.equalizer');
+
+ // ── State ──
+ bool _available = false;
+ bool _enabled = false;
+ String _activePreset = 'flat';
+ List<double> _bandLevels = []; // dB values per band
+ List<int> _bandFrequencies = []; // center frequencies (Hz)
+ double _minLevel = -15.0;
+ double _maxLevel = 15.0;
+ double _bassBoost = 0.0; // 0.0–1.0
+ double _virtualizer = 0.0; // 0.0–1.0
+ double _loudnessGain = 0.0; // 0.0–1.0
+
+ // Built-in presets (EQ curve shapes)
+ static const Map<String, List<double>> presets = {
+ 'flat': [0, 0, 0, 0, 0],
+ 'voice boost': [2, 4, 5, 3, 1],
+ 'bass boost': [5, 3, 0, -1, -2],
+ 'treble boost': [-2, -1, 0, 3, 5],
+ 'podcast': [3, 5, 4, 2, 0],
+ 'audiobook': [1, 3, 5, 4, 2],
+ 'reduce noise': [-3, -1, 0, -1, -3],
+ 'loudness': [4, 2, 0, 2, 4],
+ };
+
+ // Getters
+ bool get available => _available;
+ bool get enabled => _enabled;
+ String get activePreset => _activePreset;
+ List<double> get bandLevels => List.unmodifiable(_bandLevels);
+ List<int> get bandFrequencies => List.unmodifiable(_bandFrequencies);
+ double get minLevel => _minLevel;
+ double get maxLevel => _maxLevel;
+ double get bassBoost => _bassBoost;
+ double get virtualizer => _virtualizer;
+ double get loudnessGain => _loudnessGain;
+
+ /// Initialize — try to connect to platform EQ, fall back to software presets.
+ Future<void> init() async {
+ await _loadSettings();
+
+ try {
+ final result = await _channel.invokeMethod('init');
+ if (result is Map) {
+ _available = true;
+ _bandFrequencies = List<int>.from(result['frequencies'] ?? []);
+ _minLevel = (result['minLevel'] as num?)?.toDouble() ?? -15.0;
+ _maxLevel = (result['maxLevel'] as num?)?.toDouble() ?? 15.0;
+ final numBands = _bandFrequencies.length;
+ if (_bandLevels.length != numBands) {
+ _bandLevels = List.filled(numBands, 0.0);
+ }
+ debugPrint('[EQ] Platform EQ available: ${_bandFrequencies.length} bands');
+ if (_enabled) _applyCurrentSettings();
+ }
+ } on MissingPluginException {
+ debugPrint('[EQ] Platform channel not available — using software presets');
+ _setupSoftwareFallback();
+ } on PlatformException catch (e) {
+ debugPrint('[EQ] Platform EQ error: $e — using software presets');
+ _setupSoftwareFallback();
+ } catch (e) {
+ debugPrint('[EQ] Unexpected error: $e — using software presets');
+ _setupSoftwareFallback();
+ }
+ notifyListeners();
+ }
+
+ void _setupSoftwareFallback() {
+ _available = true; // We still expose the UI, just software-side
+ _bandFrequencies = [60, 230, 910, 3600, 14000];
+ _minLevel = -15.0;
+ _maxLevel = 15.0;
+ if (_bandLevels.length != 5) {
+ _bandLevels = List.filled(5, 0.0);
+ }
+ }
+
+ /// Toggle EQ on/off.
+ Future<void> setEnabled(bool value) async {
+ _enabled = value;
+ if (_enabled) {
+ _applyCurrentSettings();
+ } else {
+ _resetPlatform();
+ }
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Apply a named preset.
+ Future<void> applyPreset(String name) async {
+ final curve = presets[name];
+ if (curve == null) return;
+
+ _activePreset = name;
+
+ // Scale preset values to our band count and level range
+ final numBands = _bandLevels.length;
+ for (int i = 0; i < numBands; i++) {
+ final presetIdx = (i * curve.length / numBands).floor().clamp(0, curve.length - 1);
+ _bandLevels[i] = curve[presetIdx].clamp(_minLevel, _maxLevel);
+ }
+
+ if (_enabled) _applyCurrentSettings();
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Set a single band level.
+ Future<void> setBandLevel(int bandIndex, double level) async {
+ if (bandIndex < 0 || bandIndex >= _bandLevels.length) return;
+ _bandLevels[bandIndex] = level.clamp(_minLevel, _maxLevel);
+ _activePreset = 'custom';
+ if (_enabled) _applyBand(bandIndex, _bandLevels[bandIndex]);
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Set bass boost (0.0–1.0).
+ Future<void> setBassBoost(double value) async {
+ _bassBoost = value.clamp(0.0, 1.0);
+ if (_enabled) {
+ try {
+ await _channel.invokeMethod('setBassBoost', {'strength': (_bassBoost * 1000).round()});
+ } catch (_) {}
+ }
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Set virtualizer / surround (0.0–1.0).
+ Future<void> setVirtualizer(double value) async {
+ _virtualizer = value.clamp(0.0, 1.0);
+ if (_enabled) {
+ try {
+ await _channel.invokeMethod('setVirtualizer', {'strength': (_virtualizer * 1000).round()});
+ } catch (_) {}
+ }
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Set loudness enhancer gain (0.0–1.0).
+ Future<void> setLoudnessGain(double value) async {
+ _loudnessGain = value.clamp(0.0, 1.0);
+ if (_enabled) {
+ try {
+ await _channel.invokeMethod('setLoudness', {'gain': (_loudnessGain * 1500).round()});
+ } catch (_) {}
+ }
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Reset everything to flat/off.
+ Future<void> resetAll() async {
+ _activePreset = 'flat';
+ _bandLevels = List.filled(_bandLevels.length, 0.0);
+ _bassBoost = 0.0;
+ _virtualizer = 0.0;
+ _loudnessGain = 0.0;
+ if (_enabled) {
+ _applyCurrentSettings();
+ }
+ await _saveSettings();
+ notifyListeners();
+ }
+
+ /// Attach effects to an ExoPlayer audio session.
+ /// Call this whenever the audio session ID changes (new playback).
+ Future<void> attachToSession(int sessionId) async {
+ if (sessionId <= 0) return;
+ try {
+ await _channel.invokeMethod('attachSession', {'sessionId': sessionId});
+ debugPrint('[EQ] Attached to audio session $sessionId');
+ if (_enabled) _applyCurrentSettings();
+ } catch (e) {
+ debugPrint('[EQ] attachSession failed: $e');
+ }
+ }
+
+ // ── Platform communication ──
+
+ Future<void> _applyCurrentSettings() async {
+ for (int i = 0; i < _bandLevels.length; i++) {
+ _applyBand(i, _bandLevels[i]);
+ }
+ try {
+ await _channel.invokeMethod('setBassBoost', {'strength': (_bassBoost * 1000).round()});
+ await _channel.invokeMethod('setVirtualizer', {'strength': (_virtualizer * 1000).round()});
+ await _channel.invokeMethod('setLoudness', {'gain': (_loudnessGain * 1500).round()});
+ await _channel.invokeMethod('setEnabled', {'enabled': _enabled});
+ } catch (_) {}
+ }
+
+ Future<void> _applyBand(int index, double level) async {
+ try {
+ await _channel.invokeMethod('setBand', {
+ 'band': index,
+ 'level': (level * 100).round(), // millibels
+ });
+ } catch (_) {}
+ }
+
+ Future<void> _resetPlatform() async {
+ try {
+ await _channel.invokeMethod('setEnabled', {'enabled': false});
+ } catch (_) {}
+ }
+
+ // ── Persistence ──
+
+ Future<void> _loadSettings() async {
+ final prefs = await SharedPreferences.getInstance();
+ _enabled = prefs.getBool('eq_enabled') ?? false;
+ _activePreset = prefs.getString('eq_preset') ?? 'flat';
+ _bassBoost = prefs.getDouble('eq_bassBoost') ?? 0.0;
+ _virtualizer = prefs.getDouble('eq_virtualizer') ?? 0.0;
+ _loudnessGain = prefs.getDouble('eq_loudnessGain') ?? 0.0;
+
+ final bandStr = prefs.getString('eq_bands');
+ if (bandStr != null) {
+ _bandLevels = bandStr.split(',')
+ .map((s) => double.tryParse(s) ?? 0.0)
+ .toList();
+ }
+ }
+
+ Future<void> _saveSettings() async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('eq_enabled', _enabled);
+ await prefs.setString('eq_preset', _activePreset);
+ await prefs.setDouble('eq_bassBoost', _bassBoost);
+ await prefs.setDouble('eq_virtualizer', _virtualizer);
+ await prefs.setDouble('eq_loudnessGain', _loudnessGain);
+ await prefs.setString('eq_bands', _bandLevels.map((l) => l.toStringAsFixed(1)).join(','));
+ }
+
+ /// Formatted frequency label.
+ String freqLabel(int hz) {
+ if (hz >= 1000) return '${(hz / 1000).toStringAsFixed(hz % 1000 == 0 ? 0 : 1)}k';
+ return '${hz}Hz';
+ }
+}
diff --git a/lib/services/metadata_override_service.dart b/lib/services/metadata_override_service.dart
new file mode 100644
index 00000000..9f668ae3
--- /dev/null
+++ b/lib/services/metadata_override_service.dart
@@ -0,0 +1,106 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'scoped_prefs.dart';
+
+/// Stores user-chosen metadata overrides locally per item.
+/// These override server metadata that is empty or wrong, without
+/// modifying the server itself. Persisted via ScopedPrefs (user-scoped).
+class MetadataOverrideService {
+ // Singleton
+ static final MetadataOverrideService _instance = MetadataOverrideService._();
+ factory MetadataOverrideService() => _instance;
+ MetadataOverrideService._();
+
+ static const _prefix = 'metadata_override_';
+
+ /// Save a metadata override for an item. Only non-null fields are stored.
+ Future<void> save(String itemId, Map<String, dynamic> override) async {
+ // Merge with any existing override
+ final existing = await get(itemId);
+ final merged = <String, dynamic>{...?existing, ...override};
+ // Remove null values
+ merged.removeWhere((_, v) => v == null);
+ await ScopedPrefs.setString('$_prefix$itemId', jsonEncode(merged));
+ debugPrint('[MetadataOverride] Saved override for $itemId: ${merged.keys.join(', ')}');
+ }
+
+ /// Get a metadata override for an item, or null if none exists.
+ Future<Map<String, dynamic>?> get(String itemId) async {
+ final raw = await ScopedPrefs.getString('$_prefix$itemId');
+ if (raw == null) return null;
+ try {
+ return jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Delete a metadata override for an item.
+ Future<void> delete(String itemId) async {
+ await ScopedPrefs.remove('$_prefix$itemId');
+ }
+
+ /// Check if an item has a local override.
+ Future<bool> hasOverride(String itemId) async {
+ return await ScopedPrefs.containsKey('$_prefix$itemId');
+ }
+
+ /// Apply overrides to a server item map. Modifies in place and returns it.
+ /// Only fills in fields that are empty/missing on the server item.
+ Map<String, dynamic> applyOverrides(
+ Map<String, dynamic> item, Map<String, dynamic> override) {
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata =
+ Map<String, dynamic>.from(media['metadata'] as Map<String, dynamic>? ?? {});
+
+ // Only override if the server field is empty
+ void fillIfEmpty(String metaKey, String overrideKey) {
+ final current = metadata[metaKey];
+ final replacement = override[overrideKey];
+ if (replacement != null &&
+ replacement.toString().isNotEmpty &&
+ (current == null || current.toString().trim().isEmpty)) {
+ metadata[metaKey] = replacement;
+ }
+ }
+
+ fillIfEmpty('title', 'title');
+ fillIfEmpty('authorName', 'author');
+ fillIfEmpty('narratorName', 'narrator');
+ fillIfEmpty('description', 'description');
+ fillIfEmpty('publisher', 'publisher');
+ fillIfEmpty('publishedYear', 'publishedYear');
+ fillIfEmpty('asin', 'asin');
+ fillIfEmpty('isbn', 'isbn');
+
+ // Genres: merge (add missing ones)
+ final overrideGenres = override['genres'] as List<dynamic>?;
+ if (overrideGenres != null && overrideGenres.isNotEmpty) {
+ final existing = (metadata['genres'] as List<dynamic>?)?.cast<String>() ?? [];
+ if (existing.isEmpty) {
+ metadata['genres'] = overrideGenres;
+ }
+ }
+
+ // Series
+ final overrideSeries = override['series'] as List<dynamic>?;
+ if (overrideSeries != null && overrideSeries.isNotEmpty) {
+ final existing = metadata['series'] as List<dynamic>? ?? [];
+ if (existing.isEmpty) {
+ metadata['series'] = overrideSeries;
+ }
+ }
+
+ // Write back
+ final updatedMedia = Map<String, dynamic>.from(media);
+ updatedMedia['metadata'] = metadata;
+ item['media'] = updatedMedia;
+
+ // Cover URL override (stored separately since it's not in metadata)
+ if (override['coverUrl'] != null) {
+ item['_localCoverUrl'] = override['coverUrl'];
+ }
+
+ return item;
+ }
+}
diff --git a/lib/services/oidc_service.dart b/lib/services/oidc_service.dart
new file mode 100644
index 00000000..2121cc75
--- /dev/null
+++ b/lib/services/oidc_service.dart
@@ -0,0 +1,252 @@
+import 'dart:convert';
+import 'dart:math';
+import 'package:crypto/crypto.dart';
+import 'package:flutter/foundation.dart';
+import 'package:http/http.dart' as http;
+import 'package:url_launcher/url_launcher.dart';
+import 'dart:io' show Cookie, HttpClient, HttpClientRequest, HttpHeaders;
+
+/// Manages the OIDC/OAuth2 PKCE flow for audiobookshelf SSO login.
+class OidcService {
+ static final OidcService _instance = OidcService._();
+ factory OidcService() => _instance;
+ OidcService._();
+
+ // PKCE state
+ String? _codeVerifier;
+ String? _codeChallenge;
+ String? _state;
+ String? _serverUrl;
+
+ /// The raw cookie strings from the /auth/openid response.
+ List<String> _rawCookies = [];
+
+ static const _redirectUri = 'audiobookshelf://oauth';
+ static const _clientId = 'Audiobookshelf-App';
+
+ /// Generate a cryptographically random string of [length] bytes, base64url-encoded.
+ String _generateRandom(int length) {
+ final random = Random.secure();
+ final bytes = List<int>.generate(length, (_) => random.nextInt(256));
+ return base64Url.encode(bytes).replaceAll('=', '');
+ }
+
+ /// Generate PKCE code_verifier and code_challenge (S256).
+ void _generatePkce() {
+ _codeVerifier = _generateRandom(32); // 43-char min
+ final bytes = utf8.encode(_codeVerifier!);
+ final digest = sha256.convert(bytes);
+ _codeChallenge = base64Url.encode(digest.bytes).replaceAll('=', '');
+ }
+
+ /// Start the OIDC login flow.
+ /// Returns null on success (browser opened), or an error string on failure.
+ Future<String?> startLogin(String serverUrl) async {
+ _serverUrl = serverUrl.endsWith('/') ? serverUrl.substring(0, serverUrl.length - 1) : serverUrl;
+ _generatePkce();
+ _state = _generateRandom(16);
+ _rawCookies = [];
+
+ final authUrl = '$_serverUrl/auth/openid'
+ '?code_challenge=$_codeChallenge'
+ '&code_challenge_method=S256'
+ '&redirect_uri=${Uri.encodeComponent(_redirectUri)}'
+ '&client_id=${Uri.encodeComponent(_clientId)}'
+ '&response_type=code'
+ '&state=$_state';
+
+ debugPrint('[OIDC] Starting auth flow: $authUrl');
+
+ try {
+ // Use dart:io HttpClient to properly capture Set-Cookie headers
+ // (the http package merges them and loses data)
+ final client = HttpClient();
+ client.connectionTimeout = const Duration(seconds: 15);
+
+ try {
+ final request = await client.getUrl(Uri.parse(authUrl));
+ request.followRedirects = false;
+ final response = await request.close();
+
+ // Capture all cookies
+ final cookies = response.cookies;
+ for (final cookie in cookies) {
+ _rawCookies.add('${cookie.name}=${cookie.value}');
+ debugPrint('[OIDC] Captured cookie: ${cookie.name}');
+ }
+
+ // Also try raw header
+ if (_rawCookies.isEmpty) {
+ final rawSetCookie = response.headers[HttpHeaders.setCookieHeader];
+ if (rawSetCookie != null) {
+ for (final sc in rawSetCookie) {
+ final nameValue = sc.split(';').first.trim();
+ _rawCookies.add(nameValue);
+ debugPrint('[OIDC] Captured raw cookie: $nameValue');
+ }
+ }
+ }
+
+ if (response.statusCode == 302 || response.statusCode == 301) {
+ final location = response.headers.value(HttpHeaders.locationHeader);
+ if (location != null && location.isNotEmpty) {
+ debugPrint('[OIDC] Redirecting to OIDC provider: $location');
+
+ // Drain the response body
+ await response.drain<void>();
+
+ final uri = Uri.parse(location);
+ final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
+ if (!launched) {
+ return 'Could not open browser for SSO login';
+ }
+ return null; // Success — waiting for callback
+ }
+ await response.drain<void>();
+ return 'Server did not return a redirect URL';
+ } else {
+ final body = await response.transform(utf8.decoder).join();
+ debugPrint('[OIDC] Unexpected status ${response.statusCode}: $body');
+ return 'Server returned status ${response.statusCode}';
+ }
+ } finally {
+ client.close();
+ }
+ } catch (e) {
+ debugPrint('[OIDC] Error starting login: $e');
+ return 'Failed to start SSO login: $e';
+ }
+ }
+
+ /// Build a Cookie header string from stored cookies.
+ String get _cookieHeader => _rawCookies.join('; ');
+
+ /// Handle the callback from the deep link.
+ /// [uri] is the full audiobookshelf://oauth?code=X&state=Y URI.
+ /// Returns the user login response (same as /login) or null on failure.
+ Future<Map<String, dynamic>?> handleCallback(Uri uri) async {
+ final code = uri.queryParameters['code'];
+ final state = uri.queryParameters['state'];
+
+ debugPrint('[OIDC] Callback received: code=${code != null ? '***' : 'null'}, state=$state');
+
+ if (code == null || code.isEmpty) {
+ debugPrint('[OIDC] No code in callback');
+ return null;
+ }
+
+ // Verify state matches
+ if (state != _state) {
+ debugPrint('[OIDC] State mismatch: expected=$_state, got=$state');
+ return null;
+ }
+
+ if (_serverUrl == null || _codeVerifier == null) {
+ debugPrint('[OIDC] Missing server URL or code verifier');
+ return null;
+ }
+
+ // Call /auth/openid/callback with state + code + code_verifier
+ final callbackUrl = '$_serverUrl/auth/openid/callback'
+ '?state=${Uri.encodeComponent(_state!)}'
+ '&code=${Uri.encodeComponent(code)}'
+ '&code_verifier=${Uri.encodeComponent(_codeVerifier!)}';
+
+ debugPrint('[OIDC] Calling callback: $callbackUrl');
+ debugPrint('[OIDC] Sending ${_rawCookies.length} cookies');
+
+ try {
+ // Use dart:io HttpClient for proper cookie handling
+ final client = HttpClient();
+ client.connectionTimeout = const Duration(seconds: 15);
+
+ try {
+ final request = await client.getUrl(Uri.parse(callbackUrl));
+ request.followRedirects = false;
+
+ // Attach cookies
+ if (_rawCookies.isNotEmpty) {
+ request.headers.set(HttpHeaders.cookieHeader, _cookieHeader);
+ }
+
+ final response = await request.close();
+ final body = await response.transform(utf8.decoder).join();
+
+ debugPrint('[OIDC] Callback response: ${response.statusCode}');
+ debugPrint('[OIDC] Callback body length: ${body.length}');
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(body) as Map<String, dynamic>;
+ _cleanup();
+ return data;
+ } else {
+ debugPrint('[OIDC] Callback error: $body');
+ return null;
+ }
+ } finally {
+ client.close();
+ }
+ } catch (e) {
+ debugPrint('[OIDC] Callback exception: $e');
+ return null;
+ }
+ }
+
+ /// Check if we have an active OIDC flow waiting for callback.
+ bool get isWaitingForCallback => _state != null && _codeVerifier != null;
+
+ /// Clean up after flow completes or is cancelled.
+ void _cleanup() {
+ _codeVerifier = null;
+ _codeChallenge = null;
+ _state = null;
+ _rawCookies = [];
+ }
+
+ /// Cancel any in-progress flow.
+ void cancel() => _cleanup();
+
+ /// Fetch server status to check if OIDC is available.
+ static Future<Map<String, dynamic>?> getServerAuthConfig(String serverUrl) async {
+ final url = serverUrl.endsWith('/') ? '${serverUrl}status' : '$serverUrl/status';
+ try {
+ final response = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 10));
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ debugPrint('[OIDC] Failed to fetch server status: $e');
+ }
+ return null;
+ }
+
+ /// Check if a server has OIDC enabled.
+ static Future<OidcConfig?> checkOidcEnabled(String serverUrl) async {
+ final status = await getServerAuthConfig(serverUrl);
+ if (status == null) return null;
+
+ final authMethods = status['authMethods'] as List<dynamic>? ?? [];
+ final hasOidc = authMethods.contains('openid');
+ final authFormData = status['authFormData'] as Map<String, dynamic>? ?? {};
+ final buttonText = authFormData['openIDButtonText'] as String? ?? 'Login with OpenID';
+
+ return OidcConfig(
+ enabled: hasOidc,
+ buttonText: buttonText,
+ hasLocalAuth: authMethods.contains('local'),
+ );
+ }
+}
+
+/// Configuration about what auth methods a server supports.
+class OidcConfig {
+ final bool enabled;
+ final String buttonText;
+ final bool hasLocalAuth;
+
+ const OidcConfig({
+ required this.enabled,
+ required this.buttonText,
+ required this.hasLocalAuth,
+ });
+}
diff --git a/lib/services/playback_history_service.dart b/lib/services/playback_history_service.dart
new file mode 100644
index 00000000..b6f9cd9c
--- /dev/null
+++ b/lib/services/playback_history_service.dart
@@ -0,0 +1,157 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+/// Types of playback events we track.
+enum PlaybackEventType {
+ play,
+ pause,
+ seek,
+ syncLocal,
+ syncServer,
+ autoRewind,
+ skipForward,
+ skipBackward,
+ speedChange,
+}
+
+/// A single playback event entry.
+class PlaybackEvent {
+ final PlaybackEventType type;
+ final double positionSeconds;
+ final DateTime timestamp;
+ final String? detail;
+
+ PlaybackEvent({
+ required this.type,
+ required this.positionSeconds,
+ required this.timestamp,
+ this.detail,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'type': type.name,
+ 'pos': positionSeconds,
+ 'ts': timestamp.millisecondsSinceEpoch,
+ if (detail != null) 'detail': detail,
+ };
+
+ factory PlaybackEvent.fromJson(Map<String, dynamic> json) {
+ return PlaybackEvent(
+ type: PlaybackEventType.values.firstWhere(
+ (e) => e.name == json['type'],
+ orElse: () => PlaybackEventType.play,
+ ),
+ positionSeconds: (json['pos'] as num).toDouble(),
+ timestamp: DateTime.fromMillisecondsSinceEpoch(json['ts'] as int),
+ detail: json['detail'] as String?,
+ );
+ }
+
+ String get label {
+ switch (type) {
+ case PlaybackEventType.play:
+ return 'Resumed playback';
+ case PlaybackEventType.pause:
+ return 'Paused';
+ case PlaybackEventType.seek:
+ return 'Seeked';
+ case PlaybackEventType.syncLocal:
+ return 'Saved locally';
+ case PlaybackEventType.syncServer:
+ return 'Synced to server';
+ case PlaybackEventType.autoRewind:
+ return 'Auto-rewound';
+ case PlaybackEventType.skipForward:
+ return 'Skipped forward';
+ case PlaybackEventType.skipBackward:
+ return 'Skipped back';
+ case PlaybackEventType.speedChange:
+ return 'Speed changed';
+ }
+ }
+
+ String get icon {
+ switch (type) {
+ case PlaybackEventType.play:
+ return '▶';
+ case PlaybackEventType.pause:
+ return '⏸';
+ case PlaybackEventType.seek:
+ return '⏩';
+ case PlaybackEventType.syncLocal:
+ return '💾';
+ case PlaybackEventType.syncServer:
+ return '☁';
+ case PlaybackEventType.autoRewind:
+ return '⏪';
+ case PlaybackEventType.skipForward:
+ return '⏭';
+ case PlaybackEventType.skipBackward:
+ return '⏮';
+ case PlaybackEventType.speedChange:
+ return '⚡';
+ }
+ }
+}
+
+/// Stores per-book playback history in SharedPreferences.
+class PlaybackHistoryService {
+ static final PlaybackHistoryService _instance = PlaybackHistoryService._();
+ factory PlaybackHistoryService() => _instance;
+ PlaybackHistoryService._();
+
+ static const int _maxEventsPerBook = 200;
+
+ /// Log an event for a book.
+ Future<void> log({
+ required String itemId,
+ required PlaybackEventType type,
+ required double positionSeconds,
+ String? detail,
+ }) async {
+ final event = PlaybackEvent(
+ type: type,
+ positionSeconds: positionSeconds,
+ timestamp: DateTime.now(),
+ detail: detail,
+ );
+
+ final prefs = await SharedPreferences.getInstance();
+ final key = 'playback_history_$itemId';
+ final existing = prefs.getStringList(key) ?? [];
+
+ existing.add(jsonEncode(event.toJson()));
+
+ // Trim to max size (keep most recent)
+ if (existing.length > _maxEventsPerBook) {
+ existing.removeRange(0, existing.length - _maxEventsPerBook);
+ }
+
+ await prefs.setStringList(key, existing);
+ }
+
+ /// Get all events for a book, newest first.
+ Future<List<PlaybackEvent>> getHistory(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ final key = 'playback_history_$itemId';
+ final stored = prefs.getStringList(key) ?? [];
+
+ final events = <PlaybackEvent>[];
+ for (final json in stored) {
+ try {
+ events.add(PlaybackEvent.fromJson(jsonDecode(json)));
+ } catch (e) {
+ debugPrint('[History] Failed to parse event: $e');
+ }
+ }
+
+ return events.reversed.toList(); // newest first
+ }
+
+ /// Clear history for a book.
+ Future<void> clearHistory(String itemId) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove('playback_history_$itemId');
+ }
+}
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
new file mode 100644
index 00000000..67a4270d
--- /dev/null
+++ b/lib/services/progress_sync_service.dart
@@ -0,0 +1,200 @@
+import 'dart:async';
+import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:connectivity_plus/connectivity_plus.dart';
+import 'api_service.dart';
+import 'scoped_prefs.dart';
+
+/// Manages local progress storage and server sync.
+/// Progress is ALWAYS saved locally first, then synced to server when online.
+/// All progress data is scoped to the active user account via ScopedPrefs.
+class ProgressSyncService {
+ static final ProgressSyncService _instance = ProgressSyncService._();
+ factory ProgressSyncService() => _instance;
+ ProgressSyncService._();
+
+ StreamSubscription? _connectivitySub;
+ bool _isOnline = true;
+
+ /// Initialize — start listening for connectivity changes.
+ Future<void> init() async {
+ final result = await Connectivity().checkConnectivity();
+ _isOnline = !result.contains(ConnectivityResult.none);
+
+ _connectivitySub = Connectivity().onConnectivityChanged.listen((result) {
+ final wasOffline = !_isOnline;
+ _isOnline = !result.contains(ConnectivityResult.none);
+ if (_isOnline && wasOffline) {
+ debugPrint('[Sync] Back online — flushing pending syncs');
+ flushPendingSync();
+ }
+ });
+ }
+
+ bool get isOnline => _isOnline;
+
+ /// Save progress locally. Always succeeds.
+ Future<void> saveLocal({
+ required String itemId,
+ required double currentTime,
+ required double duration,
+ required double speed,
+ }) async {
+ final data = {
+ 'itemId': itemId,
+ 'currentTime': currentTime,
+ 'duration': duration,
+ 'speed': speed,
+ 'timestamp': DateTime.now().millisecondsSinceEpoch,
+ };
+ await ScopedPrefs.setString('progress_$itemId', jsonEncode(data));
+
+ final pendingList = await ScopedPrefs.getStringList('pending_syncs');
+ if (!pendingList.contains(itemId)) {
+ pendingList.add(itemId);
+ await ScopedPrefs.setStringList('pending_syncs', pendingList);
+ }
+ }
+
+ /// Get locally saved progress for an item.
+ Future<Map<String, dynamic>?> getLocal(String itemId) async {
+ final json = await ScopedPrefs.getString('progress_$itemId');
+ if (json == null) return null;
+ try {
+ return jsonDecode(json) as Map<String, dynamic>;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Get the saved currentTime for an item (for resuming).
+ Future<double> getSavedPosition(String itemId) async {
+ final data = await getLocal(itemId);
+ return (data?['currentTime'] as num?)?.toDouble() ?? 0;
+ }
+
+ /// Delete locally saved progress for an item.
+ Future<void> deleteLocal(String itemId) async {
+ await ScopedPrefs.remove('progress_$itemId');
+ final pendingList = await ScopedPrefs.getStringList('pending_syncs');
+ pendingList.remove(itemId);
+ await ScopedPrefs.setStringList('pending_syncs', pendingList);
+ }
+
+ /// Sync a single item to the server. Returns true if synced.
+ Future<bool> syncToServer({
+ required ApiService api,
+ required String itemId,
+ String? sessionId,
+ }) async {
+ if (!_isOnline) {
+ debugPrint('[Sync] Skipped — offline');
+ return false;
+ }
+
+ final data = await getLocal(itemId);
+ if (data == null) {
+ debugPrint('[Sync] Skipped — no local data for $itemId');
+ return false;
+ }
+
+ final currentTime = (data['currentTime'] as num?)?.toDouble() ?? 0;
+ final duration = (data['duration'] as num?)?.toDouble() ?? 0;
+ debugPrint('[Sync] Syncing $itemId: currentTime=$currentTime, duration=$duration, sessionId=$sessionId');
+
+ try {
+ if (sessionId != null) {
+ await api.syncPlaybackSession(
+ sessionId,
+ currentTime: currentTime,
+ duration: duration,
+ );
+ } else {
+ await api.updateProgress(
+ itemId,
+ currentTime: currentTime,
+ duration: duration,
+ );
+ }
+
+ final pendingList = await ScopedPrefs.getStringList('pending_syncs');
+ pendingList.remove(itemId);
+ await ScopedPrefs.setStringList('pending_syncs', pendingList);
+
+ debugPrint('[Sync] Synced $itemId: ${currentTime}s');
+ return true;
+ } catch (e) {
+ debugPrint('[Sync] Failed for $itemId: $e');
+ return false;
+ }
+ }
+
+ /// Flush all pending syncs (call when coming back online).
+ /// Compares local vs server timestamps — last-write-wins.
+ Future<void> flushPendingSync({ApiService? api}) async {
+ if (!_isOnline || api == null) return;
+
+ final pendingList = List<String>.from(
+ await ScopedPrefs.getStringList('pending_syncs'));
+
+ if (pendingList.isEmpty) return;
+ debugPrint('[Sync] Flushing ${pendingList.length} pending syncs');
+
+ for (final itemId in pendingList) {
+ final data = await getLocal(itemId);
+ if (data == null) continue;
+
+ final localTime = (data['currentTime'] as num?)?.toDouble() ?? 0;
+ final localDuration = (data['duration'] as num?)?.toDouble() ?? 0;
+ final localTimestamp = (data['timestamp'] as num?)?.toInt() ?? 0;
+ if (localTime <= 0) continue;
+
+ try {
+ final serverProgress = await api.getItemProgress(itemId);
+ if (serverProgress != null) {
+ final serverTimestamp = (serverProgress['lastUpdate'] as num?)?.toInt() ?? 0;
+ final serverTime = (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;
+
+ if (serverTimestamp > localTimestamp) {
+ debugPrint('[Sync] Server is newer for $itemId: server=${serverTime}s (${serverTimestamp}) vs local=${localTime}s (${localTimestamp}) — pulling');
+ await saveLocal(
+ itemId: itemId,
+ currentTime: serverTime,
+ duration: localDuration,
+ speed: (data['speed'] as num?)?.toDouble() ?? 1.0,
+ );
+ final updated = await ScopedPrefs.getStringList('pending_syncs');
+ updated.remove(itemId);
+ await ScopedPrefs.setStringList('pending_syncs', updated);
+ continue;
+ }
+ debugPrint('[Sync] Local is newer for $itemId: local=${localTime}s (${localTimestamp}) vs server=${serverTime}s (${serverTimestamp}) — pushing');
+ }
+
+ final session = await api.startPlaybackSession(itemId);
+ if (session != null) {
+ final sessionId = session['id'] as String?;
+ if (sessionId != null) {
+ await api.syncPlaybackSession(
+ sessionId,
+ currentTime: localTime,
+ duration: localDuration,
+ );
+ await api.closePlaybackSession(sessionId);
+ debugPrint('[Sync] Flushed $itemId via session: ${localTime}s');
+ }
+ }
+
+ final updated = await ScopedPrefs.getStringList('pending_syncs');
+ updated.remove(itemId);
+ await ScopedPrefs.setStringList('pending_syncs', updated);
+ } catch (e) {
+ debugPrint('[Sync] Flush failed for $itemId: $e');
+ }
+ }
+ }
+
+ void dispose() {
+ _connectivitySub?.cancel();
+ }
+}
diff --git a/lib/services/scoped_prefs.dart b/lib/services/scoped_prefs.dart
new file mode 100644
index 00000000..b98282b0
--- /dev/null
+++ b/lib/services/scoped_prefs.dart
@@ -0,0 +1,102 @@
+import 'package:shared_preferences/shared_preferences.dart';
+import 'user_account_service.dart';
+
+/// Wrapper around SharedPreferences that automatically scopes keys
+/// to the active user account. Use this for any data that should be
+/// per-user (progress, absorbing lists, playback history, etc.).
+///
+/// For data that should be GLOBAL (downloads, device ID, EQ settings),
+/// use SharedPreferences directly.
+class ScopedPrefs {
+ ScopedPrefs._();
+
+ static String _scope(String key) => UserAccountService().scopedKey(key);
+
+ // ── String ──
+
+ static Future<String?> getString(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ // Try scoped key first, fall back to un-scoped (migration)
+ final scoped = prefs.getString(_scope(key));
+ if (scoped != null) return scoped;
+ // Fallback: if no scoped value but un-scoped exists, return it
+ // (this handles pre-multi-user data transparently)
+ return prefs.getString(key);
+ }
+
+ static Future<void> setString(String key, String value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString(_scope(key), value);
+ }
+
+ static Future<void> remove(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove(_scope(key));
+ }
+
+ // ── StringList ──
+
+ static Future<List<String>> getStringList(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ final scoped = prefs.getStringList(_scope(key));
+ if (scoped != null) return scoped;
+ return prefs.getStringList(key) ?? [];
+ }
+
+ static Future<void> setStringList(String key, List<String> value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setStringList(_scope(key), value);
+ }
+
+ // ── Bool ──
+
+ static Future<bool?> getBool(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ final scoped = _scope(key);
+ if (prefs.containsKey(scoped)) return prefs.getBool(scoped);
+ if (prefs.containsKey(key)) return prefs.getBool(key);
+ return null;
+ }
+
+ static Future<void> setBool(String key, bool value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_scope(key), value);
+ }
+
+ // ── Double ──
+
+ static Future<double?> getDouble(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ final scoped = _scope(key);
+ if (prefs.containsKey(scoped)) return prefs.getDouble(scoped);
+ if (prefs.containsKey(key)) return prefs.getDouble(key);
+ return null;
+ }
+
+ static Future<void> setDouble(String key, double value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setDouble(_scope(key), value);
+ }
+
+ // ── Int ──
+
+ static Future<int?> getInt(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ final scoped = _scope(key);
+ if (prefs.containsKey(scoped)) return prefs.getInt(scoped);
+ if (prefs.containsKey(key)) return prefs.getInt(key);
+ return null;
+ }
+
+ static Future<void> setInt(String key, int value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setInt(_scope(key), value);
+ }
+
+ // ── Convenience ──
+
+ static Future<bool> containsKey(String key) async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.containsKey(_scope(key)) || prefs.containsKey(key);
+ }
+}
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
new file mode 100644
index 00000000..46fa3b2d
--- /dev/null
+++ b/lib/services/sleep_timer_service.dart
@@ -0,0 +1,461 @@
+import 'dart:async';
+import 'dart:math';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:sensors_plus/sensors_plus.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'audio_player_service.dart';
+
+enum SleepTimerMode { off, time, chapters }
+
+/// Auto sleep timer settings — automatically start a sleep timer within a time window.
+class AutoSleepSettings {
+ final bool enabled;
+ final int startHour; // 24h format, e.g. 22 for 10 PM
+ final int startMinute;
+ final int endHour; // 24h format, e.g. 6 for 6 AM
+ final int endMinute;
+ final int durationMinutes; // how many minutes the auto-started timer runs
+
+ const AutoSleepSettings({
+ this.enabled = false,
+ this.startHour = 22,
+ this.startMinute = 0,
+ this.endHour = 6,
+ this.endMinute = 0,
+ this.durationMinutes = 30,
+ });
+
+ /// Check if the current time is within the auto sleep window.
+ bool isInWindow() {
+ final now = DateTime.now();
+ final nowMinutes = now.hour * 60 + now.minute;
+ final startMinutes = startHour * 60 + startMinute;
+ final endMinutes = endHour * 60 + endMinute;
+
+ if (startMinutes <= endMinutes) {
+ // Same-day window (e.g. 14:00 – 18:00)
+ return nowMinutes >= startMinutes && nowMinutes < endMinutes;
+ } else {
+ // Overnight window (e.g. 22:00 – 06:00)
+ return nowMinutes >= startMinutes || nowMinutes < endMinutes;
+ }
+ }
+
+ String get startLabel => _formatTime(startHour, startMinute);
+ String get endLabel => _formatTime(endHour, endMinute);
+
+ static String _formatTime(int h, int m) {
+ final period = h >= 12 ? 'PM' : 'AM';
+ final h12 = h == 0 ? 12 : (h > 12 ? h - 12 : h);
+ return '$h12:${m.toString().padLeft(2, '0')} $period';
+ }
+
+ static Future<AutoSleepSettings> load() async {
+ final prefs = await SharedPreferences.getInstance();
+ return AutoSleepSettings(
+ enabled: prefs.getBool('autoSleep_enabled') ?? false,
+ startHour: prefs.getInt('autoSleep_startHour') ?? 22,
+ startMinute: prefs.getInt('autoSleep_startMinute') ?? 0,
+ endHour: prefs.getInt('autoSleep_endHour') ?? 6,
+ endMinute: prefs.getInt('autoSleep_endMinute') ?? 0,
+ durationMinutes: prefs.getInt('autoSleep_duration') ?? 30,
+ );
+ }
+
+ Future<void> save() async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('autoSleep_enabled', enabled);
+ await prefs.setInt('autoSleep_startHour', startHour);
+ await prefs.setInt('autoSleep_startMinute', startMinute);
+ await prefs.setInt('autoSleep_endHour', endHour);
+ await prefs.setInt('autoSleep_endMinute', endMinute);
+ await prefs.setInt('autoSleep_duration', durationMinutes);
+ }
+}
+
+class SleepTimerService extends ChangeNotifier {
+ // Singleton
+ static final SleepTimerService _instance = SleepTimerService._();
+ factory SleepTimerService() => _instance;
+ SleepTimerService._();
+
+ final _player = AudioPlayerService();
+
+ // ── State ──
+ SleepTimerMode _mode = SleepTimerMode.off;
+
+ // Time mode
+ Duration _timeRemaining = Duration.zero;
+ Duration _initialDuration = Duration.zero;
+ Timer? _timer;
+
+ // Chapter mode
+ int _chaptersRemaining = 0;
+ int _targetChapterIndex = -1; // chapter index where we stop
+ StreamSubscription? _positionSub;
+
+ // Shake detection
+ bool _shakeEnabled = true;
+ StreamSubscription? _accelSub;
+ DateTime _lastShake = DateTime(2000);
+ static const _shakeThreshold = 25.0; // m/s² — raised from 15 to require a deliberate shake
+ static const _shakeCooldown = Duration(seconds: 3);
+
+ // Wind-down warning
+ bool _warningSent = false;
+ static const _warningThreshold = Duration(seconds: 30);
+
+ // Reset on pause/play
+ bool _wasPlaying = false; // tracks play state transitions
+
+ // ── Getters ──
+ SleepTimerMode get mode => _mode;
+ Duration get timeRemaining => _timeRemaining;
+ Duration get initialDuration => _initialDuration;
+ double get timeProgress => _initialDuration.inSeconds > 0
+ ? (_timeRemaining.inSeconds / _initialDuration.inSeconds).clamp(0.0, 1.0)
+ : 0.0;
+ int get chaptersRemaining => _chaptersRemaining;
+ bool get isActive => _mode != SleepTimerMode.off;
+ bool get shakeEnabled => _shakeEnabled;
+
+ String get displayLabel {
+ if (_mode == SleepTimerMode.time) {
+ final totalMins = _timeRemaining.inMinutes;
+ if (totalMins > 0) return '${totalMins}m';
+ return '<1m';
+ } else if (_mode == SleepTimerMode.chapters) {
+ return '$_chaptersRemaining ch';
+ }
+ return '';
+ }
+
+ // ── Time-based sleep ──
+
+ void setTimeSleep(Duration duration) {
+ cancel();
+ _mode = SleepTimerMode.time;
+ _timeRemaining = duration;
+ _initialDuration = duration;
+ _warningSent = false;
+ _startTimeCountdown();
+ _startShakeDetection();
+ notifyListeners();
+ debugPrint('[SleepTimer] Set time sleep: ${duration.inMinutes}m');
+ }
+
+ void _startTimeCountdown() {
+ _timer?.cancel();
+ _wasPlaying = _player.isPlaying;
+ _timer = Timer.periodic(const Duration(seconds: 1), (_) async {
+ if (_timeRemaining.inSeconds <= 0) {
+ _triggerSleep();
+ return;
+ }
+ final isPlaying = _player.isPlaying;
+
+ // Detect pause→play transition and reset if setting is on
+ if (isPlaying && !_wasPlaying) {
+ final resetOnPause = await PlayerSettings.getResetSleepOnPause();
+ if (resetOnPause) {
+ _timeRemaining = _initialDuration;
+ _warningSent = false;
+ debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');
+ onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');
+ }
+ }
+ _wasPlaying = isPlaying;
+
+ // Only count down when playing
+ if (isPlaying) {
+ _timeRemaining -= const Duration(seconds: 1);
+
+ // Wind-down warning vibration at 30 seconds
+ if (!_warningSent && _timeRemaining <= _warningThreshold && _timeRemaining.inSeconds > 0) {
+ _warningSent = true;
+ _vibrateWarning();
+ onToast?.call('Sleep timer ending soon…');
+ debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining');
+ }
+
+ notifyListeners();
+ }
+ });
+ }
+
+ /// Add time (used by shake reset in time mode, or manual add)
+ void addTime(Duration extra) {
+ if (_mode != SleepTimerMode.time) return;
+ _timeRemaining += extra;
+ // Reset warning if we're above threshold again
+ if (_timeRemaining > _warningThreshold) {
+ _warningSent = false;
+ }
+ notifyListeners();
+ debugPrint('[SleepTimer] Added ${extra.inMinutes}m — now ${_timeRemaining.inMinutes}m');
+ }
+
+ // ── Chapter-based sleep ──
+
+ void setChapterSleep(int numChapters) {
+ cancel();
+ _mode = SleepTimerMode.chapters;
+ _chaptersRemaining = numChapters;
+
+ // Calculate the target chapter index
+ final currentIdx = _getCurrentChapterIndex();
+ if (currentIdx >= 0) {
+ _targetChapterIndex = currentIdx + numChapters;
+ debugPrint('[SleepTimer] Set chapter sleep: $numChapters chapters '
+ '(current=$currentIdx, target=$_targetChapterIndex)');
+ } else {
+ _targetChapterIndex = -1;
+ debugPrint('[SleepTimer] Set chapter sleep: $numChapters chapters (no current chapter)');
+ }
+
+ _startChapterMonitor();
+ _startShakeDetection();
+ notifyListeners();
+ }
+
+ void _startChapterMonitor() {
+ _positionSub?.cancel();
+ _positionSub = _player.positionStream.listen((pos) {
+ if (!_player.isPlaying) return;
+
+ final currentIdx = _getCurrentChapterIndex();
+ if (currentIdx < 0) return;
+
+ // Update chapters remaining
+ if (_targetChapterIndex >= 0) {
+ _chaptersRemaining = (_targetChapterIndex - currentIdx).clamp(0, 999);
+ notifyListeners();
+
+ // Check if we've reached the end of the target chapter
+ if (currentIdx >= _targetChapterIndex) {
+ _triggerSleep();
+ }
+ }
+ });
+ }
+
+ /// Add a chapter (used by shake reset in chapter mode, or manual add)
+ void addChapter() {
+ if (_mode != SleepTimerMode.chapters) return;
+ _chaptersRemaining++;
+ _targetChapterIndex++;
+ notifyListeners();
+ debugPrint('[SleepTimer] Added 1 chapter — now $_chaptersRemaining remaining');
+ }
+
+ // ── Common ──
+
+ int _getCurrentChapterIndex() {
+ final chapters = _player.chapters;
+ if (chapters.isEmpty) return -1;
+ final pos = _player.position.inMilliseconds / 1000.0;
+ for (int i = 0; i < chapters.length; i++) {
+ final ch = chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ if (pos >= start && pos < end) return i;
+ }
+ return -1;
+ }
+
+ void _triggerSleep() {
+ debugPrint('[SleepTimer] Triggering sleep — pausing playback');
+ _vibrateSleep();
+ _player.pause();
+ cancel();
+ }
+
+ void cancel() {
+ _timer?.cancel();
+ _timer = null;
+ _positionSub?.cancel();
+ _positionSub = null;
+ _accelSub?.cancel();
+ _accelSub = null;
+ _mode = SleepTimerMode.off;
+ _timeRemaining = Duration.zero;
+ _chaptersRemaining = 0;
+ _targetChapterIndex = -1;
+ _warningSent = false;
+ notifyListeners();
+ debugPrint('[SleepTimer] Cancelled');
+ }
+
+ // ── Haptic feedback ──
+
+ /// Medium buzz when shake-snooze adds time
+ void _vibrateSnooze() {
+ HapticFeedback.mediumImpact();
+ }
+
+ /// Double heavy buzz when timer is almost done (30s left)
+ void _vibrateWarning() {
+ HapticFeedback.heavyImpact();
+ Future.delayed(const Duration(milliseconds: 200), () {
+ HapticFeedback.heavyImpact();
+ });
+ }
+
+ /// Triple heavy buzz when sleep actually triggers
+ void _vibrateSleep() {
+ HapticFeedback.heavyImpact();
+ Future.delayed(const Duration(milliseconds: 150), () {
+ HapticFeedback.heavyImpact();
+ });
+ Future.delayed(const Duration(milliseconds: 300), () {
+ HapticFeedback.heavyImpact();
+ });
+ }
+
+ // ── Shake detection ──
+
+ Future<void> _startShakeDetection() async {
+ _shakeEnabled = await PlayerSettings.getShakeToResetSleep();
+ if (!_shakeEnabled) return;
+
+ _accelSub?.cancel();
+ _accelSub = accelerometerEventStream().listen((event) {
+ final magnitude = sqrt(
+ event.x * event.x + event.y * event.y + event.z * event.z);
+ // Subtract gravity (~9.8) and check threshold
+ if (magnitude > _shakeThreshold) {
+ final now = DateTime.now();
+ if (now.difference(_lastShake) > _shakeCooldown) {
+ _lastShake = now;
+ _onShake();
+ }
+ }
+ });
+ }
+
+ // Toast callback — UI sets this to show snackbars
+ void Function(String message)? onToast;
+
+ // ── Auto Sleep Timer ──
+ AutoSleepSettings? _autoSleepSettings;
+ bool _autoSleepDismissed = false; // user manually cancelled — don't re-trigger this window
+ bool _wasInWindow = false; // tracks window transitions to reset dismiss flag
+ Timer? _windowBoundaryTimer; // fires once at exact window start time
+
+ /// Load auto sleep settings.
+ Future<void> loadAutoSleepSettings() async {
+ _autoSleepSettings = await AutoSleepSettings.load();
+ _onSettingsUpdated();
+ }
+
+ /// Directly update settings (avoids save/load race condition).
+ void updateAutoSleepSettings(AutoSleepSettings settings) {
+ _autoSleepSettings = settings;
+ _onSettingsUpdated();
+ }
+
+ void _onSettingsUpdated() {
+ // Cancel stale boundary timer — it was for the old window
+ _windowBoundaryTimer?.cancel();
+ _windowBoundaryTimer = null;
+ // Re-evaluate with new settings if playing, or schedule boundary
+ if (_autoSleepSettings != null && _autoSleepSettings!.enabled) {
+ checkAutoSleep();
+ }
+ }
+
+ AutoSleepSettings? get autoSleepSettings => _autoSleepSettings;
+
+ /// Cancel the sleep timer because the user chose to.
+ /// Suppresses auto sleep re-triggering until the window resets.
+ void cancelByUser() {
+ debugPrint('[SleepTimer] Cancelled by user — suppressing auto sleep for this window');
+ _autoSleepDismissed = true;
+ _windowBoundaryTimer?.cancel();
+ _windowBoundaryTimer = null;
+ cancel();
+ }
+
+ /// Reset the dismiss flag — call when starting a new book or resetting playback.
+ /// This lets auto sleep re-trigger even if the user cancelled it earlier.
+ void resetDismiss() {
+ _autoSleepDismissed = false;
+ }
+
+ /// Called on playback start, resume, and app foreground.
+ Future<void> checkAutoSleep() async {
+ if (_autoSleepSettings == null) await loadAutoSleepSettings();
+ final settings = _autoSleepSettings;
+ if (settings == null || !settings.enabled) return;
+
+ final inWindow = settings.isInWindow();
+
+ // If we just left the window, reset the dismiss flag for next entry
+ if (!inWindow && _wasInWindow) {
+ _autoSleepDismissed = false;
+ }
+ _wasInWindow = inWindow;
+
+ if (inWindow) {
+ // We're in the window — try to activate
+ _windowBoundaryTimer?.cancel();
+ _windowBoundaryTimer = null;
+ if (!isActive && !_autoSleepDismissed) {
+ debugPrint('[SleepTimer] Auto sleep: in window ${settings.startLabel}–${settings.endLabel}, '
+ 'starting ${settings.durationMinutes}m timer');
+ setTimeSleep(Duration(minutes: settings.durationMinutes));
+ onToast?.call('Auto sleep: ${settings.durationMinutes}m timer started');
+ }
+ } else {
+ // Not in window yet — schedule a one-shot timer for when it opens
+ _scheduleWindowBoundary(settings);
+ }
+ }
+
+ /// Schedule a single timer that fires when the window starts.
+ /// If playback is still going at that moment, starts the sleep timer.
+ void _scheduleWindowBoundary(AutoSleepSettings settings) {
+ _windowBoundaryTimer?.cancel();
+
+ final now = DateTime.now();
+ final todayStart = DateTime(now.year, now.month, now.day, settings.startHour, settings.startMinute);
+ final nextStart = todayStart.isAfter(now) ? todayStart : todayStart.add(const Duration(days: 1));
+ final delay = nextStart.difference(now);
+
+ debugPrint('[SleepTimer] Window boundary timer set for ${delay.inMinutes}m from now');
+ _windowBoundaryTimer = Timer(delay, () {
+ _windowBoundaryTimer = null;
+ if (_player.isPlaying && !isActive && !_autoSleepDismissed) {
+ _wasInWindow = true;
+ debugPrint('[SleepTimer] Window boundary hit — starting ${settings.durationMinutes}m timer');
+ setTimeSleep(Duration(minutes: settings.durationMinutes));
+ onToast?.call('Auto sleep: ${settings.durationMinutes}m timer started');
+ }
+ });
+ }
+
+ void _onShake() async {
+ if (!isActive) return;
+ debugPrint('[SleepTimer] Shake detected!');
+
+ _vibrateSnooze();
+
+ if (_mode == SleepTimerMode.time) {
+ final addMins = await PlayerSettings.getShakeAddMinutes();
+ addTime(Duration(minutes: addMins));
+ onToast?.call('+$addMins min added!');
+ } else if (_mode == SleepTimerMode.chapters) {
+ addChapter();
+ onToast?.call('+1 chapter added!');
+ }
+ }
+
+ @override
+ void dispose() {
+ cancel();
+ _windowBoundaryTimer?.cancel();
+ _windowBoundaryTimer = null;
+ super.dispose();
+ }
+}
diff --git a/lib/services/update_checker_service.dart b/lib/services/update_checker_service.dart
new file mode 100644
index 00000000..4a814ac3
--- /dev/null
+++ b/lib/services/update_checker_service.dart
@@ -0,0 +1,108 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:http/http.dart' as http;
+import 'package:package_info_plus/package_info_plus.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+class UpdateInfo {
+ final String latestVersion;
+ final String currentVersion;
+ final String downloadUrl;
+ final String releaseNotes;
+
+ UpdateInfo({
+ required this.latestVersion,
+ required this.currentVersion,
+ required this.downloadUrl,
+ this.releaseNotes = '',
+ });
+
+ bool get hasUpdate => _compareVersions(latestVersion, currentVersion) > 0;
+}
+
+/// Compare semver strings. Returns positive if a > b, negative if a < b, 0 if equal.
+int _compareVersions(String a, String b) {
+ final aParts = a.replaceAll(RegExp(r'^v'), '').split('.').map((s) => int.tryParse(s) ?? 0).toList();
+ final bParts = b.replaceAll(RegExp(r'^v'), '').split('.').map((s) => int.tryParse(s) ?? 0).toList();
+ for (int i = 0; i < 3; i++) {
+ final av = i < aParts.length ? aParts[i] : 0;
+ final bv = i < bParts.length ? bParts[i] : 0;
+ if (av != bv) return av - bv;
+ }
+ return 0;
+}
+
+class UpdateCheckerService {
+ static const _repo = 'pounat/absorb'; // Update this to your repo
+ static const _checkInterval = Duration(hours: 12);
+ static const _dismissedKey = 'update_dismissed_version';
+ static const _lastCheckKey = 'update_last_check';
+
+ /// Check for updates. Returns UpdateInfo if a newer version exists, null otherwise.
+ /// Respects a 12-hour cooldown between checks and skips dismissed versions.
+ static Future<UpdateInfo?> check({bool force = false}) async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+
+ // Cooldown check (skip if forced)
+ if (!force) {
+ final lastCheck = prefs.getInt(_lastCheckKey) ?? 0;
+ final elapsed = DateTime.now().millisecondsSinceEpoch - lastCheck;
+ if (elapsed < _checkInterval.inMilliseconds) return null;
+ }
+
+ await prefs.setInt(_lastCheckKey, DateTime.now().millisecondsSinceEpoch);
+
+ final response = await http.get(
+ Uri.parse('https://api.github.com/repos/$_repo/releases/latest'),
+ headers: {'Accept': 'application/vnd.github.v3+json'},
+ ).timeout(const Duration(seconds: 10));
+
+ if (response.statusCode != 200) return null;
+
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final tagName = data['tag_name'] as String? ?? '';
+ final body = data['body'] as String? ?? '';
+ final assets = data['assets'] as List<dynamic>? ?? [];
+
+ // Find APK asset
+ String downloadUrl = data['html_url'] as String? ?? '';
+ for (final asset in assets) {
+ final name = (asset['name'] as String? ?? '').toLowerCase();
+ if (name.endsWith('.apk')) {
+ downloadUrl = asset['browser_download_url'] as String? ?? downloadUrl;
+ break;
+ }
+ }
+
+ final packageInfo = await PackageInfo.fromPlatform();
+ final currentVersion = packageInfo.version;
+
+ final info = UpdateInfo(
+ latestVersion: tagName,
+ currentVersion: currentVersion,
+ downloadUrl: downloadUrl,
+ releaseNotes: body,
+ );
+
+ if (!info.hasUpdate) return null;
+
+ // Check if user dismissed this version
+ if (!force) {
+ final dismissed = prefs.getString(_dismissedKey);
+ if (dismissed == tagName) return null;
+ }
+
+ return info;
+ } catch (e) {
+ debugPrint('[UpdateChecker] Error: $e');
+ return null;
+ }
+ }
+
+ /// Dismiss the update prompt for a specific version.
+ static Future<void> dismiss(String version) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString(_dismissedKey, version);
+ }
+}
diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dart
new file mode 100644
index 00000000..31fe6a5e
--- /dev/null
+++ b/lib/services/user_account_service.dart
@@ -0,0 +1,178 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+/// Represents a saved user account (server + credentials).
+class SavedAccount {
+ final String serverUrl;
+ final String username;
+ final String token;
+ final String? userId;
+
+ SavedAccount({
+ required this.serverUrl,
+ required this.username,
+ required this.token,
+ this.userId,
+ });
+
+ /// Unique key for scoping per-user SharedPreferences data.
+ /// Uses serverUrl + username to uniquely identify an account.
+ String get scopeKey {
+ // Normalize: strip protocol and trailing slashes for consistency
+ final cleanUrl = serverUrl
+ .replaceAll(RegExp(r'^https?://'), '')
+ .replaceAll(RegExp(r'/+$'), '');
+ return '${cleanUrl}_$username';
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'serverUrl': serverUrl,
+ 'username': username,
+ 'token': token,
+ 'userId': userId,
+ };
+
+ factory SavedAccount.fromJson(Map<String, dynamic> json) => SavedAccount(
+ serverUrl: json['serverUrl'] as String,
+ username: json['username'] as String,
+ token: json['token'] as String,
+ userId: json['userId'] as String?,
+ );
+
+ @override
+ bool operator ==(Object other) =>
+ other is SavedAccount &&
+ other.serverUrl == serverUrl &&
+ other.username == username;
+
+ @override
+ int get hashCode => Object.hash(serverUrl, username);
+}
+
+/// Manages multiple saved user accounts and provides scoped storage keys.
+///
+/// Downloads (audio files on disk) are shared across all users — there's no
+/// point re-downloading the same audiobook for a different user on the same
+/// device. But progress, absorbing lists, playback history, bookmarks, and
+/// metadata overrides are all scoped per-user.
+class UserAccountService {
+ static final UserAccountService _instance = UserAccountService._();
+ factory UserAccountService() => _instance;
+ UserAccountService._();
+
+ static const _accountsKey = 'saved_accounts';
+ static const _activeKey = 'active_account_scope';
+
+ List<SavedAccount> _accounts = [];
+ String? _activeScopeKey;
+
+ List<SavedAccount> get accounts => List.unmodifiable(_accounts);
+ String get activeScopeKey => _activeScopeKey ?? '';
+
+ /// Initialise from SharedPreferences. Call once at app startup.
+ Future<void> init() async {
+ final prefs = await SharedPreferences.getInstance();
+
+ // Load saved accounts
+ final json = prefs.getString(_accountsKey);
+ if (json != null) {
+ try {
+ final list = jsonDecode(json) as List<dynamic>;
+ _accounts = list
+ .map((e) => SavedAccount.fromJson(e as Map<String, dynamic>))
+ .toList();
+ } catch (e) {
+ debugPrint('[UserAccount] Failed to load accounts: $e');
+ }
+ }
+
+ // Load active scope
+ _activeScopeKey = prefs.getString(_activeKey);
+ debugPrint('[UserAccount] Loaded ${_accounts.length} accounts, active=$_activeScopeKey');
+ }
+
+ /// Save or update an account after login. Sets it as active.
+ Future<void> saveAccount(SavedAccount account) async {
+ // Remove existing entry for same server+username (update token)
+ _accounts.removeWhere(
+ (a) => a.serverUrl == account.serverUrl && a.username == account.username);
+ _accounts.insert(0, account); // Most recent first
+ _activeScopeKey = account.scopeKey;
+ await _persist();
+ debugPrint('[UserAccount] Saved & activated: ${account.username}@${account.serverUrl}');
+ }
+
+ /// Switch to a different saved account. Returns the account or null if not found.
+ SavedAccount? switchTo(String serverUrl, String username) {
+ final account = _accounts.firstWhere(
+ (a) => a.serverUrl == serverUrl && a.username == username,
+ orElse: () => SavedAccount(serverUrl: '', username: '', token: ''),
+ );
+ if (account.token.isEmpty) return null;
+ _activeScopeKey = account.scopeKey;
+ _persistActiveKey();
+ debugPrint('[UserAccount] Switched to: ${account.username}@${account.serverUrl}');
+ return account;
+ }
+
+ /// Remove a saved account. Does NOT delete its scoped data (in case the
+ /// user wants to re-add later). Returns true if found and removed.
+ Future<bool> removeAccount(String serverUrl, String username) async {
+ final before = _accounts.length;
+ _accounts.removeWhere(
+ (a) => a.serverUrl == serverUrl && a.username == username);
+ if (_accounts.length < before) {
+ await _persist();
+ debugPrint('[UserAccount] Removed: $username@$serverUrl');
+ return true;
+ }
+ return false;
+ }
+
+ /// Update the token for the active account (e.g. after token refresh).
+ Future<void> updateToken(String serverUrl, String username, String newToken) async {
+ final idx = _accounts.indexWhere(
+ (a) => a.serverUrl == serverUrl && a.username == username);
+ if (idx >= 0) {
+ final old = _accounts[idx];
+ _accounts[idx] = SavedAccount(
+ serverUrl: old.serverUrl,
+ username: old.username,
+ token: newToken,
+ userId: old.userId,
+ );
+ await _persist();
+ }
+ }
+
+ // ── Scoped key helpers ──────────────────────────────────
+
+ /// Returns a SharedPreferences key scoped to the active user.
+ /// Example: `scopedKey('progress_li_123')` → `abs.example.com_nathan:progress_li_123`
+ String scopedKey(String key) {
+ if (_activeScopeKey == null || _activeScopeKey!.isEmpty) return key;
+ return '$_activeScopeKey:$key';
+ }
+
+ /// Check if we have a scope (i.e. at least one login has occurred).
+ bool get hasScope => _activeScopeKey != null && _activeScopeKey!.isNotEmpty;
+
+ // ── Persistence ─────────────────────────────────────────
+
+ Future<void> _persist() async {
+ final prefs = await SharedPreferences.getInstance();
+ final json = jsonEncode(_accounts.map((a) => a.toJson()).toList());
+ await prefs.setString(_accountsKey, json);
+ if (_activeScopeKey != null) {
+ await prefs.setString(_activeKey, _activeScopeKey!);
+ }
+ }
+
+ Future<void> _persistActiveKey() async {
+ final prefs = await SharedPreferences.getInstance();
+ if (_activeScopeKey != null) {
+ await prefs.setString(_activeKey, _activeScopeKey!);
+ }
+ }
+}
diff --git a/lib/widgets/absorb_page_header.dart b/lib/widgets/absorb_page_header.dart
new file mode 100644
index 00000000..93db52a1
--- /dev/null
+++ b/lib/widgets/absorb_page_header.dart
@@ -0,0 +1,66 @@
+import 'package:flutter/material.dart';
+
+/// Consistent page header used across all screens.
+///
+/// Shows the ABSORB branding + page title, left-aligned, with optional
+/// trailing actions. Designed to be placed inside scrollable content
+/// (CustomScrollView slivers, ListView children, etc.) so it scrolls
+/// away with the page.
+class AbsorbPageHeader extends StatelessWidget {
+ final String title;
+ final Color? brandingColor;
+ final Color? titleColor;
+ final List<Widget>? actions;
+ final EdgeInsetsGeometry padding;
+
+ const AbsorbPageHeader({
+ super.key,
+ required this.title,
+ this.brandingColor,
+ this.titleColor,
+ this.actions,
+ this.padding = const EdgeInsets.fromLTRB(20, 12, 20, 0),
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final cs = Theme.of(context).colorScheme;
+ final bColor = brandingColor ?? cs.onSurface.withValues(alpha: 0.3);
+ final tColor = titleColor ?? cs.onSurface;
+
+ return Padding(
+ padding: padding,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Branding row — ABSORB + optional actions
+ Row(
+ children: [
+ Text(
+ 'A B S O R B',
+ style: tt.labelSmall?.copyWith(
+ color: bColor,
+ letterSpacing: 4,
+ fontWeight: FontWeight.w300,
+ ),
+ ),
+ const Spacer(),
+ if (actions != null) ...actions!,
+ ],
+ ),
+ const SizedBox(height: 4),
+ // Page title
+ Text(
+ title,
+ style: tt.headlineMedium?.copyWith(
+ fontWeight: FontWeight.w700,
+ color: tColor,
+ letterSpacing: -0.5,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/absorb_slider.dart b/lib/widgets/absorb_slider.dart
new file mode 100644
index 00000000..485e7661
--- /dev/null
+++ b/lib/widgets/absorb_slider.dart
@@ -0,0 +1,488 @@
+import 'package:flutter/material.dart';
+
+/// Absorb-style slider matching design style 4:
+/// - Rounded track with subtle background
+/// - Tall vertical thumb handle
+/// - Small endpoint dots
+/// - Filled active segment
+class AbsorbSlider extends StatelessWidget {
+ final double value;
+ final double min;
+ final double max;
+ final int? divisions;
+ final Color? activeColor;
+ final Color? inactiveColor;
+ final ValueChanged<double>? onChanged;
+ final ValueChanged<double>? onChangeEnd;
+ final String? label;
+
+ const AbsorbSlider({
+ super.key,
+ required this.value,
+ this.min = 0.0,
+ this.max = 1.0,
+ this.divisions,
+ this.activeColor,
+ this.inactiveColor,
+ this.onChanged,
+ this.onChangeEnd,
+ this.label,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final accent = activeColor ?? cs.primary;
+ final inactive = inactiveColor ?? accent.withValues(alpha: 0.15);
+
+ return SliderTheme(
+ data: SliderThemeData(
+ trackHeight: 8,
+ activeTrackColor: accent,
+ inactiveTrackColor: inactive,
+ thumbColor: accent,
+ overlayColor: accent.withValues(alpha: 0.12),
+ thumbShape: _AbsorbThumbShape(thumbColor: accent),
+ trackShape: _AbsorbTrackShape(),
+ tickMarkShape: SliderTickMarkShape.noTickMark,
+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 20),
+ ),
+ child: Slider(
+ value: value.clamp(min, max),
+ min: min,
+ max: max,
+ divisions: divisions,
+ label: label,
+ onChanged: onChanged,
+ onChangeEnd: onChangeEnd,
+ ),
+ );
+ }
+}
+
+/// Tall vertical thumb handle (style 4)
+class _AbsorbThumbShape extends SliderComponentShape {
+ final Color thumbColor;
+ const _AbsorbThumbShape({required this.thumbColor});
+
+ @override
+ Size getPreferredSize(bool isEnabled, bool isDiscrete) =>
+ const Size(6, 28);
+
+ @override
+ void paint(
+ PaintingContext context,
+ Offset center, {
+ required Animation<double> activationAnimation,
+ required Animation<double> enableAnimation,
+ required bool isDiscrete,
+ required TextPainter labelPainter,
+ required RenderBox parentBox,
+ required SliderThemeData sliderTheme,
+ required TextDirection textDirection,
+ required double value,
+ required double textScaleFactor,
+ required Size sizeWithOverflow,
+ }) {
+ final canvas = context.canvas;
+
+ // Tall rounded rectangle thumb
+ final rect = RRect.fromRectAndRadius(
+ Rect.fromCenter(center: center, width: 6, height: 28),
+ const Radius.circular(3),
+ );
+
+ // Shadow
+ canvas.drawRRect(
+ rect.shift(const Offset(0, 1)),
+ Paint()
+ ..color = Colors.black.withValues(alpha: 0.3)
+ ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3),
+ );
+
+ // Thumb
+ canvas.drawRRect(rect, Paint()..color = thumbColor);
+ }
+}
+
+/// Track with rounded ends and small endpoint dots
+class _AbsorbTrackShape extends SliderTrackShape {
+ @override
+ Rect getPreferredRect({
+ required RenderBox parentBox,
+ Offset offset = Offset.zero,
+ required SliderThemeData sliderTheme,
+ bool isEnabled = false,
+ bool isDiscrete = false,
+ }) {
+ final trackHeight = sliderTheme.trackHeight ?? 8;
+ final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
+ final trackLeft = offset.dx + 14; // padding for endpoint dots
+ final trackWidth = parentBox.size.width - 28;
+ return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
+ }
+
+ @override
+ void paint(
+ PaintingContext context,
+ Offset offset, {
+ required RenderBox parentBox,
+ required SliderThemeData sliderTheme,
+ required Animation<double> enableAnimation,
+ required Offset thumbCenter,
+ Offset? secondaryOffset,
+ bool isEnabled = false,
+ bool isDiscrete = false,
+ required TextDirection textDirection,
+ }) {
+ final canvas = context.canvas;
+ final trackRect = getPreferredRect(
+ parentBox: parentBox,
+ offset: offset,
+ sliderTheme: sliderTheme,
+ );
+
+ final trackHeight = trackRect.height;
+ final radius = Radius.circular(trackHeight / 2);
+
+ // Inactive track (full background)
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(trackRect, radius),
+ Paint()..color = sliderTheme.inactiveTrackColor ?? Colors.white10,
+ );
+
+ // Active track (from start to thumb)
+ final activeRect = Rect.fromLTRB(
+ trackRect.left,
+ trackRect.top,
+ thumbCenter.dx,
+ trackRect.bottom,
+ );
+ if (activeRect.width > 0) {
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(activeRect, radius),
+ Paint()..color = sliderTheme.activeTrackColor ?? Colors.blue,
+ );
+ }
+
+ // Endpoint dots
+ final dotRadius = 3.0;
+ final dotColor = sliderTheme.activeTrackColor?.withValues(alpha: 0.5) ??
+ Colors.white.withValues(alpha: 0.3);
+ final centerY = trackRect.center.dy;
+
+ // Left dot
+ canvas.drawCircle(
+ Offset(trackRect.left + dotRadius + 2, centerY),
+ dotRadius,
+ Paint()..color = Colors.white.withValues(alpha: 0.7),
+ );
+
+ // Right dot
+ canvas.drawCircle(
+ Offset(trackRect.right - dotRadius - 2, centerY),
+ dotRadius,
+ Paint()..color = dotColor,
+ );
+ }
+}
+
+/// Custom painter for the player progress bar (style 4 with optional squiggly wave)
+/// Used for the chapter scrubber and optional book progress bar
+class AbsorbProgressPainter extends CustomPainter {
+ final double progress;
+ final Color accent;
+ final bool isDragging;
+ final bool showEndDots;
+ final bool squiggly;
+ final bool isPlaying;
+ final double wavePhase;
+
+ AbsorbProgressPainter({
+ required this.progress,
+ required this.accent,
+ this.isDragging = false,
+ this.showEndDots = true,
+ this.squiggly = false,
+ this.isPlaying = false,
+ this.wavePhase = 0,
+ });
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final centerY = size.height / 2;
+ final trackHeight = 8.0;
+ final trackTop = centerY - trackHeight / 2;
+ final padding = 14.0;
+ final trackLeft = padding;
+ final trackWidth = size.width - padding * 2;
+ final trackRight = trackLeft + trackWidth;
+ final radius = Radius.circular(trackHeight / 2);
+ final progressX = trackLeft + (progress.clamp(0.0, 1.0) * trackWidth);
+
+ // Full track background
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight),
+ radius,
+ ),
+ Paint()..color = accent.withValues(alpha: 0.15),
+ );
+
+ // Active track
+ if (squiggly && (isPlaying || isDragging) && progressX > trackLeft + 10) {
+ // Subtle squiggly wave for active portion
+ final path = Path();
+ final waveAmplitude = isDragging ? 1.5 : 2.5;
+ final waveFrequency = 0.06;
+ final pi2 = 3.14159265 * 2;
+ final phaseOffset = wavePhase * pi2;
+
+ path.moveTo(trackLeft, centerY);
+ for (double x = trackLeft; x <= progressX; x += 1) {
+ final dampStart = ((x - trackLeft) / 25).clamp(0.0, 1.0);
+ final dampEnd = ((progressX - x) / 25).clamp(0.0, 1.0);
+ final damp = dampStart * dampEnd;
+ // Use a simple polynomial approximation of sin that's smooth
+ final angle = (x * waveFrequency + phaseOffset) % pi2;
+ final norm = angle / pi2; // 0..1
+ final sinApprox = _sinApprox(norm * pi2);
+ final y = centerY + sinApprox * waveAmplitude * damp;
+ path.lineTo(x, y);
+ }
+ canvas.drawPath(
+ path,
+ Paint()
+ ..color = accent
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = trackHeight * 0.65
+ ..strokeCap = StrokeCap.round,
+ );
+ } else if (progressX > trackLeft) {
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ Rect.fromLTWH(trackLeft, trackTop, progressX - trackLeft, trackHeight),
+ radius,
+ ),
+ Paint()..color = accent,
+ );
+ }
+
+ // Endpoint dots
+ if (showEndDots) {
+ canvas.drawCircle(
+ Offset(trackLeft + 5, centerY),
+ 3,
+ Paint()..color = Colors.white.withValues(alpha: 0.7),
+ );
+ canvas.drawCircle(
+ Offset(trackRight - 5, centerY),
+ 3,
+ Paint()..color = accent.withValues(alpha: 0.5),
+ );
+ }
+
+ // Thumb handle (tall rounded rect — style 4)
+ final thumbWidth = isDragging ? 7.0 : 5.0;
+ final thumbHeight = isDragging ? 32.0 : 26.0;
+ final thumbRect = RRect.fromRectAndRadius(
+ Rect.fromCenter(
+ center: Offset(progressX, centerY),
+ width: thumbWidth,
+ height: thumbHeight,
+ ),
+ Radius.circular(thumbWidth / 2),
+ );
+
+ canvas.drawRRect(
+ thumbRect.shift(const Offset(0, 1)),
+ Paint()
+ ..color = Colors.black.withValues(alpha: 0.3)
+ ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3),
+ );
+ canvas.drawRRect(thumbRect, Paint()..color = accent);
+ }
+
+ // Attempt at smooth sin without dart:math — Bhaskara I approximation
+ static double _sinApprox(double x) {
+ const pi = 3.14159265;
+ // Normalize to 0..2pi
+ var a = x % (2 * pi);
+ if (a < 0) a += 2 * pi;
+ // Map to 0..pi range, track sign
+ double sign = 1;
+ if (a > pi) {
+ a -= pi;
+ sign = -1;
+ }
+ // Bhaskara I: sin(x) ≈ 16x(π−x) / (5π²−4x(π−x))
+ final num = 16 * a * (pi - a);
+ final den = 5 * pi * pi - 4 * a * (pi - a);
+ return sign * num / den;
+ }
+
+ @override
+ bool shouldRepaint(covariant AbsorbProgressPainter old) =>
+ progress != old.progress || isDragging != old.isDragging ||
+ accent != old.accent || squiggly != old.squiggly ||
+ isPlaying != old.isPlaying || wavePhase != old.wavePhase;
+}
+
+/// Absorb-style range slider with two thumbs (min/max).
+/// Uses the same visual language as AbsorbSlider.
+class AbsorbRangeSlider extends StatelessWidget {
+ final RangeValues values;
+ final double min;
+ final double max;
+ final int? divisions;
+ final Color? activeColor;
+ final ValueChanged<RangeValues>? onChanged;
+
+ const AbsorbRangeSlider({
+ super.key,
+ required this.values,
+ this.min = 0.0,
+ this.max = 1.0,
+ this.divisions,
+ this.activeColor,
+ this.onChanged,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final accent = activeColor ?? cs.primary;
+
+ return SliderTheme(
+ data: SliderTheme.of(context).copyWith(
+ rangeTrackShape: _AbsorbRangeTrackShape(),
+ rangeThumbShape: _AbsorbRangeThumbShape(accent: accent),
+ trackHeight: 8,
+ activeTrackColor: accent,
+ inactiveTrackColor: accent.withValues(alpha: 0.15),
+ overlayColor: accent.withValues(alpha: 0.08),
+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 20),
+ ),
+ child: RangeSlider(
+ values: values,
+ min: min,
+ max: max,
+ divisions: divisions,
+ onChanged: onChanged,
+ ),
+ );
+ }
+}
+
+class _AbsorbRangeTrackShape extends RangeSliderTrackShape {
+ @override
+ Rect getPreferredRect({
+ required RenderBox parentBox,
+ Offset offset = Offset.zero,
+ required SliderThemeData sliderTheme,
+ bool isEnabled = false,
+ bool isDiscrete = false,
+ }) {
+ final trackHeight = sliderTheme.trackHeight ?? 8;
+ final trackLeft = offset.dx + 14;
+ final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
+ final trackWidth = parentBox.size.width - 28;
+ return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
+ }
+
+ @override
+ void paint(
+ PaintingContext context,
+ Offset offset, {
+ required RenderBox parentBox,
+ required SliderThemeData sliderTheme,
+ required Animation<double> enableAnimation,
+ required Offset startThumbCenter,
+ required Offset endThumbCenter,
+ bool isEnabled = false,
+ bool isDiscrete = false,
+ required TextDirection textDirection,
+ }) {
+ final canvas = context.canvas;
+ final trackRect = getPreferredRect(
+ parentBox: parentBox,
+ offset: offset,
+ sliderTheme: sliderTheme,
+ );
+ final radius = Radius.circular(trackRect.height / 2);
+ final activeColor = sliderTheme.activeTrackColor ?? Colors.blue;
+ final inactiveColor = sliderTheme.inactiveTrackColor ?? Colors.grey;
+
+ // Full background track
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(trackRect, radius),
+ Paint()..color = inactiveColor,
+ );
+
+ // Active segment between thumbs
+ final activeRect = Rect.fromLTRB(
+ startThumbCenter.dx, trackRect.top,
+ endThumbCenter.dx, trackRect.bottom,
+ );
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(activeRect, radius),
+ Paint()..color = activeColor,
+ );
+
+ // Endpoint dots
+ final centerY = trackRect.center.dy;
+ canvas.drawCircle(
+ Offset(trackRect.left + 5, centerY), 3,
+ Paint()..color = Colors.white.withValues(alpha: 0.7),
+ );
+ canvas.drawCircle(
+ Offset(trackRect.right - 5, centerY), 3,
+ Paint()..color = activeColor.withValues(alpha: 0.5),
+ );
+ }
+}
+
+class _AbsorbRangeThumbShape extends RangeSliderThumbShape {
+ final Color accent;
+
+ _AbsorbRangeThumbShape({required this.accent});
+
+ @override
+ Size getPreferredSize(bool isEnabled, bool isDiscrete) =>
+ const Size(6, 28);
+
+ @override
+ void paint(
+ PaintingContext context,
+ Offset center, {
+ required Animation<double> activationAnimation,
+ required Animation<double> enableAnimation,
+ bool isDiscrete = false,
+ bool isEnabled = false,
+ bool? isOnTop,
+ required SliderThemeData sliderTheme,
+ TextDirection? textDirection,
+ Thumb? thumb,
+ bool? isPressed,
+ }) {
+ final canvas = context.canvas;
+ final pressed = isPressed ?? false;
+ final w = pressed ? 7.0 : 5.0;
+ final h = pressed ? 32.0 : 26.0;
+
+ final thumbRect = RRect.fromRectAndRadius(
+ Rect.fromCenter(center: center, width: w, height: h),
+ Radius.circular(w / 2),
+ );
+
+ // Shadow
+ canvas.drawRRect(
+ thumbRect.shift(const Offset(0, 1)),
+ Paint()
+ ..color = Colors.black.withValues(alpha: 0.3)
+ ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3),
+ );
+ // Thumb
+ canvas.drawRRect(thumbRect, Paint()..color = accent);
+ }
+}
diff --git a/lib/widgets/absorb_title.dart b/lib/widgets/absorb_title.dart
new file mode 100644
index 00000000..9ce55cb3
--- /dev/null
+++ b/lib/widgets/absorb_title.dart
@@ -0,0 +1,19 @@
+import 'package:flutter/material.dart';
+
+class AbsorbTitle extends StatelessWidget {
+ final Color? color;
+
+ const AbsorbTitle({super.key, this.color});
+
+ @override
+ Widget build(BuildContext context) {
+ return Text(
+ 'A B S O R B',
+ style: Theme.of(context).textTheme.labelSmall?.copyWith(
+ color: color ?? Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.3),
+ letterSpacing: 4,
+ fontWeight: FontWeight.w300,
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/absorb_wave_icon.dart b/lib/widgets/absorb_wave_icon.dart
new file mode 100644
index 00000000..9ac031cd
--- /dev/null
+++ b/lib/widgets/absorb_wave_icon.dart
@@ -0,0 +1,53 @@
+import 'dart:math' as math;
+import 'package:flutter/material.dart';
+
+/// Reusable Absorb wave icon — the 5-bar ascending/descending wave pattern.
+/// Used as the app logo on the login screen, stats session icon, etc.
+/// For the animated nav bar version, see app_shell.dart's _AnimatedWaveIcon.
+class AbsorbWaveIcon extends StatelessWidget {
+ final double size;
+ final Color? color;
+
+ const AbsorbWaveIcon({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: _AbsorbWavePainter(color: c),
+ );
+ }
+}
+
+class _AbsorbWavePainter extends CustomPainter {
+ final Color color;
+
+ _AbsorbWavePainter({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 paint = Paint()
+ ..color = color
+ ..strokeWidth = size.width * 0.07
+ ..strokeCap = StrokeCap.round;
+
+ final totalWidth = size.width * 0.6;
+ final startX = (size.width - totalWidth) / 2;
+ final spacing = totalWidth / (_barCount - 1);
+ final midY = size.height / 2;
+ final maxHalf = size.height * 0.38;
+
+ for (int i = 0; i < _barCount; i++) {
+ final x = startX + spacing * i;
+ final half = maxHalf * _barHeights[i];
+ canvas.drawLine(Offset(x, midY - half), Offset(x, midY + half), paint);
+ }
+ }
+
+ @override
+ bool shouldRepaint(_AbsorbWavePainter old) => old.color != color;
+}
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
new file mode 100644
index 00000000..dfad1ea9
--- /dev/null
+++ b/lib/widgets/absorbing_card.dart
@@ -0,0 +1,993 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/download_service.dart';
+import '../services/playback_history_service.dart';
+import 'book_detail_sheet.dart';
+import 'episode_list_sheet.dart';
+import 'equalizer_sheet.dart';
+import 'card_progress_bar.dart';
+import 'card_playback_controls.dart';
+import 'card_buttons.dart';
+import 'chromecast_button.dart';
+import '../services/chromecast_service.dart';
+import '../services/progress_sync_service.dart';
+
+class AbsorbingCard extends StatefulWidget {
+ final Map<String, dynamic> item;
+ final AudioPlayerService player;
+ const AbsorbingCard({super.key, required this.item, required this.player});
+
+ @override
+ State<AbsorbingCard> createState() => AbsorbingCardState();
+}
+
+class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClientMixin {
+ ColorScheme? _coverScheme;
+ bool _isStarting = false;
+ List<dynamic>? _fetchedChapters;
+ StreamSubscription<Duration>? _chapterTrackSub;
+ int _lastChapterIdx = -1;
+ ui.Image? _blurredCover; // Precached blurred background
+
+ @override
+ bool get wantKeepAlive => true;
+
+ String get _itemId => widget.item['id'] as String? ?? '';
+ Map<String, dynamic> get _media => widget.item['media'] as Map<String, dynamic>? ?? {};
+ Map<String, dynamic> get _metadata => _media['metadata'] as Map<String, dynamic>? ?? {};
+ String get _title => _metadata['title'] as String? ?? 'Unknown';
+ String get _author => _metadata['authorName'] as String? ?? '';
+ double get _duration => (_media['duration'] as num?)?.toDouble() ?? 0;
+ List<dynamic> get _chapters {
+ // Prefer fetched chapters (from full item), fall back to inline data
+ if (_fetchedChapters != null && _fetchedChapters!.isNotEmpty) return _fetchedChapters!;
+ return _media['chapters'] as List<dynamic>? ?? [];
+ }
+ bool get _isActive {
+ if (widget.player.currentItemId != _itemId) return false;
+ // For podcast episode cards, only active if the same episode is playing
+ if (_episodeId != null && widget.player.currentEpisodeId != null) {
+ return _episodeId == widget.player.currentEpisodeId;
+ }
+ return true;
+ }
+ bool get _isPodcastEpisode => _isActive && widget.player.currentEpisodeId != null;
+
+ // For inactive podcast show cards: recentEpisode is embedded in the continue-listening entity
+ Map<String, dynamic>? get _recentEpisode => widget.item['recentEpisode'] as Map<String, dynamic>?;
+ String? get _episodeId => _recentEpisode?['id'] as String?;
+ // Use episode duration for inactive podcast show cards (show duration is aggregate/incorrect)
+ double get _effectiveDuration {
+ if (!_isActive && _recentEpisode != null) {
+ // Try top-level duration first, then audioFile.duration
+ final epDur = (_recentEpisode!['duration'] as num?)?.toDouble();
+ if (epDur != null && epDur > 0) return epDur;
+ final audioFile = _recentEpisode!['audioFile'] as Map<String, dynamic>?;
+ final afDur = (audioFile?['duration'] as num?)?.toDouble();
+ if (afDur != null && afDur > 0) return afDur;
+ }
+ return _duration;
+ }
+
+ String? get _coverUrl {
+ final lib = context.read<LibraryProvider>();
+ return lib.getCoverUrl(_itemId, width: 800);
+ }
+
+ bool get _isLocalCover => _coverUrl != null && _coverUrl!.startsWith('/');
+
+ @override
+ void initState() {
+ super.initState();
+ _fetchChaptersIfNeeded();
+ _startChapterTracking();
+ }
+
+ Future<void> _fetchChaptersIfNeeded() async {
+ // If chapters are already in the item data, skip
+ final inline = _media['chapters'] as List<dynamic>? ?? [];
+ if (inline.isNotEmpty) return;
+ // Fetch full item to get chapters
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+ try {
+ final fullItem = await api.getLibraryItem(_itemId);
+ if (fullItem != null && mounted) {
+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};
+ final chapters = media['chapters'] as List<dynamic>? ?? [];
+ if (chapters.isNotEmpty) {
+ setState(() => _fetchedChapters = chapters);
+ // If this is the active book and player has no chapters, update them
+ if (_isActive && widget.player.chapters.isEmpty) {
+ widget.player.updateChapters(chapters);
+ }
+ }
+ }
+ } catch (_) {}
+ }
+
+ void _startChapterTracking() {
+ _chapterTrackSub?.cancel();
+ _chapterTrackSub = widget.player.absolutePositionStream.listen((pos) {
+ if (!_isActive) return;
+ final posS = pos.inMilliseconds / 1000.0;
+ final chapters = widget.player.chapters.isNotEmpty ? widget.player.chapters : _chapters;
+ if (chapters.isEmpty) {
+ // No chapters (podcast episode) — rebuild every second to keep % live
+ final sec = pos.inSeconds;
+ if (sec != _lastChapterIdx) {
+ _lastChapterIdx = sec;
+ if (mounted) setState(() {});
+ }
+ return;
+ }
+ int idx = 0;
+ for (int i = 0; i < chapters.length; i++) {
+ final ch = chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ if (posS >= start && posS < end) { idx = i; break; }
+ }
+ if (idx != _lastChapterIdx) {
+ _lastChapterIdx = idx;
+ if (mounted) setState(() {});
+ }
+ });
+ }
+
+ @override
+ void didUpdateWidget(AbsorbingCard old) {
+ super.didUpdateWidget(old);
+ final oldId = old.item['id'] as String? ?? '';
+ if (oldId != _itemId) {
+ // Item changed — reset all stale state
+ _coverScheme = null;
+ _blurredCover?.dispose();
+ _blurredCover = null;
+ _fetchedChapters = null;
+ _lastChapterIdx = -1;
+ _fetchChaptersIfNeeded();
+ }
+ if (old.player != widget.player) _startChapterTracking();
+ }
+
+ @override
+ void dispose() {
+ _chapterTrackSub?.cancel();
+ _blurredCover?.dispose();
+ super.dispose();
+ }
+
+ void _onCoverLoaded(ImageProvider provider) {
+ if (_coverScheme != null) return;
+ ColorScheme.fromImageProvider(provider: provider, brightness: Brightness.dark)
+ .then((s) {
+ if (mounted) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) setState(() => _coverScheme = s);
+ });
+ }
+ })
+ .catchError((_) {});
+ // Precache the blurred version of the cover
+ if (_blurredCover == null) {
+ _precacheBlur(provider);
+ }
+ }
+
+ /// Resolve the image, render it blurred to an offscreen canvas, cache the result.
+ Future<void> _precacheBlur(ImageProvider provider) async {
+ try {
+ final completer = Completer<ui.Image>();
+ final stream = provider.resolve(ImageConfiguration.empty);
+ late ImageStreamListener listener;
+ listener = ImageStreamListener((info, _) {
+ completer.complete(info.image);
+ stream.removeListener(listener);
+ }, onError: (e, _) {
+ if (!completer.isCompleted) completer.completeError(e);
+ stream.removeListener(listener);
+ });
+ stream.addListener(listener);
+
+ final srcImage = await completer.future;
+ // Render at reduced size for performance (blur hides detail anyway)
+ const targetWidth = 200;
+ final aspect = srcImage.height / srcImage.width;
+ final targetHeight = (targetWidth * aspect).round();
+
+ final recorder = ui.PictureRecorder();
+ final canvas = Canvas(recorder, Rect.fromLTWH(0, 0, targetWidth.toDouble(), targetHeight.toDouble()));
+ final paint = Paint()
+ ..imageFilter = ui.ImageFilter.blur(sigmaX: 30, sigmaY: 30, tileMode: TileMode.decal);
+ canvas.drawImageRect(
+ srcImage,
+ Rect.fromLTWH(0, 0, srcImage.width.toDouble(), srcImage.height.toDouble()),
+ Rect.fromLTWH(0, 0, targetWidth.toDouble(), targetHeight.toDouble()),
+ paint,
+ );
+ final picture = recorder.endRecording();
+ final blurred = await picture.toImage(targetWidth, targetHeight);
+ picture.dispose();
+
+ if (mounted) {
+ setState(() => _blurredCover = blurred);
+ } else {
+ blurred.dispose();
+ }
+ } catch (_) {
+ // Fallback: card will show without blurred background, which is fine
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ super.build(context); // required for AutomaticKeepAliveClientMixin
+ final tt = Theme.of(context).textTheme;
+ final cs = _coverScheme ?? Theme.of(context).colorScheme;
+ final accent = cs.primary;
+ final bgDark = cs.surface;
+
+ final lib = context.watch<LibraryProvider>();
+ final mediaHeaders = lib.mediaHeaders;
+ // For podcast episodes, look up progress by compound key (itemId-episodeId)
+ final progress = (_episodeId != null)
+ ? lib.getEpisodeProgress(_itemId, _episodeId!)
+ : (_isPodcastEpisode
+ ? lib.getEpisodeProgress(_itemId, widget.player.currentEpisodeId!)
+ : lib.getProgress(_itemId));
+ final bool isFinished;
+ if (_episodeId != null) {
+ isFinished = lib.getEpisodeProgressData(_itemId, _episodeId!)?['isFinished'] == true;
+ } else if (_isPodcastEpisode) {
+ isFinished = lib.getEpisodeProgressData(_itemId, widget.player.currentEpisodeId!)?['isFinished'] == true;
+ } else {
+ isFinished = lib.getProgressData(_itemId)?['isFinished'] == true;
+ }
+ final chapterIdx = _currentChapterIndex();
+ final totalChapters = _isActive ? widget.player.chapters.length : _chapters.length;
+ final double bookProgress;
+ if (_isActive && widget.player.totalDuration > 0) {
+ final playerPos = widget.player.position.inMilliseconds / 1000.0;
+ // Don't use player position if it's near zero while we have real progress
+ // (means the player is still loading/seeking to resume point)
+ if (playerPos < 1.0 && progress > 0.01) {
+ bookProgress = progress; // Keep showing stored progress during load
+ } else {
+ bookProgress = (playerPos / widget.player.totalDuration).clamp(0.0, 1.0);
+ }
+ } else {
+ // For inactive cards, use stored progress (episode-level for podcast shows)
+ bookProgress = progress;
+ }
+
+ return Container(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: accent.withValues(alpha: 0.15), width: 1),
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(23),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ // Layer 1: Pre-blurred cover background (cached bitmap — no per-frame blur)
+ if (_blurredCover != null)
+ RepaintBoundary(
+ child: RawImage(
+ image: _blurredCover,
+ fit: BoxFit.cover,
+ width: double.infinity,
+ height: double.infinity,
+ ),
+ )
+ else if (_coverUrl != null)
+ // Fallback while blur is being computed: show unblurred cover dimmed
+ RepaintBoundary(
+ child: _isLocalCover
+ ? Builder(builder: (_) {
+ final provider = FileImage(File(_coverUrl!));
+ _onCoverLoaded(provider);
+ return Opacity(
+ opacity: 0.3,
+ child: Image.file(File(_coverUrl!), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => Container(color: Colors.black)),
+ );
+ })
+ : CachedNetworkImage(
+ imageUrl: _coverUrl!,
+ fit: BoxFit.cover,
+ httpHeaders: mediaHeaders,
+ imageBuilder: (_, provider) {
+ _onCoverLoaded(provider);
+ return Opacity(
+ opacity: 0.3,
+ child: Image(image: provider, fit: BoxFit.cover),
+ );
+ },
+ placeholder: (_, __) => Container(color: Colors.black),
+ errorWidget: (_, __, ___) => Container(color: Colors.black),
+ ),
+ ),
+ // Layer 2: Scrim
+ Positioned.fill(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.3),
+ Colors.black.withValues(alpha: 0.6),
+ Colors.black.withValues(alpha: 0.85),
+ ],
+ ),
+ ),
+ ),
+ ),
+ // Layer 3: Content
+ Column(
+ children: [
+ // ── Stats row ──
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 10, 24, 0),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('${(bookProgress * 100).clamp(0, 100).toStringAsFixed(1)}%',
+ style: tt.labelMedium?.copyWith(
+ color: Colors.white.withValues(alpha: 0.95),
+ fontWeight: FontWeight.w800, fontSize: 15,
+ shadows: [Shadow(color: Colors.black.withValues(alpha: 0.6), blurRadius: 4)],
+ )),
+ if (totalChapters > 0 && !_isPodcastEpisode)
+ Text('Ch ${(chapterIdx + 1).clamp(1, totalChapters)} / $totalChapters',
+ style: tt.labelMedium?.copyWith(
+ color: Colors.white.withValues(alpha: 0.85),
+ fontWeight: FontWeight.w700, fontSize: 14,
+ shadows: [Shadow(color: Colors.black.withValues(alpha: 0.6), blurRadius: 4)],
+ )),
+ ],
+ ),
+ ),
+ // ── Book progress bar ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false),
+ ),
+ const SizedBox(height: 10),
+ // ── Cover with title/author/chapter overlaid + download badge ──
+ Flexible(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: ListenableBuilder(
+ listenable: ChromecastService(),
+ builder: (context, _) => LayoutBuilder(
+ builder: (context, constraints) {
+ final coverWidth = constraints.maxWidth * 0.85;
+ // Use the smaller of desired width or available height to prevent squishing
+ final coverSize = coverWidth < constraints.maxHeight
+ ? coverWidth
+ : constraints.maxHeight;
+ final isDownloaded = DownloadService().isDownloaded(_itemId);
+ final castService = ChromecastService();
+ final isCastingThis = castService.isCasting && castService.castingItemId == _itemId;
+ return Container(
+ width: coverSize,
+ height: coverSize,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(16),
+ boxShadow: [
+ BoxShadow(color: Colors.black.withValues(alpha: 0.5), blurRadius: 20, spreadRadius: -2, offset: const Offset(0, 6)),
+ BoxShadow(color: accent.withValues(alpha: 0.15), blurRadius: 30, spreadRadius: -5),
+ ],
+ ),
+ child: RepaintBoundary(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ // Cover image
+ _coverUrl != null
+ ? _isLocalCover
+ ? Image.file(File(_coverUrl!), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _coverPlaceholder())
+ : CachedNetworkImage(imageUrl: _coverUrl!, fit: BoxFit.cover,
+ httpHeaders: mediaHeaders,
+ placeholder: (_, __) => _coverPlaceholder(),
+ errorWidget: (_, __, ___) => _coverPlaceholder())
+ : _coverPlaceholder(),
+ // Downloaded badge (top-right)
+ if (isDownloaded)
+ Positioned(
+ top: 8, right: 8,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.download_done_rounded, size: 13, color: accent.withValues(alpha: 0.9)),
+ const SizedBox(width: 4),
+ Text('Downloaded', style: TextStyle(color: accent.withValues(alpha: 0.9), fontSize: 10, fontWeight: FontWeight.w600)),
+ ],
+ ),
+ ),
+ ),
+ // Casting overlay
+ if (isCastingThis) ...[
+ Positioned.fill(
+ child: Container(
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.45),
+ borderRadius: BorderRadius.circular(16),
+ ),
+ ),
+ ),
+ Positioned.fill(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.cast_connected_rounded, size: 36, color: accent.withValues(alpha: 0.9)),
+ const SizedBox(height: 8),
+ Text('Casting to', style: TextStyle(color: Colors.white.withValues(alpha: 0.6), fontSize: 11, fontWeight: FontWeight.w500)),
+ const SizedBox(height: 2),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Text(
+ castService.connectedDeviceName ?? 'Device',
+ style: TextStyle(color: accent, fontSize: 14, fontWeight: FontWeight.w700),
+ textAlign: TextAlign.center,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ // Finished overlay
+ if (isFinished && !isCastingThis) ...[
+ Positioned.fill(
+ child: Container(
+ color: Colors.black.withValues(alpha: 0.78),
+ ),
+ ),
+ Positioned.fill(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.check_circle_rounded, size: 32, color: Colors.green.shade400),
+ const SizedBox(height: 6),
+ const Text('Finished',
+ style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w700)),
+ const SizedBox(height: 18),
+ SizedBox(
+ width: double.infinity,
+ child: GestureDetector(
+ onTap: _listenAgain,
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 9),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.18),
+ borderRadius: BorderRadius.circular(11),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.25)),
+ ),
+ child: const Text('Listen Again',
+ textAlign: TextAlign.center,
+ style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600)),
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ SizedBox(
+ width: double.infinity,
+ child: GestureDetector(
+ onTap: _removeFromAbsorbing,
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 9),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(11),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.18)),
+ ),
+ child: const Text('Remove',
+ textAlign: TextAlign.center,
+ style: TextStyle(color: Colors.white70, fontSize: 12, fontWeight: FontWeight.w500)),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 20),
+ // ── Chapter pill-scrubber (same width as book bar) ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters),
+ ),
+ // ── Controls + buttons ──
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Column(
+ children: [
+ const Spacer(flex: 2),
+ CardPlaybackControls(
+ player: widget.player,
+ accent: accent,
+ isActive: _isActive,
+ isStarting: _isStarting,
+ onStart: _startPlayback,
+ itemId: _itemId,
+ ),
+ const Spacer(flex: 3),
+ // ── Button grid (hugs bottom) ──
+ Row(children: [
+ Expanded(child: CardWideButton(
+ icon: Icons.list_rounded, label: 'Chapters',
+ accent: accent, isActive: _isActive,
+ onTap: () => _showChapters(context, accent, tt),
+ )),
+ const SizedBox(width: 8),
+ Expanded(child: CardWideButton(
+ icon: Icons.speed_rounded, label: 'Speed',
+ accent: accent, isActive: _isActive,
+ child: CardSpeedButtonInline(player: widget.player, accent: accent, isActive: _isActive),
+ )),
+ ]),
+ const SizedBox(height: 8),
+ // Secondary actions: Sleep Timer + Bookmarks
+ Row(children: [
+ Expanded(child: CardWideButton(
+ icon: Icons.bedtime_outlined, label: 'Sleep Timer',
+ accent: accent, isActive: _isActive,
+ child: CardSleepButtonInline(accent: accent, isActive: _isActive),
+ )),
+ const SizedBox(width: 8),
+ Expanded(child: CardWideButton(
+ icon: Icons.bookmark_outline_rounded, label: 'Bookmarks',
+ accent: accent, isActive: _isActive,
+ child: CardBookmarkButtonInline(
+ player: widget.player, accent: accent,
+ isActive: _isActive, itemId: _itemId,
+ ),
+ )),
+ ]),
+ const SizedBox(height: 8),
+ // More menu: Details + History (centered below buttons)
+ Center(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => _showMoreMenu(context, accent, tt),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.more_horiz_rounded, size: 18, color: Colors.white54),
+ const SizedBox(width: 4),
+ Text('More', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Colors.white54)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ int _currentChapterIndex() {
+ final chapters = _isActive ? widget.player.chapters : _chapters;
+ if (chapters.isEmpty) return -1;
+ double pos;
+ if (_isActive) {
+ pos = widget.player.position.inMilliseconds / 1000.0;
+ } else {
+ // Use stored progress to calculate position when not actively playing
+ final lib = context.read<LibraryProvider>();
+ final progress = (_episodeId != null)
+ ? lib.getEpisodeProgress(_itemId, _episodeId!)
+ : lib.getProgress(_itemId);
+ pos = progress * _effectiveDuration;
+ }
+ for (int i = 0; i < chapters.length; i++) {
+ final ch = chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ if (pos >= start && pos < end) return i;
+ }
+ // If past the last chapter end, return last chapter
+ if (pos > 0 && chapters.isNotEmpty) return chapters.length - 1;
+ return 0;
+ }
+
+ String? _chapterName(int chapterIdx) {
+ if (_isActive && widget.player.currentChapter != null) {
+ return widget.player.currentChapter!['title'] as String?;
+ }
+ if (chapterIdx >= 0 && chapterIdx < _chapters.length) {
+ final ch = _chapters[chapterIdx] as Map<String, dynamic>;
+ return ch['title'] as String?;
+ }
+ return null;
+ }
+
+ String _fmtTime(double s) {
+ if (s < 0) s = 0;
+ final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor(); final sec = (s % 60).floor();
+ if (h > 0) return '${h.toString().padLeft(2, '0')}:${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';
+ return '${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';
+ }
+
+ Widget _coverPlaceholder() => Container(
+ color: Colors.white.withValues(alpha: 0.05),
+ child: Center(child: Icon(Icons.headphones_rounded, size: 48, color: Colors.white.withValues(alpha: 0.15))),
+ );
+
+ Future<void> _startPlayback() async {
+ if (_isStarting) return;
+ // If we're casting this book, don't start local playback
+ final cast = ChromecastService();
+ if (cast.isCasting && cast.castingItemId == _itemId) return;
+ setState(() => _isStarting = true);
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) { setState(() => _isStarting = false); return; }
+ await widget.player.playItem(
+ api: api, itemId: _itemId, title: _title, author: _author,
+ coverUrl: _coverUrl, totalDuration: _effectiveDuration, chapters: _chapters,
+ episodeId: _episodeId,
+ episodeTitle: _recentEpisode?['title'] as String?,
+ );
+ if (mounted) setState(() => _isStarting = false);
+ }
+
+ Future<void> _listenAgain() async {
+ if (_isStarting) return;
+ final cast = ChromecastService();
+ if (cast.isCasting && cast.castingItemId == _itemId) return;
+ setState(() => _isStarting = true);
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) { setState(() => _isStarting = false); return; }
+ final lib = context.read<LibraryProvider>();
+ await api.resetProgress(_itemId, _duration);
+ lib.resetProgressFor(_itemId);
+ // Clear the locally saved position so playItem() doesn't override startTime
+ // back to the end of the book (where it was saved on completion)
+ await ProgressSyncService().deleteLocal(_itemId);
+ await widget.player.playItem(
+ api: api, itemId: _itemId, title: _title, author: _author,
+ coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ );
+ if (mounted) setState(() => _isStarting = false);
+ }
+
+ Future<void> _removeFromAbsorbing() async {
+ if (widget.player.currentItemId == _itemId) {
+ await widget.player.pause();
+ await widget.player.stop();
+ }
+ if (mounted) {
+ final lib = context.read<LibraryProvider>();
+ // Use compound key for podcast episodes
+ final key = _episodeId != null ? '$_itemId-$_episodeId' : _itemId;
+ await lib.removeFromAbsorbing(key);
+ }
+ }
+
+ void _showChapters(BuildContext context, Color accent, TextTheme tt) {
+ final chapters = _isActive ? widget.player.chapters : _chapters;
+ if (chapters.isEmpty) return;
+ // Get total duration for percentage calc
+ final totalDur = _isActive ? widget.player.totalDuration : _duration;
+
+ showModalBottomSheet(
+ context: context, isScrollControlled: true, useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => DraggableScrollableSheet(
+ expand: false, initialChildSize: 0.6, maxChildSize: 0.9,
+ builder: (_, sc) => Container(
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: Column(children: [
+ Padding(padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+ Text('Chapters', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const SizedBox(height: 8),
+ Expanded(child: ListView.builder(
+ controller: sc, itemCount: chapters.length,
+ itemBuilder: (_, i) {
+ final ch = chapters[i] as Map<String, dynamic>;
+ final chTitle = ch['title'] as String? ?? 'Chapter ${i + 1}';
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? 0;
+ final pos = _isActive ? widget.player.position.inMilliseconds / 1000.0 : 0.0;
+ final isCurrent = _isActive && pos >= start && pos < end;
+ // Percentage of book at end of this chapter
+ final pct = totalDur > 0 ? (end / totalDur * 100).round() : 0;
+ return ListTile(
+ dense: true, selected: isCurrent,
+ selectedTileColor: accent.withValues(alpha: 0.1),
+ leading: SizedBox(width: 28, child: Text('${i + 1}', textAlign: TextAlign.center,
+ style: tt.labelMedium?.copyWith(fontWeight: isCurrent ? FontWeight.w700 : FontWeight.w400, color: isCurrent ? accent : Colors.white38))),
+ title: Text(chTitle, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(fontWeight: isCurrent ? FontWeight.w600 : FontWeight.w400, color: isCurrent ? Colors.white : Colors.white70)),
+ trailing: Row(mainAxisSize: MainAxisSize.min, children: [
+ Text('$pct%', style: tt.labelSmall?.copyWith(
+ color: isCurrent ? accent.withValues(alpha: 0.7) : Colors.white24, fontSize: 10, fontWeight: FontWeight.w600)),
+ const SizedBox(width: 8),
+ Text(_fmtDur(end - start), style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ ]),
+ onTap: _isActive ? () {
+ widget.player.seekTo(Duration(seconds: start.round()));
+ Navigator.pop(ctx);
+ } : null,
+ );
+ },
+ )),
+ ]),
+ ),
+ ),
+ );
+ }
+
+ void _showHistory(BuildContext context, Color accent, TextTheme tt) {
+ showModalBottomSheet(
+ context: context, isScrollControlled: true, useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => DraggableScrollableSheet(
+ expand: false, initialChildSize: 0.6, maxChildSize: 0.9,
+ builder: (_, sc) => Container(
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: Column(children: [
+ Padding(padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ const Spacer(),
+ Text('Playback History', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const Spacer(),
+ IconButton(
+ icon: const Icon(Icons.delete_outline_rounded, size: 20, color: Colors.white38),
+ onPressed: () async {
+ await PlaybackHistoryService().clearHistory(_itemId);
+ Navigator.pop(ctx);
+ },
+ tooltip: 'Clear history',
+ ),
+ ]),
+ ),
+ const SizedBox(height: 8),
+ Expanded(child: FutureBuilder<List<PlaybackEvent>>(
+ future: PlaybackHistoryService().getHistory(_itemId),
+ builder: (ctx, snap) {
+ if (!snap.hasData) return const Center(child: CircularProgressIndicator(strokeWidth: 2));
+ final events = snap.data!;
+ if (events.isEmpty) return Center(child: Text('No history yet', style: tt.bodyMedium?.copyWith(color: Colors.white38)));
+ return ListView.builder(
+ controller: sc, itemCount: events.length,
+ itemBuilder: (_, i) {
+ final e = events[i]; // already newest-first from getHistory
+ final posLabel = _fmtTime(e.positionSeconds);
+ final timeAgo = _timeAgo(e.timestamp);
+ return ListTile(
+ dense: true,
+ leading: Icon(_historyIcon(e.type), size: 18, color: accent.withValues(alpha: 0.7)),
+ title: Text(e.label, style: tt.bodySmall?.copyWith(color: Colors.white70)),
+ subtitle: Text('at $posLabel', style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ trailing: Text(timeAgo, style: tt.labelSmall?.copyWith(color: Colors.white30)),
+ onTap: _isActive ? () {
+ widget.player.seekTo(Duration(seconds: e.positionSeconds.round()));
+ Navigator.pop(ctx);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(duration: const Duration(seconds: 3), content: Text('Jumped to $posLabel')));
+ } : null,
+ );
+ },
+ );
+ },
+ )),
+ ]),
+ ),
+ ),
+ );
+ }
+
+ void _showMoreMenu(BuildContext context, Color accent, TextTheme tt) {
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => Container(
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Drag handle
+ Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 16),
+ // Details option
+ MoreMenuItem(
+ icon: (_episodeId != null || _isPodcastEpisode) ? Icons.podcasts_rounded : Icons.info_outline_rounded,
+ label: (_episodeId != null || _isPodcastEpisode) ? 'Episode Details' : 'Book Details',
+ accent: accent,
+ onTap: () {
+ Navigator.pop(ctx);
+ if (_episodeId != null || _isPodcastEpisode) {
+ final episode = _recentEpisode ?? {
+ 'id': widget.player.currentEpisodeId,
+ 'title': widget.player.currentEpisodeTitle,
+ 'duration': widget.player.totalDuration,
+ };
+ EpisodeDetailSheet.show(context, widget.item, episode);
+ } else {
+ showBookDetailSheet(context, _itemId);
+ }
+ },
+ ),
+ const SizedBox(height: 6),
+ // Equalizer / Audio Enhancements
+ MoreMenuItem(
+ icon: Icons.equalizer_rounded,
+ label: 'Audio Enhancements',
+ accent: accent,
+ onTap: () { Navigator.pop(ctx); showEqualizerSheet(context, accent); },
+ ),
+ const SizedBox(height: 6),
+ // Cast to device
+ ListenableBuilder(
+ listenable: ChromecastService(),
+ builder: (_, __) {
+ final cast = ChromecastService();
+ final String castLabel;
+ if (cast.isCasting && cast.castingItemId == _itemId) {
+ castLabel = 'Casting to ${cast.connectedDeviceName ?? "device"}';
+ } else if (cast.isConnected) {
+ castLabel = 'Cast to ${cast.connectedDeviceName ?? "device"}';
+ } else {
+ castLabel = 'Cast to Device';
+ }
+ return MoreMenuItem(
+ icon: cast.isConnected ? Icons.cast_connected_rounded : Icons.cast_rounded,
+ label: castLabel,
+ accent: accent,
+ onTap: () {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ Navigator.pop(ctx);
+ if (cast.isCasting && cast.castingItemId == _itemId) {
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: const Color(0xFF1A1A1A),
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (_) => CastControlSheet(),
+ );
+ } else if (cast.isConnected) {
+ if (api != null) {
+ cast.castItem(
+ api: api, itemId: _itemId, title: _title, author: _author,
+ coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ );
+ }
+ } else {
+ showCastDevicePicker(context,
+ api: api, itemId: _itemId, title: _title, author: _author,
+ coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters);
+ }
+ },
+ );
+ },
+ ),
+ const SizedBox(height: 6),
+ // History option
+ MoreMenuItem(
+ icon: Icons.history_rounded,
+ label: 'Playback History',
+ accent: accent,
+ enabled: _isActive,
+ onTap: () { Navigator.pop(ctx); _showHistory(context, accent, tt); },
+ ),
+ const SizedBox(height: 6),
+ // Remove from Absorbing
+ MoreMenuItem(
+ icon: Icons.remove_circle_outline_rounded,
+ label: 'Remove from Absorbing',
+ accent: Colors.red.shade300,
+ onTap: () {
+ Navigator.pop(ctx);
+ _removeFromAbsorbing();
+ },
+ ),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ IconData _historyIcon(PlaybackEventType type) {
+ switch (type) {
+ case PlaybackEventType.play: return Icons.play_arrow_rounded;
+ case PlaybackEventType.pause: return Icons.pause_rounded;
+ case PlaybackEventType.seek: return Icons.swap_horiz_rounded;
+ case PlaybackEventType.syncLocal: return Icons.save_rounded;
+ case PlaybackEventType.syncServer: return Icons.cloud_done_rounded;
+ case PlaybackEventType.autoRewind: return Icons.replay_rounded;
+ case PlaybackEventType.skipForward: return Icons.forward_30_rounded;
+ case PlaybackEventType.skipBackward: return Icons.replay_10_rounded;
+ case PlaybackEventType.speedChange: return Icons.speed_rounded;
+ }
+ }
+
+ String _timeAgo(DateTime dt) {
+ final diff = DateTime.now().difference(dt);
+ if (diff.inSeconds < 60) return 'just now';
+ if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
+ if (diff.inHours < 24) return '${diff.inHours}h ago';
+ return '${diff.inDays}d ago';
+ }
+
+ String _fmtDur(double s) {
+ final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor(); final sec = (s % 60).floor();
+ if (h > 0) return '${h}h ${m}m';
+ return '${m}m ${sec}s';
+ }
+}
diff --git a/lib/widgets/absorbing_shared.dart b/lib/widgets/absorbing_shared.dart
new file mode 100644
index 00000000..c1b73f12
--- /dev/null
+++ b/lib/widgets/absorbing_shared.dart
@@ -0,0 +1,165 @@
+import 'dart:math' as math;
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../services/download_service.dart';
+
+// ─── DOWNLOAD BUTTON WITH FILL BAR (wide card style) ────────
+
+class DownloadWideButton extends StatefulWidget {
+ final String itemId;
+ final String? coverUrl;
+ final String title;
+ final String? author;
+ final Color accent;
+ const DownloadWideButton({super.key, required this.itemId, this.coverUrl, required this.title, this.author, required this.accent});
+ @override State<DownloadWideButton> createState() => _DownloadWideButtonState();
+}
+
+class _DownloadWideButtonState extends State<DownloadWideButton> {
+ final _dl = DownloadService();
+
+ @override void initState() { super.initState(); _dl.addListener(_rebuild); }
+ @override void dispose() { _dl.removeListener(_rebuild); super.dispose(); }
+ void _rebuild() { if (mounted) setState(() {}); }
+
+ @override Widget build(BuildContext context) {
+ final downloading = _dl.isDownloading(widget.itemId);
+ final downloaded = _dl.isDownloaded(widget.itemId);
+ final progress = _dl.downloadProgress(widget.itemId);
+
+ final IconData icon;
+ final String label;
+ final Color color;
+ if (downloaded) {
+ icon = Icons.download_done_rounded;
+ label = 'Saved';
+ color = Colors.greenAccent.withValues(alpha: 0.7);
+ } else if (downloading) {
+ icon = Icons.downloading_rounded;
+ label = '${(progress * 100).toStringAsFixed(0)}%';
+ color = widget.accent;
+ } else {
+ icon = Icons.download_outlined;
+ label = 'Download';
+ color = Colors.white54;
+ }
+
+ return GestureDetector(
+ onTap: () => _handleTap(context),
+ child: Container(
+ height: 36,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: downloaded ? Colors.greenAccent.withValues(alpha: 0.06) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: downloaded ? Colors.greenAccent.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Stack(children: [
+ if (downloading)
+ FractionallySizedBox(
+ widthFactor: progress.clamp(0.0, 1.0),
+ child: Container(
+ decoration: BoxDecoration(
+ color: widget.accent.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(13),
+ ),
+ ),
+ ),
+ Center(child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(icon, size: 16, color: color),
+ const SizedBox(width: 8),
+ Text(label, style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.w500)),
+ ],
+ )),
+ ]),
+ ),
+ );
+ }
+
+ void _handleTap(BuildContext context) {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+ if (_dl.isDownloaded(widget.itemId)) {
+ showDialog(context: context, builder: (ctx) => AlertDialog(
+ backgroundColor: const Color(0xFF2A2A2A),
+ title: const Text('Remove download?', style: TextStyle(color: Colors.white)),
+ content: const Text('This will be removed from your device.', style: TextStyle(color: Colors.white70)),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),
+ TextButton(onPressed: () { _dl.deleteDownload(widget.itemId); Navigator.pop(ctx); },
+ child: const Text('Remove', style: TextStyle(color: Colors.redAccent))),
+ ],
+ ));
+ } else if (_dl.isDownloading(widget.itemId)) {
+ _dl.cancelDownload(widget.itemId);
+ } else {
+ _dl.downloadItem(api: api, itemId: widget.itemId, title: widget.title, author: widget.author, coverUrl: widget.coverUrl);
+ }
+ }
+}
+
+// ─── ABSORBING WAVE ANIMATION ────────────────────────────────
+
+class AbsorbingWave extends StatefulWidget {
+ final Color color;
+ const AbsorbingWave({super.key, required this.color});
+ @override State<AbsorbingWave> createState() => _AbsorbingWaveState();
+}
+
+class _AbsorbingWaveState extends State<AbsorbingWave> with SingleTickerProviderStateMixin {
+ late final AnimationController _ctrl;
+
+ @override
+ void initState() {
+ super.initState();
+ _ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 1200))..repeat();
+ }
+
+ @override
+ void dispose() { _ctrl.dispose(); super.dispose(); }
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedBuilder(
+ animation: _ctrl,
+ builder: (_, __) {
+ return CustomPaint(
+ size: const Size(24, 24),
+ painter: _WavePainter(phase: _ctrl.value, color: widget.color),
+ );
+ },
+ );
+ }
+}
+
+class _WavePainter extends CustomPainter {
+ final double phase;
+ final Color color;
+ _WavePainter({required this.phase, required this.color});
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final paint = Paint()
+ ..color = color
+ ..strokeWidth = 2.5
+ ..strokeCap = StrokeCap.round
+ ..style = PaintingStyle.stroke;
+
+ final midY = size.height / 2;
+ final path = Path();
+ final waveLength = size.width;
+ path.moveTo(0, midY);
+ for (double x = 0; x <= size.width; x += 0.5) {
+ final y = midY + 6 * math.sin((x / waveLength * 2 * math.pi) + (phase * 2 * math.pi));
+ path.lineTo(x, y);
+ }
+ canvas.drawPath(path, paint);
+ }
+
+ @override
+ bool shouldRepaint(_WavePainter old) => old.phase != phase;
+}
diff --git a/lib/widgets/author_card.dart b/lib/widgets/author_card.dart
new file mode 100644
index 00000000..613049ea
--- /dev/null
+++ b/lib/widgets/author_card.dart
@@ -0,0 +1,84 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+
+class AuthorCard extends StatelessWidget {
+ final Map<String, dynamic> author;
+
+ const AuthorCard({super.key, required this.author});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+
+ final name = author['name'] as String? ?? 'Unknown';
+ final authorId = author['id'] as String? ?? '';
+
+ String? imageUrl;
+ if (authorId.isNotEmpty && auth.serverUrl != null && auth.token != null) {
+ imageUrl =
+ '${auth.serverUrl}/api/authors/$authorId/image?width=200&token=${auth.token}';
+ }
+
+ final headers = lib.mediaHeaders;
+
+ return InkWell(
+ onTap: () {},
+ borderRadius: BorderRadius.circular(16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Circular avatar
+ Container(
+ width: 80,
+ height: 80,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: cs.secondaryContainer,
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: imageUrl != null
+ ? CachedNetworkImage(
+ imageUrl: imageUrl,
+ fit: BoxFit.cover,
+ httpHeaders: headers,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ )
+ : _placeholder(cs),
+ ),
+ const SizedBox(height: 8),
+ // Name
+ SizedBox(
+ width: 100,
+ child: Text(
+ name,
+ textAlign: TextAlign.center,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelMedium?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Center(
+ child: Icon(
+ Icons.person_rounded,
+ size: 32,
+ color: cs.onSecondaryContainer.withValues(alpha: 0.5),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/book_card.dart b/lib/widgets/book_card.dart
new file mode 100644
index 00000000..7ef78a77
--- /dev/null
+++ b/lib/widgets/book_card.dart
@@ -0,0 +1,371 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/library_provider.dart';
+import '../services/download_service.dart';
+import 'book_detail_sheet.dart';
+import 'episode_list_sheet.dart';
+
+class BookCard extends StatelessWidget {
+ final Map<String, dynamic> item;
+ final bool showProgress;
+ final bool isWide;
+
+ const BookCard({
+ super.key,
+ required this.item,
+ this.showProgress = false,
+ this.isWide = false,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ final itemId = item['id'] as String?;
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+
+ final title = metadata['title'] as String? ?? 'Unknown Title';
+ final authorName = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+
+ // Progress from LibraryProvider (fetched via /api/me, same source as book detail)
+ double progress = 0;
+ if (showProgress) {
+ progress = lib.getProgress(itemId);
+ }
+
+ final headers = lib.mediaHeaders;
+
+ if (isWide) {
+ return _buildWideCard(context, cs, tt, title, authorName, coverUrl, progress, headers);
+ }
+ return _buildCompactCard(context, cs, tt, title, authorName, coverUrl, progress, headers);
+ }
+
+ void _navigateToDetail(BuildContext context) {
+ final itemId = item['id'] as String?;
+ if (itemId == null) return;
+ final lib = context.read<LibraryProvider>();
+ if (lib.isPodcastLibrary) {
+ EpisodeListSheet.show(context, item);
+ } else {
+ showBookDetailSheet(context, itemId);
+ }
+ }
+
+ /// Wide "continue listening" card with square cover + text side-by-side.
+ /// Uses IntrinsicHeight so the row sizes to the square cover without overflow.
+ Widget _buildWideCard(
+ BuildContext context,
+ ColorScheme cs,
+ TextTheme tt,
+ String title,
+ String authorName,
+ String? coverUrl,
+ double progress,
+ Map<String, String> headers,
+ ) {
+ return Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _navigateToDetail(context),
+ borderRadius: BorderRadius.circular(16),
+ child: Row(
+ children: [
+ // Square cover with download badge
+ SizedBox(
+ width: 120,
+ height: 120,
+ child: Stack(
+ children: [
+ _CoverImage(coverUrl: coverUrl, cs: cs, fit: BoxFit.contain, httpHeaders: headers),
+ if (DownloadService().isDownloaded(item['id'] as String? ?? ''))
+ Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.all(3),
+ decoration: BoxDecoration(
+ color: Colors.black54,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Icon(Icons.download_done_rounded,
+ size: 14, color: cs.primary),
+ ),
+ ),
+ ],
+ ),
+ ),
+ // Info section
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ ),
+ ),
+ if (authorName.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ authorName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ],
+ if (showProgress) ...[
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: LinearProgressIndicator(
+ value: progress.clamp(0, 1),
+ minHeight: 5,
+ backgroundColor: cs.surfaceContainerHighest,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text(
+ '${(progress * 100).round()}%',
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ /// Compact vertical card with a square cover on top and text below.
+ Widget _buildCompactCard(
+ BuildContext context,
+ ColorScheme cs,
+ TextTheme tt,
+ String title,
+ String authorName,
+ String? coverUrl,
+ double progress,
+ Map<String, String> headers,
+ ) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Square cover
+ AspectRatio(
+ aspectRatio: 1,
+ child: _PressableCard(
+ onTap: () => _navigateToDetail(context),
+ borderRadius: 12,
+ child: Card(
+ elevation: 0,
+ margin: EdgeInsets.zero,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ _CoverImage(coverUrl: coverUrl, cs: cs, httpHeaders: headers),
+ if (DownloadService().isDownloaded(item['id'] as String? ?? ''))
+ Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.all(3),
+ decoration: BoxDecoration(
+ color: Colors.black54,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Icon(Icons.download_done_rounded,
+ size: 14, color: cs.primary),
+ ),
+ ),
+ if (showProgress && progress > 0)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: ClipRRect(
+ borderRadius: const BorderRadius.vertical(
+ bottom: Radius.circular(12),
+ ),
+ child: LinearProgressIndicator(
+ value: progress.clamp(0, 1),
+ minHeight: 4,
+ backgroundColor: Colors.transparent,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 6),
+ // Title
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelMedium?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface,
+ ),
+ ),
+ ),
+ if (authorName.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ authorName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// Reusable cover image with placeholder.
+class _CoverImage extends StatelessWidget {
+ final String? coverUrl;
+ final ColorScheme cs;
+ final BoxFit fit;
+ final Map<String, String> httpHeaders;
+
+ const _CoverImage({required this.coverUrl, required this.cs, this.fit = BoxFit.cover, this.httpHeaders = const {}});
+
+ @override
+ Widget build(BuildContext context) {
+ if (coverUrl == null || coverUrl!.isEmpty) {
+ return _placeholder();
+ }
+
+ // Local file path (offline cached cover)
+ if (coverUrl!.startsWith('/')) {
+ final file = File(coverUrl!);
+ if (file.existsSync()) {
+ return Image.file(file, fit: fit, errorBuilder: (_, __, ___) => _placeholder());
+ }
+ return _placeholder();
+ }
+
+ return CachedNetworkImage(
+ imageUrl: coverUrl!,
+ fit: fit,
+ httpHeaders: httpHeaders,
+ placeholder: (_, __) => _placeholder(),
+ errorWidget: (_, __, ___) => _placeholder(),
+ );
+ }
+
+ Widget _placeholder() {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(
+ Icons.headphones_rounded,
+ size: 32,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4),
+ ),
+ ),
+ );
+ }
+}
+
+/// Pressable wrapper that scales down slightly on tap for tactile feedback.
+class _PressableCard extends StatefulWidget {
+ final Widget child;
+ final VoidCallback onTap;
+ final double borderRadius;
+
+ const _PressableCard({
+ required this.child,
+ required this.onTap,
+ this.borderRadius = 12,
+ });
+
+ @override
+ State<_PressableCard> createState() => _PressableCardState();
+}
+
+class _PressableCardState extends State<_PressableCard>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _controller;
+ late final Animation<double> _scale;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 100),
+ reverseDuration: const Duration(milliseconds: 200),
+ );
+ _scale = Tween<double>(begin: 1.0, end: 0.96).animate(
+ CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
+ );
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return GestureDetector(
+ onTapDown: (_) => _controller.forward(),
+ onTapUp: (_) {
+ _controller.reverse();
+ widget.onTap();
+ },
+ onTapCancel: () => _controller.reverse(),
+ child: ScaleTransition(
+ scale: _scale,
+ child: widget.child,
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
new file mode 100644
index 00000000..6681918e
--- /dev/null
+++ b/lib/widgets/book_detail_sheet.dart
@@ -0,0 +1,748 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:open_filex/open_filex.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:http/http.dart' as http;
+import 'package:url_launcher/url_launcher.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/api_service.dart';
+import '../services/download_service.dart';
+import '../services/progress_sync_service.dart';
+import '../services/metadata_override_service.dart';
+import '../screens/app_shell.dart';
+import '../screens/library_screen.dart';
+import 'absorbing_shared.dart';
+import 'metadata_lookup_sheet.dart';
+
+// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────
+
+void showBookDetailSheet(BuildContext context, String itemId) {
+ showModalBottomSheet(
+ context: context, isScrollControlled: true, useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => DraggableScrollableSheet(
+ expand: false, initialChildSize: 0.85, minChildSize: 0.5, maxChildSize: 0.95,
+ builder: (ctx, sc) => _BookDetailSheetContent(itemId: itemId, scrollController: sc),
+ ),
+ );
+}
+
+class _BookDetailSheetContent extends StatefulWidget {
+ final String itemId;
+ final ScrollController scrollController;
+ const _BookDetailSheetContent({required this.itemId, required this.scrollController});
+ @override State<_BookDetailSheetContent> createState() => _BookDetailSheetContentState();
+}
+
+class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
+ Map<String, dynamic>? _item;
+ Map<String, dynamic>? _rating;
+ bool _isLoading = true;
+ bool _chaptersExpanded = false;
+ bool _isAbsorbing = false;
+ bool _hasLocalOverride = false;
+ bool _showGoodreads = false;
+
+ @override void initState() {
+ super.initState();
+ _loadItem();
+ PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });
+ }
+
+ Future<void> _loadItem() async {
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+
+ // Try server first
+ if (api != null && !lib.isOffline) {
+ try {
+ final item = await api.getLibraryItem(widget.itemId);
+ if (item != null && mounted) {
+ // Apply local metadata overrides
+ final overrideService = MetadataOverrideService();
+ final override = await overrideService.get(widget.itemId);
+ Map<String, dynamic> finalItem = item;
+ if (override != null) {
+ finalItem = overrideService.applyOverrides(item, override);
+ _hasLocalOverride = true;
+ }
+
+ setState(() { _item = finalItem; _isLoading = false; });
+
+ // Fetch Audible rating
+ final media = finalItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final asin = metadata['asin'] as String?;
+ final title = metadata['title'] as String? ?? '';
+ final author = metadata['authorName'] as String?;
+
+ Map<String, dynamic>? rating;
+ if (asin != null && asin.isNotEmpty) {
+ rating = await ApiService.getAudibleRating(asin);
+ }
+ if ((rating == null || (rating['rating'] as num).toDouble() <= 0) &&
+ title.isNotEmpty) {
+ final fallback = await api.searchAudibleRating(title, author);
+ if (fallback != null && (fallback['rating'] as num).toDouble() > 0) {
+ rating = fallback;
+ }
+ }
+ if (rating != null && mounted) {
+ setState(() => _rating = rating);
+ }
+ return;
+ }
+ } catch (_) {
+ // Server unreachable — fall through to offline
+ }
+ }
+
+ // Offline fallback: build item from local download data
+ final dl = DownloadService().getInfo(widget.itemId);
+ if (dl.sessionData != null) {
+ try {
+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
+ final localItem = session['libraryItem'] as Map<String, dynamic>?;
+ if (localItem != null && mounted) {
+ setState(() { _item = localItem; _isLoading = false; });
+ return;
+ }
+ } catch (_) {}
+ }
+ // Minimal fallback from DownloadInfo metadata
+ if (dl.title != null && mounted) {
+ setState(() {
+ _item = {
+ 'id': widget.itemId,
+ 'media': {
+ 'metadata': {
+ 'title': dl.title,
+ 'authorName': dl.author ?? '',
+ },
+ },
+ };
+ _isLoading = false;
+ });
+ return;
+ }
+
+ if (mounted) setState(() => _isLoading = false);
+ }
+
+ String? get _coverUrl {
+ // Check for local override cover first
+ final localCover = _item?['_localCoverUrl'] as String?;
+ if (localCover != null && localCover.isNotEmpty) return localCover;
+ final auth = context.read<AuthProvider>();
+ return auth.apiService?.getCoverUrl(widget.itemId, width: 800);
+ }
+
+ @override Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ return Container(
+ clipBehavior: Clip.antiAlias,
+ decoration: const BoxDecoration(color: Color(0xFF111111), borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
+ child: Stack(children: [
+ if (_coverUrl != null)
+ Positioned.fill(
+ child: RepaintBoundary(
+ child: CachedNetworkImage(
+ imageUrl: _coverUrl!, fit: BoxFit.cover,
+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,
+ imageBuilder: (_, p) => ImageFiltered(
+ imageFilter: ImageFilter.blur(sigmaX: 50, sigmaY: 50, tileMode: TileMode.decal),
+ child: Image(image: p, fit: BoxFit.cover)),
+ placeholder: (_, __) => const SizedBox(),
+ errorWidget: (_, __, ___) => const SizedBox(),
+ ),
+ ),
+ ),
+ Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(
+ begin: Alignment.topCenter, end: Alignment.bottomCenter,
+ colors: [const Color(0xFF111111).withValues(alpha: 0.6), const Color(0xFF111111).withValues(alpha: 0.85), const Color(0xFF111111)],
+ )))),
+ _isLoading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))
+ : _item == null
+ ? Center(child: Text('Failed to load', style: tt.bodyMedium?.copyWith(color: Colors.white38)))
+ : AnimatedOpacity(
+ opacity: 1.0, duration: const Duration(milliseconds: 300),
+ child: _buildContent(context, cs, tt)),
+ ]),
+ );
+ }
+
+ Widget _buildContent(BuildContext context, ColorScheme cs, TextTheme tt) {
+ final media = _item!['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final chapters = media['chapters'] as List<dynamic>? ?? [];
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final authorName = metadata['authorName'] as String? ?? '';
+ final narrator = metadata['narratorName'] as String? ?? '';
+ final descRaw = metadata['description'] as String? ?? '';
+ final desc = descRaw.replaceAll(RegExp(r'<[^>]*>'), '').replaceAll('&amp;', '&').replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&#39;', "'").replaceAll('&nbsp;', ' ').trim();
+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ final seriesEntries = metadata['series'] as List<dynamic>? ?? [];
+ final genres = (metadata['genres'] as List<dynamic>?)?.cast<String>() ?? [];
+ final publisher = metadata['publisher'] as String? ?? '';
+ final year = metadata['publishedYear'] as String? ?? '';
+ final lib = context.watch<LibraryProvider>();
+ final progress = lib.getProgress(widget.itemId);
+ final auth = context.read<AuthProvider>();
+
+ final progressData = lib.getProgressData(widget.itemId);
+ final isFinished = progressData?['isFinished'] == true;
+ final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;
+ final ebookFile = media['ebookFile'] as Map<String, dynamic>?;
+
+ final isEbookOnly = PlayerSettings.isEbookOnly(_item!);
+
+ return ListView(controller: widget.scrollController, padding: EdgeInsets.fromLTRB(20, 8, 20, 32 + MediaQuery.of(context).viewPadding.bottom), children: [
+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+ Text(title, textAlign: TextAlign.center, style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white)),
+ const SizedBox(height: 4),
+ Text(authorName, textAlign: TextAlign.center, style: tt.bodyMedium?.copyWith(color: Colors.white60)),
+ if (narrator.isNotEmpty) ...[const SizedBox(height: 2),
+ Text('Narrated by $narrator', textAlign: TextAlign.center, style: tt.bodySmall?.copyWith(color: Colors.white38))],
+ // ─── AUDIBLE RATING (space always reserved) ─────────
+ const SizedBox(height: 8),
+ SizedBox(
+ height: 20,
+ child: (_rating != null && (_rating!['rating'] as num).toDouble() > 0)
+ ? Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ ..._buildStars((_rating!['rating'] as num).toDouble(), cs),
+ const SizedBox(width: 6),
+ Text((_rating!['rating'] as num).toStringAsFixed(1),
+ style: tt.labelLarge?.copyWith(fontWeight: FontWeight.w600, color: Colors.white70)),
+ const SizedBox(width: 4),
+ Text('on Audible', style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ ])
+ : null,
+ ),
+ const SizedBox(height: 12),
+ if (progress > 0 && !isFinished) ...[
+ ClipRRect(borderRadius: BorderRadius.circular(3),
+ child: LinearProgressIndicator(value: progress.clamp(0.0, 1.0), minHeight: 4,
+ backgroundColor: Colors.white.withValues(alpha: 0.1), valueColor: AlwaysStoppedAnimation(cs.primary))),
+ const SizedBox(height: 4),
+ Text('${(progress * 100).toStringAsFixed(1)}% complete', textAlign: TextAlign.center,
+ style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ const SizedBox(height: 12),
+ ],
+ if (isEbookOnly)
+ SizedBox(height: 52, child: FilledButton.icon(
+ onPressed: null,
+ icon: const Icon(Icons.menu_book_rounded, size: 24),
+ label: Text('eBook Only — No Audio',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),
+ ))
+ else
+ SizedBox(height: 52, child: FilledButton.icon(
+ onPressed: _isAbsorbing ? null : () {
+ setState(() => _isAbsorbing = true);
+ _startAbsorb(context, auth: auth, title: title, author: authorName,
+ coverUrl: _coverUrl, duration: duration, chapters: chapters);
+ },
+ icon: _isAbsorbing
+ ? SizedBox(width: 24, height: 24, child: AbsorbingWave(color: cs.onPrimary))
+ : const Icon(Icons.waves_rounded, size: 24),
+ label: Text(_isAbsorbing ? 'Absorbing…' : 'Absorb',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onPrimary)),
+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),
+ )),
+ const SizedBox(height: 12),
+ Row(children: [
+ Expanded(child: DownloadWideButton(itemId: widget.itemId, coverUrl: _coverUrl, title: title, author: authorName, accent: cs.primary)),
+ const SizedBox(width: 10),
+ Expanded(child: GestureDetector(
+ onTap: () => isFinished
+ ? _markNotFinished(context, auth, currentTime, duration)
+ : _markFinished(context, auth, duration),
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: isFinished ? Colors.green.withValues(alpha: 0.06) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: isFinished ? Colors.green.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(
+ isFinished ? Icons.check_circle_rounded : Icons.check_circle_outline_rounded,
+ size: 16,
+ color: isFinished ? Colors.green : Colors.white54,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ isFinished ? 'Fully Absorbed' : 'Fully Absorb',
+ style: TextStyle(
+ color: isFinished ? Colors.green : Colors.white54,
+ fontSize: 12, fontWeight: FontWeight.w500,
+ ),
+ ),
+ ]),
+ ),
+ )),
+ ]),
+ if (ebookFile != null) ...[
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: () => _openEbook(context, auth, ebookFile, title),
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ _ebookLoading
+ ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white54))
+ : const Icon(Icons.menu_book_rounded, size: 16, color: Colors.white54),
+ const SizedBox(width: 6),
+ Text(
+ _ebookLoading ? 'Opening…' : 'Open ePub in Another App',
+ style: const TextStyle(color: Colors.white54, fontSize: 12, fontWeight: FontWeight.w500),
+ ),
+ ]),
+ ),
+ ),
+ ],
+ if (progress > 0 || isFinished) ...[
+ const SizedBox(height: 8),
+ _sheetBtn(icon: Icons.restart_alt_rounded,
+ label: 'Reset Progress', onTap: () => _resetProgress(context, auth, duration)),
+ ],
+ const SizedBox(height: 16),
+ Wrap(spacing: 8, runSpacing: 8, children: [
+ if (year.isNotEmpty) _chip(Icons.calendar_today_rounded, year),
+ _chip(Icons.schedule_rounded, _fmtDur(duration)),
+ if (chapters.isNotEmpty) _chip(Icons.list_rounded, '${chapters.length} chapters'),
+ if (publisher.isNotEmpty) _chip(Icons.business_rounded, publisher),
+ ...genres.take(3).map((g) => _chip(Icons.tag_rounded, g)),
+ ]),
+ if (seriesEntries.isNotEmpty) ...[const SizedBox(height: 16),
+ ...seriesEntries.map((s) {
+ final name = s['name'] as String? ?? '';
+ final seq = s['sequence'] as String? ?? '';
+ final seriesId = s['id'] as String?;
+ return Padding(padding: const EdgeInsets.only(bottom: 4),
+ child: GestureDetector(
+ onTap: () => _openSeries(context, seriesId, name),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),
+ ),
+ child: Row(children: [
+ Icon(Icons.auto_stories_rounded, size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Expanded(child: Text('$name${seq.isNotEmpty ? ' #$seq' : ''}',
+ style: tt.bodySmall?.copyWith(color: cs.primary.withValues(alpha: 0.9), fontWeight: FontWeight.w500))),
+ Icon(Icons.chevron_right_rounded, size: 18, color: cs.primary.withValues(alpha: 0.5)),
+ ]),
+ ),
+ ));
+ })],
+ if (desc.isNotEmpty) ...[const SizedBox(height: 16),
+ Text('About', style: tt.titleSmall?.copyWith(color: Colors.white54, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 6),
+ Text(desc, style: tt.bodySmall?.copyWith(color: Colors.white70, height: 1.5))],
+ if (chapters.isNotEmpty) ...[const SizedBox(height: 16),
+ GestureDetector(onTap: () => setState(() => _chaptersExpanded = !_chaptersExpanded),
+ child: Row(children: [
+ Text('Chapters (${chapters.length})', style: tt.titleSmall?.copyWith(color: Colors.white54, fontWeight: FontWeight.w600)),
+ const Spacer(), Icon(_chaptersExpanded ? Icons.expand_less : Icons.expand_more, color: Colors.white38, size: 20)])),
+ if (_chaptersExpanded) ...[const SizedBox(height: 8),
+ ...chapters.asMap().entries.map((e) {
+ final ch = e.value as Map<String, dynamic>;
+ return Padding(padding: const EdgeInsets.symmetric(vertical: 3),
+ child: Row(children: [
+ SizedBox(width: 28, child: Text('${e.key + 1}', style: tt.labelSmall?.copyWith(color: Colors.white30))),
+ Expanded(child: Text(ch['title'] as String? ?? 'Chapter ${e.key + 1}', maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: Colors.white60))),
+ Text(_fmtDur(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: Colors.white30)),
+ ]));
+ })]],
+ // ─── Metadata lookup (bottom of sheet) ─────────────────
+ if (_showGoodreads) ...[
+ const SizedBox(height: 8),
+ _sheetBtn(
+ icon: Icons.local_library_rounded,
+ label: 'Search on Goodreads',
+ onTap: () => _openGoodreads(title, authorName),
+ ),
+ ],
+ if (auth.apiService != null && !lib.isOffline) ...[
+ const SizedBox(height: 20),
+ _sheetBtn(
+ icon: Icons.manage_search_rounded,
+ label: _hasLocalOverride ? 'Re-Lookup Metadata' : 'Lookup Metadata',
+ onTap: () => _openMetadataLookup(context, auth, title, authorName),
+ ),
+ ],
+ if (_hasLocalOverride) ...[
+ const SizedBox(height: 8),
+ _sheetBtn(
+ icon: Icons.layers_clear_rounded,
+ label: 'Clear Local Metadata',
+ onTap: () => _clearOverride(context),
+ ),
+ ],
+ ]);
+ }
+
+ Widget _sheetBtn({required IconData icon, required String label, required VoidCallback onTap}) {
+ return GestureDetector(onTap: onTap, child: Container(height: 44,
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.1))),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 16, color: Colors.white54), const SizedBox(width: 6),
+ Text(label, style: const TextStyle(color: Colors.white54, fontSize: 12, fontWeight: FontWeight.w500))])));
+ }
+
+ Widget _chip(IconData icon, String text) {
+ return Container(
+ constraints: const BoxConstraints(maxWidth: 200),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08))),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(icon, size: 12, color: Colors.white38), const SizedBox(width: 4),
+ Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,
+ style: const TextStyle(color: Colors.white54, fontSize: 11)))]));
+ }
+
+ String _fmtDur(double s) {
+ final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();
+ if (h > 0) return '${h}h ${m}m';
+ return '${m}m';
+ }
+
+ List<Widget> _buildStars(double rating, ColorScheme cs) {
+ final stars = <Widget>[];
+ final fullStars = rating.floor();
+ final hasHalf = (rating - fullStars) >= 0.4;
+ for (int i = 0; i < 5; i++) {
+ if (i < fullStars) {
+ stars.add(Icon(Icons.star_rounded, size: 16, color: cs.primary));
+ } else if (i == fullStars && hasHalf) {
+ stars.add(Icon(Icons.star_half_rounded, size: 16, color: cs.primary));
+ } else {
+ stars.add(Icon(Icons.star_outline_rounded, size: 16, color: Colors.white24));
+ }
+ }
+ return stars;
+ }
+
+ Future<void> _openSeries(BuildContext context, String? seriesId, String seriesName) async {
+ if (seriesId == null) return;
+ final auth = context.read<AuthProvider>();
+ // Show series sheet on top of the detail sheet (don't close detail)
+ showSeriesBooksSheet(
+ context,
+ seriesName: seriesName,
+ seriesId: seriesId,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }
+
+ bool _ebookLoading = false;
+
+ Future<void> _openEbook(BuildContext context, AuthProvider auth, Map<String, dynamic> ebookFile, String bookTitle) async {
+ if (_ebookLoading) return;
+ setState(() => _ebookLoading = true);
+
+ try {
+ final api = auth.apiService;
+ if (api == null) return;
+
+ final ino = ebookFile['ino'] as String?;
+ if (ino == null) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('No ebook file found')));
+ }
+ return;
+ }
+
+ // Get the file extension from the ebook metadata
+ final ebookName = ebookFile['metadata']?['filename'] as String? ?? ebookFile['name'] as String? ?? 'book.epub';
+ final ext = ebookName.contains('.') ? ebookName.substring(ebookName.lastIndexOf('.')) : '.epub';
+
+ // Download to cache directory
+ final cacheDir = await getTemporaryDirectory();
+ final safeTitle = bookTitle.replaceAll(RegExp(r'[^\w\s-]'), '').trim();
+ final filePath = '${cacheDir.path}/$safeTitle$ext';
+ final file = File(filePath);
+
+ // Only download if not already cached
+ if (!file.existsSync()) {
+ final cleanBase = api.baseUrl.endsWith('/') ? api.baseUrl.substring(0, api.baseUrl.length - 1) : api.baseUrl;
+ final url = '$cleanBase/api/items/${widget.itemId}/file/$ino';
+ final response = await http.get(
+ Uri.parse(url),
+ headers: {'Authorization': 'Bearer ${api.token}'},
+ ).timeout(const Duration(seconds: 60));
+
+ if (response.statusCode == 200) {
+ await file.writeAsBytes(response.bodyBytes);
+ } else {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Failed to download ebook (${response.statusCode})')));
+ }
+ return;
+ }
+ }
+
+ // Open with system handler
+ final result = await OpenFilex.open(filePath);
+ if (result.type != ResultType.done && mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text(result.message.isNotEmpty ? result.message : 'No app found to open ebook')));
+ }
+ } catch (e) {
+ debugPrint('[Ebook] Error: $e');
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Error opening ebook: $e')));
+ }
+ } finally {
+ if (mounted) setState(() => _ebookLoading = false);
+ }
+ }
+
+ Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters}) async {
+ final player = AudioPlayerService();
+ // Grab the root navigator before we pop the sheet
+ final rootNav = Navigator.of(context, rootNavigator: true);
+
+ // Ensure this book is on the absorbing list (clear any manual remove)
+ if (context.mounted) {
+ final lib = context.read<LibraryProvider>();
+ lib.addToAbsorbing(widget.itemId);
+ }
+
+ if (player.currentItemId == widget.itemId) {
+ if (!player.isPlaying) player.play();
+ rootNav.pop();
+ Future.delayed(const Duration(milliseconds: 100), () {
+ AppShell.goToAbsorbingGlobal();
+ });
+ return;
+ }
+ final api = auth.apiService;
+ if (api == null) return;
+
+ // Start playback
+ await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters);
+
+ // Refresh library so the absorbing screen picks up the new book
+ if (context.mounted) {
+ final lib = context.read<LibraryProvider>();
+ lib.refreshLocalProgress();
+ lib.refresh();
+ }
+
+ // Close sheet and navigate
+ rootNav.pop();
+ Future.delayed(const Duration(milliseconds: 100), () {
+ AppShell.goToAbsorbingGlobal();
+ });
+ }
+
+ Future<void> _markFinished(BuildContext context, AuthProvider auth, double duration) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Mark as Fully Absorbed?'),
+ content: const Text('This will set your progress to 100% and stop playback if this book is playing.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Fully Absorb')),
+ ],
+ ),
+ );
+ if (confirmed != true) return;
+ final api = auth.apiService;
+ if (api == null) return;
+ final player = AudioPlayerService();
+ if (player.currentItemId == widget.itemId) await player.stop();
+ try {
+ await api.markFinished(widget.itemId, duration);
+ await ProgressSyncService().deleteLocal(widget.itemId);
+ if (context.mounted) {
+ await _loadItem();
+ await context.read<LibraryProvider>().refresh();
+ if (mounted) setState(() {});
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3), content: const Text('Marked as finished — nice work!'),
+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ } catch (_) {
+ if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3), content: const Text('Failed to update — check your connection'),
+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+
+ Future<void> _markNotFinished(BuildContext context, AuthProvider auth, double currentTime, double duration) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Mark as Not Finished?'),
+ content: const Text('This will clear the finished status but keep your current position.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Unmark')),
+ ],
+ ),
+ );
+ if (confirmed != true) return;
+ final api = auth.apiService;
+ if (api == null) return;
+ try {
+ await api.markNotFinished(widget.itemId, currentTime: currentTime, duration: duration);
+ await ProgressSyncService().deleteLocal(widget.itemId);
+ if (context.mounted) {
+ await _loadItem();
+ await context.read<LibraryProvider>().refresh();
+ if (mounted) setState(() {});
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3), content: const Text('Marked as not finished — back at it!'),
+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ } catch (_) {
+ if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3), content: const Text('Failed to update — check your connection'),
+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+
+ Future<void> _resetProgress(BuildContext context, AuthProvider auth, double duration) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Reset Progress?'),
+ content: const Text('This will erase all progress for this book and set it back to the beginning. This can\'t be undone.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true),
+ style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
+ child: const Text('Reset')),
+ ],
+ ),
+ );
+ if (confirmed != true) return;
+ final api = auth.apiService;
+ if (api == null) return;
+ final player = AudioPlayerService();
+
+ // Stop player without saving progress
+ if (player.currentItemId == widget.itemId) {
+ await player.stopWithoutSaving();
+ }
+
+ // Clear local progress
+ await ProgressSyncService().deleteLocal(widget.itemId);
+
+ // Reset server progress (PATCH to zero + hide from continue listening)
+ final serverSuccess = await api.resetProgress(widget.itemId, duration);
+
+ // Clear from library provider (mark as reset — forces 0 progress)
+ if (context.mounted) context.read<LibraryProvider>().resetProgressFor(widget.itemId);
+ if (context.mounted) {
+ await _loadItem();
+ await context.read<LibraryProvider>().refresh();
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text(serverSuccess ? 'Progress reset — fresh start!' : 'Reset may not have synced — check your server'),
+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+
+ void _openGoodreads(String title, String author) async {
+ final q = author.isNotEmpty ? '$title $author' : title;
+ final uri = Uri.https('www.goodreads.com', '/search', {'q': q});
+ try {
+ // Open in Goodreads app if installed
+ if (!await launchUrl(uri, mode: LaunchMode.externalNonBrowserApplication)) {
+ await launchUrl(uri, mode: LaunchMode.externalApplication);
+ }
+ } catch (_) {
+ // App not installed — fall back to browser
+ await launchUrl(uri, mode: LaunchMode.externalApplication);
+ }
+ }
+
+ void _openMetadataLookup(BuildContext context, AuthProvider auth, String title, String author) {
+ final api = auth.apiService;
+ if (api == null) return;
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => DraggableScrollableSheet(
+ expand: false,
+ initialChildSize: 0.85,
+ minChildSize: 0.5,
+ maxChildSize: 0.95,
+ builder: (ctx, sc) => MetadataLookupSheet(
+ itemId: widget.itemId,
+ api: api,
+ initialTitle: title,
+ initialAuthor: author,
+ onApplied: () {
+ // Reload the item to show the new override
+ _loadItem();
+ },
+ ),
+ ),
+ );
+ }
+
+ Future<void> _clearOverride(BuildContext context) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Clear Local Metadata?'),
+ content: const Text(
+ 'This will remove the locally stored metadata and revert to whatever the server has.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Clear')),
+ ],
+ ),
+ );
+ if (confirmed != true) return;
+ await MetadataOverrideService().delete(widget.itemId);
+ if (mounted) {
+ setState(() => _hasLocalOverride = false);
+ await _loadItem();
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: const Text('Local metadata cleared'),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+ }
+}
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
new file mode 100644
index 00000000..afae4e39
--- /dev/null
+++ b/lib/widgets/card_buttons.dart
@@ -0,0 +1,501 @@
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import '../services/audio_player_service.dart';
+import '../services/bookmark_service.dart';
+import '../services/sleep_timer_service.dart';
+import 'absorb_slider.dart';
+import 'sleep_timer_sheet.dart';
+
+/// Show a toast when the user taps a button that requires active playback.
+void showInactiveToast(BuildContext context) {
+ ScaffoldMessenger.of(context)
+ ..clearSnackBars()
+ ..showSnackBar(const SnackBar(
+ content: Text('Start playing something first'),
+ duration: Duration(seconds: 2),
+ behavior: SnackBarBehavior.floating,
+ ));
+}
+
+// ─── WIDE GLASS BUTTON (for 2-column grid) ─────────────────
+
+class CardWideButton extends StatelessWidget {
+ final IconData icon;
+ final String label;
+ final Color accent;
+ final bool isActive;
+ final bool alwaysEnabled;
+ final VoidCallback? onTap;
+ final Widget? child; // if provided, renders child instead (for stateful buttons)
+
+ const CardWideButton({
+ super.key,
+ required this.icon, required this.label,
+ required this.accent, required this.isActive,
+ this.alwaysEnabled = false,
+ this.onTap, this.child,
+ });
+
+ @override Widget build(BuildContext context) {
+ if (child != null) return child!;
+ final enabled = isActive || alwaysEnabled;
+ return GestureDetector(
+ onTap: enabled ? onTap : () => showInactiveToast(context),
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 10),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(icon, size: 15, color: enabled ? Colors.white54 : Colors.white24),
+ const SizedBox(width: 6),
+ Text(label, style: TextStyle(
+ color: enabled ? Colors.white54 : Colors.white24,
+ fontSize: 11, fontWeight: FontWeight.w500)),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// Menu item for the More bottom sheet
+class MoreMenuItem extends StatelessWidget {
+ final IconData icon;
+ final String label;
+ final Color accent;
+ final bool enabled;
+ final VoidCallback onTap;
+
+ const MoreMenuItem({
+ super.key,
+ required this.icon, required this.label,
+ required this.accent, required this.onTap,
+ this.enabled = true,
+ });
+
+ @override Widget build(BuildContext context) {
+ return GestureDetector(
+ onTap: enabled ? onTap : () => showInactiveToast(context),
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ children: [
+ Icon(icon, size: 20, color: enabled ? accent.withValues(alpha: 0.7) : Colors.white24),
+ const SizedBox(width: 14),
+ Expanded(child: Text(label, style: TextStyle(
+ color: enabled ? Colors.white.withValues(alpha: 0.8) : Colors.white24,
+ fontSize: 14, fontWeight: FontWeight.w500))),
+ Icon(Icons.chevron_right_rounded, size: 18, color: enabled ? Colors.white24 : Colors.white12),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// Sleep button as wide card with countdown and fill bar
+class CardSleepButtonInline extends StatelessWidget {
+ final Color accent;
+ final bool isActive;
+ const CardSleepButtonInline({super.key, required this.accent, required this.isActive});
+
+ @override Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: SleepTimerService(),
+ builder: (_, __) {
+ final sleep = SleepTimerService();
+ // Only show timer state on the card that's actually playing
+ final active = isActive && sleep.isActive;
+ final isTime = sleep.mode == SleepTimerMode.time;
+
+ String label;
+ if (active && isTime) {
+ final r = sleep.timeRemaining;
+ final m = r.inMinutes;
+ final s = r.inSeconds % 60;
+ label = '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ } else if (active) {
+ label = '${sleep.chaptersRemaining} ch left';
+ } else {
+ label = 'Sleep Timer';
+ }
+
+ return GestureDetector(
+ onTap: isActive ? () {
+ showSleepTimerSheet(context, accent);
+ } : () => showInactiveToast(context),
+ child: Container(
+ height: 36,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: active ? accent.withValues(alpha: 0.1) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: active ? accent.withValues(alpha: 0.3) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Stack(children: [
+ if (active && isTime)
+ FractionallySizedBox(
+ widthFactor: sleep.timeProgress.clamp(0.0, 1.0),
+ child: Container(
+ decoration: BoxDecoration(
+ color: accent.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(13),
+ ),
+ ),
+ ),
+ Center(child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.bedtime_outlined, size: 16,
+ color: active ? accent : (isActive ? Colors.white54 : Colors.white24)),
+ const SizedBox(width: 8),
+ Text(label, style: TextStyle(
+ color: active ? accent : (isActive ? Colors.white54 : Colors.white24),
+ fontSize: active && isTime ? 13 : 12,
+ fontWeight: active ? FontWeight.w700 : FontWeight.w500,
+ fontFeatures: active && isTime ? const [FontFeature.tabularFigures()] : null,
+ )),
+ ],
+ )),
+ ]),
+ ),
+ );
+ },
+ );
+ }
+}
+
+/// Bookmark button as wide card
+class CardBookmarkButtonInline extends StatefulWidget {
+ final AudioPlayerService player;
+ final Color accent;
+ final bool isActive;
+ final String itemId;
+ const CardBookmarkButtonInline({super.key, required this.player, required this.accent, required this.isActive, required this.itemId});
+ @override State<CardBookmarkButtonInline> createState() => _CardBookmarkButtonInlineState();
+}
+
+class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
+ int _count = 0;
+ @override void initState() { super.initState(); _loadCount(); }
+ Future<void> _loadCount() async {
+ final c = await BookmarkService().getCount(widget.itemId);
+ if (mounted) setState(() => _count = c);
+ }
+
+ @override Widget build(BuildContext context) {
+ return GestureDetector(
+ onTap: widget.isActive ? () => _showBookmarks(context) : () => showInactiveToast(context),
+ onLongPress: widget.isActive ? () => _quickAdd(context) : null,
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.bookmark_outline_rounded, size: 18,
+ color: widget.isActive ? Colors.white54 : Colors.white24),
+ const SizedBox(width: 8),
+ Text(_count > 0 ? 'Bookmarks ($_count)' : 'Bookmark', style: TextStyle(
+ color: widget.isActive ? Colors.white54 : Colors.white24,
+ fontSize: 12, fontWeight: FontWeight.w500)),
+ ],
+ ),
+ ),
+ );
+ }
+
+ void _quickAdd(BuildContext ctx) async {
+ final pos = widget.player.position.inMilliseconds / 1000.0;
+ String? chTitle;
+ for (final ch in widget.player.chapters) {
+ final m = ch as Map<String, dynamic>;
+ final s = (m['start'] as num?)?.toDouble() ?? 0;
+ final e = (m['end'] as num?)?.toDouble() ?? 0;
+ if (pos >= s && pos < e) { chTitle = m['title'] as String?; break; }
+ }
+ await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: chTitle ?? 'Bookmark');
+ _loadCount();
+ if (ctx.mounted) {
+ ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(duration: const Duration(seconds: 2), content: const Text('Bookmark added'), behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+
+ void _showBookmarks(BuildContext context) {
+ showModalBottomSheet(
+ context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,
+ builder: (ctx) => DraggableScrollableSheet(
+ initialChildSize: 0.6, minChildSize: 0.3, maxChildSize: 0.9, expand: false,
+ builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
+ ),
+ );
+ }
+}
+
+/// Speed button as wide card — opens the full speed sheet with slider
+class CardSpeedButtonInline extends StatelessWidget {
+ final AudioPlayerService player;
+ final Color accent;
+ final bool isActive;
+ const CardSpeedButtonInline({super.key, required this.player, required this.accent, required this.isActive});
+
+ @override Widget build(BuildContext context) {
+ return GestureDetector(
+ onTap: isActive ? () {
+ showModalBottomSheet(context: context, backgroundColor: Colors.transparent,
+ useSafeArea: true,
+ builder: (ctx) => CardSpeedSheet(player: player, accent: accent));
+ } : () => showInactiveToast(context),
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.speed_rounded, size: 16,
+ color: isActive ? accent : Colors.white24),
+ const SizedBox(width: 8),
+ Text('${player.speed.toStringAsFixed(2)}x', style: TextStyle(
+ color: isActive ? accent : Colors.white24,
+ fontSize: 13, fontWeight: FontWeight.w700)),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+// ─── SPEED SHEET ─────────────────────────────────────────────
+
+class CardSpeedSheet extends StatefulWidget {
+ final AudioPlayerService player; final Color accent;
+ const CardSpeedSheet({super.key, required this.player, required this.accent});
+ @override State<CardSpeedSheet> createState() => _CardSpeedSheetState();
+}
+
+class _CardSpeedSheetState extends State<CardSpeedSheet> {
+ late double _speed;
+ static const _presets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5];
+
+ @override void initState() { super.initState(); _speed = (widget.player.speed * 20).round() / 20.0; }
+ void _setSpeed(double v) { final s = (v * 20).round() / 20.0; setState(() => _speed = s.clamp(0.5, 3.0)); widget.player.setSpeed(_speed); }
+
+ @override Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final navBarPad = MediaQuery.of(context).viewPadding.bottom;
+ return Container(
+ padding: EdgeInsets.fromLTRB(24, 16, 24, 24 + navBarPad),
+ decoration: BoxDecoration(color: const Color(0xFF1A1A1A), borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: widget.accent.withValues(alpha: 0.2), width: 1))),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 20),
+ Text('Playback Speed', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const SizedBox(height: 4),
+ Text('${_speed.toStringAsFixed(2)}x', style: tt.headlineMedium?.copyWith(fontWeight: FontWeight.w700, color: widget.accent)),
+ const SizedBox(height: 16),
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: _presets.map((s) {
+ final a = (_speed - s).abs() < 0.01;
+ return GestureDetector(onTap: () => _setSpeed(s), child: AnimatedContainer(
+ duration: const Duration(milliseconds: 150),
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+ decoration: BoxDecoration(color: a ? widget.accent : Colors.white.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: a ? widget.accent : Colors.white.withValues(alpha: 0.12))),
+ child: Text('${s}x', style: TextStyle(color: a ? Colors.black : Colors.white70, fontSize: 13, fontWeight: a ? FontWeight.w700 : FontWeight.w500)),
+ ));
+ }).toList()),
+ const SizedBox(height: 16),
+ AbsorbSlider(value: _speed, min: 0.5, max: 3.0, divisions: 50, activeColor: widget.accent, onChanged: _setSpeed),
+ Padding(padding: const EdgeInsets.symmetric(horizontal: 12), child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: const [
+ Text('0.5x', style: TextStyle(color: Colors.white30, fontSize: 11)),
+ Text('3.0x', style: TextStyle(color: Colors.white30, fontSize: 11)),
+ ],
+ )),
+ ]),
+ );
+ }
+}
+
+// ─── BOOKMARK SHEET ──────────────────────────────────────────
+
+class SimpleBookmarkSheet extends StatefulWidget {
+ final String itemId; final AudioPlayerService player; final Color accent; final ScrollController scrollController; final VoidCallback onChanged;
+ const SimpleBookmarkSheet({super.key, required this.itemId, required this.player, required this.accent, required this.scrollController, required this.onChanged});
+ @override State<SimpleBookmarkSheet> createState() => _SimpleBookmarkSheetState();
+}
+
+class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
+ List<Bookmark>? _bookmarks;
+ @override void initState() { super.initState(); _load(); }
+ Future<void> _load() async {
+ final bm = await BookmarkService().getBookmarks(widget.itemId);
+ if (mounted) setState(() => _bookmarks = bm);
+ widget.onChanged();
+ }
+
+ @override Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ return Container(
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: widget.accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: Column(children: [
+ Padding(padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+ Padding(padding: const EdgeInsets.symmetric(horizontal: 20), child: Row(children: [
+ const Spacer(),
+ Text('Bookmarks', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const Spacer(),
+ GestureDetector(onTap: () => _addBookmark(), child: Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(color: widget.accent.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(10)),
+ child: Icon(Icons.add_rounded, color: widget.accent, size: 20),
+ )),
+ ])),
+ const SizedBox(height: 8),
+ Expanded(child: _bookmarks == null
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : _bookmarks!.isEmpty
+ ? Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.bookmark_outline_rounded, size: 48, color: Colors.white.withValues(alpha: 0.1)),
+ const SizedBox(height: 12),
+ Text('No bookmarks yet', style: tt.bodyMedium?.copyWith(color: Colors.white38)),
+ const SizedBox(height: 4),
+ Text('Long-press the bookmark button to quick save', style: tt.bodySmall?.copyWith(color: Colors.white24, fontSize: 11)),
+ ]))
+ : ListView.builder(
+ controller: widget.scrollController, padding: const EdgeInsets.only(bottom: 24), itemCount: _bookmarks!.length,
+ itemBuilder: (ctx, i) {
+ final bm = _bookmarks![i];
+ final hasNote = bm.note != null && bm.note!.isNotEmpty;
+ return InkWell(
+ onTap: () { widget.player.seekTo(Duration(seconds: bm.positionSeconds.round())); Navigator.pop(ctx); },
+ onLongPress: () => _editBookmark(bm),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Icon(Icons.bookmark_rounded, size: 20, color: widget.accent),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(bm.title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(color: Colors.white70)),
+ const SizedBox(height: 2),
+ Text(bm.formattedPosition, style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ if (hasNote) ...[
+ const SizedBox(height: 4),
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(8),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Text(bm.note!, maxLines: 3, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: Colors.white38, fontSize: 11, height: 1.4)),
+ ),
+ ],
+ ])),
+ const SizedBox(width: 8),
+ GestureDetector(
+ onTap: () async {
+ await BookmarkService().deleteBookmark(itemId: widget.itemId, bookmarkId: bm.id);
+ _load();
+ },
+ child: const Padding(
+ padding: EdgeInsets.all(4),
+ child: Icon(Icons.close_rounded, size: 16, color: Colors.white24),
+ ),
+ ),
+ ]),
+ ),
+ );
+ })),
+ ]),
+ );
+ }
+
+ Future<void> _addBookmark() async {
+ final pos = widget.player.position.inMilliseconds / 1000.0;
+ final h = pos ~/ 3600; final m = (pos % 3600) ~/ 60; final s = pos.toInt() % 60;
+ final posStr = h > 0 ? '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}' : '$m:${s.toString().padLeft(2, '0')}';
+
+ // Find current chapter name for default title
+ String defaultTitle = 'Bookmark at $posStr';
+ for (final ch in widget.player.chapters) {
+ final cm = ch as Map<String, dynamic>;
+ final cs = (cm['start'] as num?)?.toDouble() ?? 0;
+ final ce = (cm['end'] as num?)?.toDouble() ?? 0;
+ if (pos >= cs && pos < ce) { defaultTitle = cm['title'] as String? ?? defaultTitle; break; }
+ }
+
+ final titleC = TextEditingController(text: defaultTitle);
+ final noteC = TextEditingController();
+ final result = await showDialog<Map<String, String>>(context: context, builder: (ctx) => AlertDialog(
+ title: const Text('Add Bookmark'),
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
+ TextField(controller: titleC, autofocus: true, decoration: const InputDecoration(labelText: 'Title', border: OutlineInputBorder())),
+ const SizedBox(height: 12),
+ TextField(controller: noteC, maxLines: 3, decoration: const InputDecoration(labelText: 'Note (optional)', border: OutlineInputBorder(), alignLabelWithHint: true)),
+ ]),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, {'title': titleC.text, 'note': noteC.text}), child: const Text('Save')),
+ ],
+ ));
+ if (result != null && result['title']!.isNotEmpty) {
+ final note = result['note']?.isNotEmpty == true ? result['note'] : null;
+ await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: result['title']!, note: note);
+ _load();
+ }
+ }
+
+ Future<void> _editBookmark(Bookmark bm) async {
+ final titleC = TextEditingController(text: bm.title);
+ final noteC = TextEditingController(text: bm.note ?? '');
+ final result = await showDialog<Map<String, String>>(context: context, builder: (ctx) => AlertDialog(
+ title: const Text('Edit Bookmark'),
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
+ TextField(controller: titleC, decoration: const InputDecoration(labelText: 'Title', border: OutlineInputBorder())),
+ const SizedBox(height: 12),
+ TextField(controller: noteC, maxLines: 3, decoration: const InputDecoration(labelText: 'Note (optional)', border: OutlineInputBorder(), alignLabelWithHint: true)),
+ ]),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, {'title': titleC.text, 'note': noteC.text}), child: const Text('Save')),
+ ],
+ ));
+ if (result != null && result['title']!.isNotEmpty) {
+ await BookmarkService().updateBookmark(
+ itemId: widget.itemId, bookmarkId: bm.id,
+ title: result['title']!, note: result['note']?.isNotEmpty == true ? result['note'] : null,
+ );
+ _load();
+ }
+ }
+}
diff --git a/lib/widgets/card_playback_controls.dart b/lib/widgets/card_playback_controls.dart
new file mode 100644
index 00000000..9d195713
--- /dev/null
+++ b/lib/widgets/card_playback_controls.dart
@@ -0,0 +1,247 @@
+import 'package:flutter/material.dart';
+import 'package:just_audio/just_audio.dart' hide PlaybackEvent;
+import '../services/audio_player_service.dart';
+import '../services/chromecast_service.dart';
+
+// ─── PLAYBACK CONTROLS (card version) ───────────────────────
+
+class CardPlaybackControls extends StatefulWidget {
+ final AudioPlayerService player;
+ final Color accent;
+ final bool isActive;
+ final bool isStarting;
+ final VoidCallback onStart;
+ final String? itemId;
+ const CardPlaybackControls({super.key, required this.player, required this.accent, required this.isActive, required this.isStarting, required this.onStart, this.itemId});
+ @override State<CardPlaybackControls> createState() => _CardPlaybackControlsState();
+}
+
+class _CardPlaybackControlsState extends State<CardPlaybackControls> with SingleTickerProviderStateMixin {
+ int _backSkip = 10;
+ int _forwardSkip = 30;
+ late AnimationController _playPauseController;
+
+ @override void initState() {
+ super.initState();
+ _playPauseController = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 300),
+ value: 0, // 0 = play icon, 1 = pause icon
+ );
+ _loadSkipSettings();
+ PlayerSettings.settingsChanged.addListener(_loadSkipSettings);
+ }
+
+ @override void didUpdateWidget(covariant CardPlaybackControls old) {
+ super.didUpdateWidget(old);
+ }
+
+ void _loadSkipSettings() {
+ PlayerSettings.getBackSkip().then((v) { if (mounted && v != _backSkip) setState(() => _backSkip = v); });
+ PlayerSettings.getForwardSkip().then((v) { if (mounted && v != _forwardSkip) setState(() => _forwardSkip = v); });
+ }
+
+ @override void dispose() {
+ PlayerSettings.settingsChanged.removeListener(_loadSkipSettings);
+ _playPauseController.dispose();
+ super.dispose();
+ }
+
+ Widget _skipIcon(int seconds, bool isForward, {bool active = true}) {
+ final hasBuiltIn = [5, 10, 30].contains(seconds);
+ if (hasBuiltIn) {
+ IconData icon;
+ if (isForward) { icon = seconds == 5 ? Icons.forward_5_rounded : seconds == 10 ? Icons.forward_10_rounded : Icons.forward_30_rounded; }
+ else { icon = seconds == 5 ? Icons.replay_5_rounded : seconds == 10 ? Icons.replay_10_rounded : Icons.replay_30_rounded; }
+ return Icon(icon, size: 38, color: active ? Colors.white70 : Colors.white24);
+ }
+ return Stack(alignment: Alignment.center, children: [
+ Icon(isForward ? Icons.rotate_right_rounded : Icons.rotate_left_rounded, size: 38, color: active ? Colors.white70 : Colors.white24),
+ Padding(padding: const EdgeInsets.only(top: 2), child: Text('$seconds', style: TextStyle(fontSize: 10, fontWeight: FontWeight.w900, color: active ? Colors.white : Colors.white24))),
+ ]);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (widget.isStarting) {
+ return SizedBox(height: 64,
+ child: Center(child: SizedBox(width: 64, height: 64,
+ child: Container(
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: Colors.white,
+ boxShadow: [BoxShadow(color: widget.accent.withValues(alpha: 0.4), blurRadius: 25, spreadRadius: -5)],
+ ),
+ child: Center(child: SizedBox(width: 28, height: 28, child: CircularProgressIndicator(strokeWidth: 2, color: widget.accent))),
+ ),
+ )),
+ );
+ }
+
+ final cast = ChromecastService();
+
+ return ListenableBuilder(
+ listenable: cast,
+ builder: (context, _) {
+ // Check if we're casting this specific book
+ final castItemId = widget.itemId ?? widget.player.currentItemId;
+ final isCastingThis = cast.isCasting && cast.castingItemId == castItemId;
+
+ if (isCastingThis) {
+ return _buildCastControls(cast);
+ }
+
+ return _buildLocalControls();
+ },
+ );
+ }
+
+ /// Controls that route to ChromecastService
+ Widget _buildCastControls(ChromecastService cast) {
+ final isPlaying = cast.isPlaying;
+
+ if (isPlaying) {
+ _playPauseController.forward();
+ } else {
+ _playPauseController.reverse();
+ }
+
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ GestureDetector(
+ onTap: cast.skipToPreviousChapter,
+ child: SizedBox(width: 40, height: 40, child: Center(
+ child: Icon(Icons.skip_previous_rounded, size: 24, color: Colors.white38),
+ )),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: () => cast.skipBackward(_backSkip),
+ child: SizedBox(width: 52, height: 52, child: Center(child: _skipIcon(_backSkip, false))),
+ ),
+ const SizedBox(width: 16),
+ GestureDetector(
+ onTap: cast.togglePlayPause,
+ child: SizedBox(
+ width: 80, height: 80,
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Container(
+ width: 64, height: 64,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: Colors.white,
+ boxShadow: [BoxShadow(color: widget.accent.withValues(alpha: 0.4), blurRadius: 25, spreadRadius: -5)],
+ ),
+ child: Center(
+ child: AnimatedIcon(
+ icon: AnimatedIcons.play_pause,
+ progress: _playPauseController,
+ size: 34,
+ color: Colors.black87,
+ ),
+ ),
+ ),
+ // Cast indicator badge
+ Positioned(
+ bottom: 4,
+ child: Icon(Icons.cast_connected_rounded, size: 14, color: widget.accent.withValues(alpha: 0.7)),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ GestureDetector(
+ onTap: () => cast.skipForward(_forwardSkip),
+ child: SizedBox(width: 52, height: 52, child: Center(child: _skipIcon(_forwardSkip, true))),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: cast.skipToNextChapter,
+ child: SizedBox(width: 40, height: 40, child: Center(
+ child: Icon(Icons.skip_next_rounded, size: 24, color: Colors.white38),
+ )),
+ ),
+ ],
+ );
+ }
+
+ /// Original local player controls
+ Widget _buildLocalControls() {
+ return StreamBuilder<PlayerState>(
+ stream: widget.isActive ? widget.player.playerStateStream : const Stream.empty(),
+ builder: (_, snapshot) {
+ final isPlaying = widget.isActive && (snapshot.data?.playing ?? false);
+ final isLoading = widget.isActive && (snapshot.data?.processingState == ProcessingState.loading || snapshot.data?.processingState == ProcessingState.buffering);
+
+ if (isPlaying) {
+ _playPauseController.forward();
+ } else {
+ _playPauseController.reverse();
+ }
+
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ GestureDetector(
+ onTap: widget.isActive ? widget.player.skipToPreviousChapter : null,
+ child: SizedBox(width: 40, height: 40, child: Center(
+ child: Icon(Icons.skip_previous_rounded, size: 24, color: widget.isActive ? Colors.white38 : Colors.white12),
+ )),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: widget.isActive ? () => widget.player.skipBackward(_backSkip) : null,
+ child: SizedBox(width: 52, height: 52, child: Center(child: _skipIcon(_backSkip, false, active: widget.isActive))),
+ ),
+ const SizedBox(width: 16),
+ GestureDetector(
+ onTap: widget.isActive ? widget.player.togglePlayPause : widget.onStart,
+ child: SizedBox(
+ width: 80, height: 80,
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Container(
+ width: 64, height: 64,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: Colors.white,
+ boxShadow: [BoxShadow(color: widget.accent.withValues(alpha: 0.4), blurRadius: 25, spreadRadius: -5)],
+ ),
+ child: isLoading
+ ? Center(child: SizedBox(width: 28, height: 28, child: CircularProgressIndicator(strokeWidth: 2, color: widget.accent)))
+ : Center(
+ child: AnimatedIcon(
+ icon: AnimatedIcons.play_pause,
+ progress: _playPauseController,
+ size: 34,
+ color: Colors.black87,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ GestureDetector(
+ onTap: widget.isActive ? () => widget.player.skipForward(_forwardSkip) : null,
+ child: SizedBox(width: 52, height: 52, child: Center(child: _skipIcon(_forwardSkip, true, active: widget.isActive))),
+ ),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: widget.isActive ? widget.player.skipToNextChapter : null,
+ child: SizedBox(width: 40, height: 40, child: Center(
+ child: Icon(Icons.skip_next_rounded, size: 24, color: widget.isActive ? Colors.white38 : Colors.white12),
+ )),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
new file mode 100644
index 00000000..1fb5fcf3
--- /dev/null
+++ b/lib/widgets/card_progress_bar.dart
@@ -0,0 +1,515 @@
+import 'dart:async';
+import 'dart:math';
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import '../services/audio_player_service.dart';
+import 'absorb_slider.dart';
+import 'absorbing_shared.dart';
+
+// ─── DUAL PROGRESS BAR (card version) ───────────────────────
+
+class CardDualProgressBar extends StatefulWidget {
+ final AudioPlayerService player;
+ final Color accent;
+ final bool isActive;
+ final double staticProgress;
+ final double staticDuration;
+ final List<dynamic> chapters;
+ final bool showBookBar;
+ final bool showChapterBar;
+ final String? chapterName;
+ final int chapterIndex;
+ final int totalChapters;
+ const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0});
+ @override State<CardDualProgressBar> createState() => _CardDualProgressBarState();
+}
+
+class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerProviderStateMixin, WidgetsBindingObserver {
+ double? _chapterDragValue;
+ double? _bookDragValue;
+ bool _showBookSlider = false;
+ bool _speedAdjustedTime = true;
+ late AnimationController _waveController;
+ late AnimationController _smoothTicker;
+
+ // Smooth position tracking
+ double _lastKnownPos = 0;
+ DateTime _lastPosTime = DateTime.now();
+ double _currentSpeed = 1.0;
+ bool _isPlaying = false;
+ StreamSubscription<Duration>? _posSub;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addObserver(this);
+ _waveController = AnimationController(vsync: this, duration: const Duration(milliseconds: 2500))..repeat();
+ _smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999))..repeat();
+ _loadSettings();
+ _subscribePosition();
+ // Listen for settings changes instead of polling
+ PlayerSettings.settingsChanged.addListener(_loadSettings);
+ }
+
+ void _loadSettings() {
+ PlayerSettings.getShowBookSlider().then((v) { if (mounted && v != _showBookSlider) setState(() => _showBookSlider = v); });
+ PlayerSettings.getSpeedAdjustedTime().then((v) { if (mounted && v != _speedAdjustedTime) setState(() => _speedAdjustedTime = v); });
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state == AppLifecycleState.resumed) _loadSettings();
+ }
+
+ @override
+ void didUpdateWidget(CardDualProgressBar old) {
+ super.didUpdateWidget(old);
+ if (old.isActive != widget.isActive) _subscribePosition();
+ }
+
+ void _subscribePosition() {
+ _posSub?.cancel();
+ if (widget.isActive) {
+ // Reset to the seed on a fresh subscription — clears stale position from a
+ // previous episode and gives the near-zero rejection filter a clean baseline.
+ final seedPos = widget.staticProgress * widget.staticDuration;
+ _lastKnownPos = seedPos;
+ _lastPosTime = DateTime.now();
+
+ _posSub = widget.player.absolutePositionStream.listen((dur) {
+ final posSeconds = dur.inMilliseconds / 1000.0;
+
+ // If a seek just happened, check if this position event is the real
+ // post-seek value or a transient glitch. Accept values near the seek
+ // target; reject obvious transitional near-zero values.
+ final seekTarget = widget.player.activeSeekTarget;
+ if (seekTarget != null) {
+ // Accept if close to the seek target (within 5s tolerance)
+ if ((posSeconds - seekTarget).abs() < 5.0) {
+ _lastKnownPos = posSeconds;
+ _lastPosTime = DateTime.now();
+ _currentSpeed = widget.player.speed;
+ _isPlaying = widget.player.isPlaying;
+ return;
+ }
+ // Reject transient values far from the seek target
+ return;
+ }
+
+ // Normal playback: reject transient near-zero during track changes
+ if (_lastKnownPos > 10.0 && posSeconds < 2.0) {
+ return;
+ }
+
+ _lastKnownPos = posSeconds;
+ _lastPosTime = DateTime.now();
+ _currentSpeed = widget.player.speed;
+ _isPlaying = widget.player.isPlaying;
+ });
+ _currentSpeed = widget.player.speed;
+ _isPlaying = widget.player.isPlaying;
+ }
+ }
+
+ /// Smoothly interpolated position — predicts where playback is right now.
+ /// Snaps immediately to seek target when a seek is in progress.
+ double get _smoothPos {
+ // If a seek just happened, snap to the target immediately
+ final seekTarget = widget.player.activeSeekTarget;
+ if (seekTarget != null && (seekTarget - _lastKnownPos).abs() > 2.0) {
+ return seekTarget;
+ }
+ if (!widget.isActive || !_isPlaying) return _lastKnownPos;
+ final elapsed = DateTime.now().difference(_lastPosTime).inMilliseconds / 1000.0;
+ return _lastKnownPos + elapsed * _currentSpeed;
+ }
+
+ @override void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ PlayerSettings.settingsChanged.removeListener(_loadSettings);
+ _posSub?.cancel();
+ _waveController.dispose();
+ _smoothTicker.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final player = widget.player;
+ final active = widget.isActive;
+
+ return ListenableBuilder(
+ listenable: _smoothTicker,
+ builder: (context, _) {
+ final staticPos = widget.staticProgress * widget.staticDuration;
+ final posS = active ? _smoothPos : staticPos;
+ final totalDur = active ? player.totalDuration : widget.staticDuration;
+ final speed = active ? _currentSpeed : 1.0;
+ final isPlaying = active && _isPlaying;
+ final bookProgress = totalDur > 0 ? (posS / totalDur).clamp(0.0, 1.0) : 0.0;
+
+ double chapterStart = 0, chapterEnd = totalDur;
+ if (active) {
+ final chapter = player.currentChapter;
+ if (chapter != null) {
+ chapterStart = (chapter['start'] as num?)?.toDouble() ?? 0;
+ chapterEnd = (chapter['end'] as num?)?.toDouble() ?? totalDur;
+ } else if (player.chapters.isNotEmpty) {
+ for (final ch in player.chapters) {
+ final m = ch as Map<String, dynamic>;
+ final s = (m['start'] as num?)?.toDouble() ?? 0;
+ final e = (m['end'] as num?)?.toDouble() ?? 0;
+ if (posS >= s && posS < e) {
+ chapterStart = s;
+ chapterEnd = e;
+ break;
+ }
+ }
+ }
+ } else if (widget.chapters.isNotEmpty) {
+ // Inactive card: find chapter from stored chapters list using static position
+ for (final ch in widget.chapters) {
+ final m = ch as Map<String, dynamic>;
+ final s = (m['start'] as num?)?.toDouble() ?? 0;
+ final e = (m['end'] as num?)?.toDouble() ?? 0;
+ if (posS >= s && posS < e) {
+ chapterStart = s;
+ chapterEnd = e;
+ break;
+ }
+ }
+ }
+ final chapterDur = chapterEnd - chapterStart;
+ final chapterPos = (posS - chapterStart).clamp(0.0, chapterDur);
+ final chapterProgress = chapterDur > 0 ? chapterPos / chapterDur : 0.0;
+ final speedDiv = _speedAdjustedTime ? speed : 1.0;
+ final bookRemaining = (totalDur - posS) / speedDiv;
+ final chapterRemaining = (chapterDur - chapterPos) / speedDiv;
+ final chapterElapsed = chapterPos / speedDiv;
+
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Column(children: [
+ // Book bar
+ if (widget.showBookBar) ...[
+ if (_showBookSlider) ...[
+ SizedBox(height: 32, child: LayoutBuilder(builder: (_, cons) {
+ final w = cons.maxWidth;
+ final p = _bookDragValue ?? bookProgress;
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onHorizontalDragStart: active ? (d) { setState(() => _bookDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,
+ onHorizontalDragUpdate: active ? (d) { setState(() => _bookDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,
+ onHorizontalDragEnd: active ? (_) { if (_bookDragValue != null) { final seekMs = (_bookDragValue! * totalDur * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } setState(() => _bookDragValue = null); } : null,
+ onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = (v * totalDur * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } : null,
+ child: CustomPaint(size: Size(w, 32), painter: AbsorbProgressPainter(progress: p, accent: widget.accent.withValues(alpha: 0.5), isDragging: _bookDragValue != null)),
+ );
+ })),
+ Padding(padding: const EdgeInsets.only(top: 2, bottom: 6), child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : posS), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? Colors.white70 : Colors.white54, fontSize: 12, fontWeight: FontWeight.w600, shadows: [Shadow(color: Colors.black.withValues(alpha: 0.5), blurRadius: 3)])),
+ Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? Colors.white70 : Colors.white54, fontSize: 12, fontWeight: FontWeight.w600, shadows: [Shadow(color: Colors.black.withValues(alpha: 0.5), blurRadius: 3)])),
+ ],
+ )),
+ ] else ...[
+ Row(children: [
+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : posS), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? Colors.white60 : Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ const SizedBox(width: 8),
+ Expanded(child: ClipRRect(borderRadius: BorderRadius.circular(4),
+ child: LinearProgressIndicator(value: bookProgress, minHeight: 3, backgroundColor: Colors.white.withValues(alpha: 0.08), valueColor: AlwaysStoppedAnimation(widget.accent.withValues(alpha: 0.5))))),
+ const SizedBox(width: 8),
+ Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? Colors.white60 : Colors.white38, fontSize: 11, fontWeight: FontWeight.w500)),
+ ]),
+ const SizedBox(height: 10),
+ ],
+ ], // end showBookBar
+ // Chapter bar
+ if (widget.showChapterBar) ...[
+ // ── Chapter pill-scrubber ──
+ SizedBox(height: 30, child: LayoutBuilder(builder: (_, cons) {
+ final w = cons.maxWidth;
+ final p = _chapterDragValue ?? chapterProgress;
+ final isDragging = _chapterDragValue != null;
+ final chName = widget.chapterName != null
+ ? _smartChapterName(widget.chapterName!, widget.chapterIndex, widget.totalChapters)
+ : null;
+
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onHorizontalDragStart: active ? (d) { setState(() => _chapterDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,
+ onHorizontalDragUpdate: active ? (d) { setState(() => _chapterDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,
+ onHorizontalDragEnd: active ? (_) { if (_chapterDragValue != null) { final seekMs = ((chapterStart + _chapterDragValue! * chapterDur) * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } setState(() => _chapterDragValue = null); } : null,
+ onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = ((chapterStart + v * chapterDur) * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } : null,
+ child: CustomPaint(
+ size: Size(w, 30),
+ painter: ChapterPillPainter(
+ progress: p,
+ accent: widget.accent,
+ wavePhase: 0,
+ isPlaying: isPlaying,
+ isDragging: isDragging,
+ ),
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: chName != null
+ ? MarqueeText(
+ text: chName,
+ style: TextStyle(
+ color: Colors.white.withValues(alpha: 0.9),
+ fontWeight: FontWeight.w600,
+ fontSize: 12,
+ letterSpacing: 0.2,
+ ),
+ )
+ : const SizedBox.shrink(),
+ ),
+ ),
+ ),
+ );
+ })),
+ // Time labels below pill — update during drag
+ Padding(padding: const EdgeInsets.only(top: 3), child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(_fmt(_chapterDragValue != null ? (_chapterDragValue! * chapterDur) / speedDiv : chapterElapsed),
+ style: tt.labelSmall?.copyWith(
+ color: _chapterDragValue != null ? widget.accent : Colors.white54,
+ fontSize: 11, fontWeight: FontWeight.w600,
+ fontFeatures: const [FontFeature.tabularFigures()])),
+ Text('-${_fmt(_chapterDragValue != null ? ((1.0 - _chapterDragValue!) * chapterDur) / speedDiv : chapterRemaining)}',
+ style: tt.labelSmall?.copyWith(
+ color: _chapterDragValue != null ? widget.accent : Colors.white38,
+ fontSize: 11, fontWeight: FontWeight.w500,
+ fontFeatures: const [FontFeature.tabularFigures()])),
+ ],
+ )),
+ ], // end showChapterBar
+ ]),
+ );
+ },
+ );
+ }
+
+ String _fmt(double s) {
+ if (s < 0) s = 0;
+ final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor(); final sec = (s % 60).floor();
+ if (h > 0) return '${h.toString().padLeft(2, '0')}:${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';
+ return '${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';
+ }
+
+ /// Smart chapter name: prefix bare numbers, show chapter position.
+ String _smartChapterName(String raw, int index, int total) {
+ final trimmed = raw.trim();
+ // Pure number → "Chapter 16"
+ if (RegExp(r'^\d+$').hasMatch(trimmed)) {
+ return 'Chapter $trimmed';
+ }
+ // Very short (1-2 chars) → prefix
+ if (trimmed.length <= 2) {
+ return 'Chapter $trimmed';
+ }
+ return trimmed;
+ }
+}
+
+// ─── CHAPTER PILL PAINTER ────────────────────────────────────
+
+class ChapterPillPainter extends CustomPainter {
+ final double progress;
+ final Color accent;
+ final double wavePhase;
+ final bool isPlaying;
+ final bool isDragging;
+
+ ChapterPillPainter({
+ required this.progress,
+ required this.accent,
+ required this.wavePhase,
+ required this.isPlaying,
+ required this.isDragging,
+ });
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final h = size.height;
+ final w = size.width;
+ final radius = h / 2;
+ final p = progress.clamp(0.0, 1.0);
+
+ // Pill shape
+ final pillRect = RRect.fromRectAndRadius(
+ Rect.fromLTWH(0, 0, w, h),
+ Radius.circular(radius),
+ );
+
+ // Background
+ canvas.drawRRect(pillRect, Paint()..color = const Color(0xFF1A1A1A));
+
+ // Border
+ canvas.drawRRect(
+ pillRect,
+ Paint()
+ ..color = isDragging ? accent.withValues(alpha: 0.5) : accent.withValues(alpha: 0.2)
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 0.5,
+ );
+
+ if (p <= 0.001) return;
+
+ // Fill — clip to pill, draw a simple rect
+ final fillW = p * w;
+ canvas.save();
+ canvas.clipRRect(pillRect);
+ canvas.drawRect(
+ Rect.fromLTWH(0, 0, fillW, h),
+ Paint()..color = accent.withValues(alpha: 0.25),
+ );
+ canvas.restore();
+
+ // Thin glowing line at progress edge — height follows pill curvature
+ if (p < 0.995) {
+ final lineX = fillW.clamp(1.0, w - 1.0);
+
+ // Calculate how tall the line should be based on the pill circle at this x
+ // The pill is a stadium shape: two semicircles of radius=h/2 at each end
+ double lineH;
+ if (lineX < radius) {
+ // Left cap region — chord height
+ final dx = radius - lineX;
+ lineH = 2 * sqrt(radius * radius - dx * dx);
+ } else if (lineX > w - radius) {
+ // Right cap region — chord height
+ final dx = lineX - (w - radius);
+ lineH = 2 * sqrt(radius * radius - dx * dx);
+ } else {
+ // Middle — full height
+ lineH = h;
+ }
+
+ final inset = (h - lineH) / 2 + 2; // 2px inner padding
+
+ // Glow layers (more when playing)
+ if (isPlaying) {
+ // Outer glow
+ canvas.drawLine(
+ Offset(lineX, inset),
+ Offset(lineX, h - inset),
+ Paint()
+ ..color = accent.withValues(alpha: 0.2)
+ ..strokeWidth = 8.0
+ ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6),
+ );
+ // Mid glow
+ canvas.drawLine(
+ Offset(lineX, inset),
+ Offset(lineX, h - inset),
+ Paint()
+ ..color = accent.withValues(alpha: 0.4)
+ ..strokeWidth = 4.0
+ ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3),
+ );
+ }
+
+ // Solid line
+ canvas.drawLine(
+ Offset(lineX, inset),
+ Offset(lineX, h - inset),
+ Paint()
+ ..color = accent.withValues(alpha: isPlaying ? 0.95 : 0.5)
+ ..strokeWidth = 1.5
+ ..strokeCap = StrokeCap.round,
+ );
+ }
+ }
+
+ @override
+ bool shouldRepaint(covariant ChapterPillPainter old) =>
+ old.progress != progress ||
+ old.isDragging != isDragging;
+}
+
+// ─── MARQUEE TEXT ────────────────────────────────────────────
+
+class MarqueeText extends StatefulWidget {
+ final String text;
+ final TextStyle style;
+ const MarqueeText({super.key, required this.text, required this.style});
+ @override State<MarqueeText> createState() => _MarqueeTextState();
+}
+
+class _MarqueeTextState extends State<MarqueeText> with SingleTickerProviderStateMixin {
+ late ScrollController _scrollController;
+ late AnimationController _animController;
+ double _maxScroll = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _scrollController = ScrollController();
+ _animController = AnimationController(vsync: this, duration: const Duration(seconds: 6));
+ _animController.addListener(_onTick);
+ WidgetsBinding.instance.addPostFrameCallback((_) => _checkOverflow());
+ }
+
+ @override
+ void didUpdateWidget(covariant MarqueeText old) {
+ super.didUpdateWidget(old);
+ if (old.text != widget.text) {
+ _animController.stop();
+ _animController.reset();
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ WidgetsBinding.instance.addPostFrameCallback((_) => _checkOverflow());
+ }
+ }
+
+ void _onTick() {
+ if (_scrollController.hasClients && _maxScroll > 0) {
+ _scrollController.jumpTo(_animController.value * _maxScroll);
+ }
+ }
+
+ void _checkOverflow() {
+ if (!mounted || !_scrollController.hasClients) return;
+ _maxScroll = _scrollController.position.maxScrollExtent;
+ if (_maxScroll > 0) {
+ final dur = Duration(milliseconds: (_maxScroll * 25).round().clamp(2000, 15000));
+ _animController.duration = dur;
+ _startLoop();
+ }
+ }
+
+ void _startLoop() async {
+ await Future.delayed(const Duration(seconds: 2));
+ if (!mounted) return;
+ await _animController.forward(from: 0);
+ if (!mounted) return;
+ await Future.delayed(const Duration(seconds: 2));
+ if (!mounted) return;
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _startLoop();
+ }
+
+ @override
+ void dispose() {
+ _animController.removeListener(_onTick);
+ _animController.dispose();
+ _scrollController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return SingleChildScrollView(
+ controller: _scrollController,
+ scrollDirection: Axis.horizontal,
+ physics: const NeverScrollableScrollPhysics(),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 2),
+ child: Text(widget.text, style: widget.style, maxLines: 1, softWrap: false),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/chromecast_button.dart b/lib/widgets/chromecast_button.dart
new file mode 100644
index 00000000..2539834c
--- /dev/null
+++ b/lib/widgets/chromecast_button.dart
@@ -0,0 +1,371 @@
+import 'dart:async';
+import 'package:flutter/material.dart';
+import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+import '../services/chromecast_service.dart';
+import '../services/api_service.dart';
+
+/// Shows a device picker. If castAfter params are provided, automatically
+/// casts the book after connecting to the selected device.
+void showCastDevicePicker(
+ BuildContext context, {
+ ApiService? api,
+ String? itemId,
+ String? title,
+ String? author,
+ String? coverUrl,
+ double? totalDuration,
+ List<dynamic>? chapters,
+}) {
+ final cast = ChromecastService();
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: const Color(0xFF1A1A1A),
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (ctx) => SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(width: 36, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 16),
+ const Text('Cast to Device', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white)),
+ const SizedBox(height: 16),
+ SizedBox(
+ height: 200,
+ child: StreamBuilder<List<GoogleCastDevice>>(
+ stream: cast.devicesStream,
+ builder: (_, snap) {
+ final devices = snap.data ?? [];
+ if (devices.isEmpty) {
+ return const Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white38)),
+ SizedBox(height: 12),
+ Text('Searching for Cast devices...', style: TextStyle(color: Colors.white38, fontSize: 13)),
+ ],
+ ),
+ );
+ }
+ return ListView.builder(
+ shrinkWrap: true,
+ itemCount: devices.length,
+ itemBuilder: (_, i) {
+ final device = devices[i];
+ return ListTile(
+ leading: const Icon(Icons.cast_rounded, color: Colors.white54),
+ title: Text(device.friendlyName, style: const TextStyle(color: Colors.white)),
+ subtitle: Text(device.modelName ?? '', style: const TextStyle(color: Colors.white38, fontSize: 12)),
+ onTap: () {
+ Navigator.pop(ctx);
+ cast.connectToDevice(device);
+ if (api != null && itemId != null) {
+ _waitAndCast(cast, api: api, itemId: itemId,
+ title: title ?? '', author: author ?? '',
+ coverUrl: coverUrl, totalDuration: totalDuration ?? 0,
+ chapters: chapters ?? []);
+ }
+ },
+ );
+ },
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
+
+/// Wait for connection to establish, then cast the item.
+void _waitAndCast(
+ ChromecastService cast, {
+ required ApiService api,
+ required String itemId,
+ required String title,
+ required String author,
+ required String? coverUrl,
+ required double totalDuration,
+ required List<dynamic> chapters,
+}) {
+ if (cast.isConnected) {
+ cast.castItem(api: api, itemId: itemId, title: title, author: author,
+ coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters);
+ return;
+ }
+
+ StreamSubscription? sub;
+ Timer? timeout;
+
+ void cleanup() {
+ sub?.cancel();
+ timeout?.cancel();
+ }
+
+ sub = GoogleCastSessionManager.instance.currentSessionStream.listen((session) {
+ if (cast.isConnected) {
+ cleanup();
+ Future.delayed(const Duration(milliseconds: 500), () {
+ cast.castItem(api: api, itemId: itemId, title: title, author: author,
+ coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters);
+ });
+ }
+ });
+
+ timeout = Timer(const Duration(seconds: 15), () {
+ debugPrint('[Cast] Connection timeout — giving up auto-cast');
+ cleanup();
+ });
+}
+
+/// Bottom sheet with cast controls when connected.
+class CastControlSheet extends StatelessWidget {
+ const CastControlSheet({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: ChromecastService(),
+ builder: (context, _) {
+ final cast = ChromecastService();
+ final accent = Theme.of(context).colorScheme.primary;
+
+ return SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(24, 16, 24, 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(width: 36, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 20),
+
+ Row(children: [
+ Icon(Icons.cast_connected_rounded, size: 20, color: accent),
+ const SizedBox(width: 10),
+ Expanded(child: Text(cast.connectedDeviceName ?? 'Cast Device',
+ style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: accent), overflow: TextOverflow.ellipsis)),
+ ]),
+
+ if (cast.isCasting) ...[
+ const SizedBox(height: 20),
+ // Book info + chapter
+ Row(children: [
+ if (cast.castingCoverUrl != null)
+ ClipRRect(borderRadius: BorderRadius.circular(8),
+ child: Image.network(cast.castingCoverUrl!, width: 48, height: 48, fit: BoxFit.cover,
+ headers: context.read<LibraryProvider>().mediaHeaders,
+ errorBuilder: (_, __, ___) => Container(width: 48, height: 48,
+ decoration: BoxDecoration(color: Colors.white10, borderRadius: BorderRadius.circular(8)),
+ child: const Icon(Icons.headphones_rounded, size: 24, color: Colors.white24)))),
+ const SizedBox(width: 14),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(cast.castingTitle ?? 'Unknown', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),
+ const SizedBox(height: 2),
+ Text(cast.castingAuthor ?? '', style: const TextStyle(fontSize: 12, color: Colors.white60), maxLines: 1, overflow: TextOverflow.ellipsis),
+ if (cast.currentChapterTitle != null) ...[
+ const SizedBox(height: 2),
+ Text(cast.currentChapterTitle!, style: TextStyle(fontSize: 11, color: accent.withValues(alpha: 0.7)), maxLines: 1, overflow: TextOverflow.ellipsis),
+ ],
+ ])),
+ ]),
+ const SizedBox(height: 16),
+
+ // Progress bar
+ StreamBuilder<Duration>(
+ stream: cast.castPositionStream?.map((d) => d ?? Duration.zero),
+ initialData: cast.castPosition,
+ builder: (_, snap) {
+ final pos = snap.data ?? Duration.zero;
+ final totalMs = (cast.castingDuration * 1000).round();
+ final progress = totalMs > 0 ? (pos.inMilliseconds / totalMs).clamp(0.0, 1.0) : 0.0;
+ return Column(children: [
+ LinearProgressIndicator(value: progress, backgroundColor: Colors.white10, color: accent, minHeight: 3, borderRadius: BorderRadius.circular(2)),
+ const SizedBox(height: 6),
+ Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
+ Text(_fmt(pos), style: const TextStyle(fontSize: 11, color: Colors.white38)),
+ Text(_fmt(Duration(seconds: cast.castingDuration.round())), style: const TextStyle(fontSize: 11, color: Colors.white38)),
+ ]),
+ ]);
+ },
+ ),
+ const SizedBox(height: 12),
+
+ // Playback controls
+ Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ IconButton(onPressed: cast.skipToPreviousChapter, icon: const Icon(Icons.skip_previous_rounded, size: 24, color: Colors.white38)),
+ IconButton(onPressed: () => cast.skipBackward(10), icon: const Icon(Icons.replay_10_rounded, size: 32, color: Colors.white70)),
+ const SizedBox(width: 8),
+ Container(width: 52, height: 52,
+ decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white,
+ boxShadow: [BoxShadow(color: accent.withValues(alpha: 0.3), blurRadius: 16, spreadRadius: -4)]),
+ child: IconButton(onPressed: cast.togglePlayPause,
+ icon: Icon(cast.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded, size: 28, color: Colors.black87))),
+ const SizedBox(width: 8),
+ IconButton(onPressed: () => cast.skipForward(30), icon: const Icon(Icons.forward_30_rounded, size: 32, color: Colors.white70)),
+ IconButton(onPressed: cast.skipToNextChapter, icon: const Icon(Icons.skip_next_rounded, size: 24, color: Colors.white38)),
+ ]),
+
+ // Speed control
+ const SizedBox(height: 12),
+ _CastSpeedControl(cast: cast, accent: accent),
+
+ // Volume control
+ const SizedBox(height: 8),
+ _CastVolumeControl(cast: cast, accent: accent),
+ ],
+
+ const SizedBox(height: 20),
+ Row(children: [
+ if (cast.isCasting) ...[
+ Expanded(child: OutlinedButton.icon(
+ onPressed: () { cast.stopCasting(); Navigator.of(context).pop(); },
+ icon: const Icon(Icons.stop_rounded, size: 18), label: const Text('Stop Casting'),
+ style: OutlinedButton.styleFrom(foregroundColor: Colors.white60, side: const BorderSide(color: Colors.white12),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))))),
+ const SizedBox(width: 12),
+ ],
+ Expanded(child: OutlinedButton.icon(
+ onPressed: () { cast.disconnect(); Navigator.of(context).pop(); },
+ icon: const Icon(Icons.close_rounded, size: 18), label: const Text('Disconnect'),
+ style: OutlinedButton.styleFrom(foregroundColor: Colors.redAccent.withValues(alpha: 0.8),
+ side: BorderSide(color: Colors.redAccent.withValues(alpha: 0.3)),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))))),
+ ]),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ String _fmt(Duration d) {
+ final h = d.inHours, m = d.inMinutes % 60, s = d.inSeconds % 60;
+ if (h > 0) return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ return '$m:${s.toString().padLeft(2, '0')}';
+ }
+}
+
+// ─── Cast Speed Control ─────────────────────────────────────
+
+class _CastSpeedControl extends StatelessWidget {
+ final ChromecastService cast;
+ final Color accent;
+ const _CastSpeedControl({required this.cast, required this.accent});
+
+ static const _presets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0];
+
+ @override
+ Widget build(BuildContext context) {
+ final speed = cast.castSpeed;
+ return Row(
+ children: [
+ Icon(Icons.speed_rounded, size: 16, color: accent),
+ const SizedBox(width: 8),
+ Text('${speed.toStringAsFixed(2)}x',
+ style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700, color: accent)),
+ const SizedBox(width: 12),
+ Expanded(
+ child: SizedBox(
+ height: 32,
+ child: ListView(
+ scrollDirection: Axis.horizontal,
+ children: _presets.map((s) {
+ final selected = (s - speed).abs() < 0.01;
+ return Padding(
+ padding: const EdgeInsets.only(right: 6),
+ child: GestureDetector(
+ onTap: () => cast.setSpeed(s),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ decoration: BoxDecoration(
+ color: selected ? accent.withValues(alpha: 0.2) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(color: selected ? accent.withValues(alpha: 0.4) : Colors.white12),
+ ),
+ child: Text('${s}x',
+ style: TextStyle(
+ fontSize: 12, fontWeight: FontWeight.w600,
+ color: selected ? accent : Colors.white54,
+ ),
+ ),
+ ),
+ ),
+ );
+ }).toList(),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+// ─── Cast Volume Control ────────────────────────────────────
+
+class _CastVolumeControl extends StatefulWidget {
+ final ChromecastService cast;
+ final Color accent;
+ const _CastVolumeControl({required this.cast, required this.accent});
+
+ @override
+ State<_CastVolumeControl> createState() => _CastVolumeControlState();
+}
+
+class _CastVolumeControlState extends State<_CastVolumeControl> {
+ late double _localVolume;
+ bool _dragging = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _localVolume = widget.cast.volume;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final vol = _dragging ? _localVolume : widget.cast.volume;
+ return Row(
+ children: [
+ Icon(
+ vol <= 0.01 ? Icons.volume_off_rounded
+ : vol < 0.5 ? Icons.volume_down_rounded
+ : Icons.volume_up_rounded,
+ size: 18, color: Colors.white54,
+ ),
+ Expanded(
+ child: SliderTheme(
+ data: SliderThemeData(
+ trackHeight: 3,
+ thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 7),
+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 14),
+ activeTrackColor: widget.accent,
+ inactiveTrackColor: Colors.white12,
+ thumbColor: widget.accent,
+ overlayColor: widget.accent.withValues(alpha: 0.15),
+ ),
+ child: Slider(
+ value: vol.clamp(0.0, 1.0),
+ min: 0.0,
+ max: 1.0,
+ onChangeStart: (_) => _dragging = true,
+ onChanged: (v) => setState(() => _localVolume = v),
+ onChangeEnd: (v) {
+ _dragging = false;
+ widget.cast.setVolume(v);
+ },
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
new file mode 100644
index 00000000..9a2fae73
--- /dev/null
+++ b/lib/widgets/episode_list_sheet.dart
@@ -0,0 +1,1104 @@
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/download_service.dart';
+import '../services/chromecast_service.dart';
+import '../providers/auth_provider.dart';
+
+/// Bottom sheet that shows a podcast's episode list.
+/// Mirrors the UX of [BookDetailSheet] but adapted for podcast shows.
+class EpisodeListSheet extends StatefulWidget {
+ final Map<String, dynamic> podcastItem;
+ final ScrollController? scrollController;
+
+ const EpisodeListSheet({super.key, required this.podcastItem})
+ : scrollController = null;
+
+ const EpisodeListSheet._({
+ required this.podcastItem,
+ required this.scrollController,
+ }) : super(key: null);
+
+ /// Show the episode list as a modal bottom sheet.
+ static void show(BuildContext context, Map<String, dynamic> podcastItem) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => DraggableScrollableSheet(
+ initialChildSize: 0.85,
+ minChildSize: 0.5,
+ maxChildSize: 0.95,
+ expand: false,
+ builder: (_, scrollController) => EpisodeListSheet._(
+ podcastItem: podcastItem,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+ }
+
+ @override
+ State<EpisodeListSheet> createState() => _EpisodeListSheetState();
+}
+
+class _EpisodeListSheetState extends State<EpisodeListSheet> {
+ List<dynamic> _episodes = [];
+ bool _isLoading = true;
+ bool _descriptionExpanded = false;
+ bool _isDownloadingAll = false;
+
+ String get _itemId => widget.podcastItem['id'] as String? ?? '';
+
+ Map<String, dynamic> get _media =>
+ widget.podcastItem['media'] as Map<String, dynamic>? ?? {};
+
+ Map<String, dynamic> get _metadata =>
+ _media['metadata'] as Map<String, dynamic>? ?? {};
+
+ String get _title => _metadata['title'] as String? ?? 'Unknown Podcast';
+ String get _author => _metadata['author'] as String? ?? '';
+ String get _description => _metadata['description'] as String? ?? '';
+
+ @override
+ void initState() {
+ super.initState();
+ _loadEpisodes();
+ }
+
+ Future<void> _loadEpisodes() async {
+ // Episodes may already be in the item from expanded=1 or from the library list
+ final existing = _media['episodes'] as List<dynamic>?;
+ if (existing != null && existing.isNotEmpty) {
+ setState(() {
+ _episodes = _sortEpisodes(existing);
+ _isLoading = false;
+ });
+ return;
+ }
+
+ // Otherwise fetch the full item
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) {
+ setState(() => _isLoading = false);
+ return;
+ }
+
+ final fullItem = await api.getLibraryItem(_itemId);
+ if (fullItem != null && mounted) {
+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ setState(() {
+ _episodes = _sortEpisodes(episodes);
+ _isLoading = false;
+ });
+ } else {
+ if (mounted) setState(() => _isLoading = false);
+ }
+ }
+
+ /// Sort episodes newest first by publishedAt.
+ List<dynamic> _sortEpisodes(List<dynamic> episodes) {
+ final sorted = List<dynamic>.from(episodes);
+ sorted.sort((a, b) {
+ final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;
+ final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;
+ return bTime.compareTo(aTime); // newest first
+ });
+ return sorted;
+ }
+
+ Future<void> _playEpisode(Map<String, dynamic> episode) async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+
+ final episodeId = episode['id'] as String? ?? '';
+ final episodeTitle = episode['title'] as String? ?? 'Episode';
+ final duration = (episode['duration'] as num?)?.toDouble() ?? 0;
+ final coverUrl = api.getCoverUrl(_itemId);
+
+ // Check if Chromecast is connected
+ final cast = ChromecastService();
+ if (cast.isConnected) {
+ await cast.castItem(
+ api: api,
+ itemId: _itemId,
+ title: episodeTitle,
+ author: _title,
+ coverUrl: coverUrl,
+ totalDuration: duration,
+ chapters: [],
+ );
+ if (mounted) Navigator.pop(context);
+ return;
+ }
+
+ final player = AudioPlayerService();
+ await player.playItem(
+ api: api,
+ itemId: _itemId,
+ title: episodeTitle,
+ author: _title,
+ coverUrl: coverUrl,
+ totalDuration: duration,
+ chapters: [],
+ episodeId: episodeId,
+ episodeTitle: episodeTitle,
+ );
+ if (mounted) Navigator.pop(context);
+ }
+
+ Future<void> _downloadEpisode(Map<String, dynamic> episode) async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+
+ final episodeId = episode['id'] as String? ?? '';
+ final episodeTitle = episode['title'] as String? ?? 'Episode';
+ final coverUrl = api.getCoverUrl(_itemId);
+
+ final error = await DownloadService().downloadItem(
+ api: api,
+ itemId: '$_itemId-$episodeId',
+ title: episodeTitle,
+ author: _title,
+ coverUrl: coverUrl,
+ episodeId: episodeId,
+ );
+
+ if (error != null && mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error)));
+ }
+ }
+
+ Future<void> _downloadAll() async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+
+ setState(() => _isDownloadingAll = true);
+
+ for (final ep in _episodes) {
+ if (!mounted) break;
+ final episodeId = ep['id'] as String? ?? '';
+ final key = '$_itemId-$episodeId';
+ if (DownloadService().isDownloaded(key) || DownloadService().isDownloading(key)) continue;
+
+ await DownloadService().downloadItem(
+ api: api,
+ itemId: key,
+ title: ep['title'] as String? ?? 'Episode',
+ author: _title,
+ coverUrl: api.getCoverUrl(_itemId),
+ episodeId: episodeId,
+ );
+ }
+
+ if (mounted) setState(() => _isDownloadingAll = false);
+ }
+
+ String? get _coverUrl {
+ final auth = context.read<AuthProvider>();
+ return auth.apiService?.getCoverUrl(_itemId, width: 800);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final coverUrl = _coverUrl;
+
+ return Container(
+ clipBehavior: Clip.antiAlias,
+ decoration: const BoxDecoration(
+ color: Color(0xFF111111),
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Stack(children: [
+ // Blurred cover background
+ if (coverUrl != null)
+ Positioned.fill(
+ child: RepaintBoundary(
+ child: CachedNetworkImage(
+ imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ imageBuilder: (_, p) => ImageFiltered(
+ imageFilter: ImageFilter.blur(sigmaX: 50, sigmaY: 50, tileMode: TileMode.decal),
+ child: Image(image: p, fit: BoxFit.cover)),
+ placeholder: (_, __) => const SizedBox(),
+ errorWidget: (_, __, ___) => const SizedBox(),
+ ),
+ ),
+ ),
+ // Gradient overlay
+ Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(
+ begin: Alignment.topCenter, end: Alignment.bottomCenter,
+ colors: [
+ const Color(0xFF111111).withValues(alpha: 0.6),
+ const Color(0xFF111111).withValues(alpha: 0.85),
+ const Color(0xFF111111),
+ ],
+ )))),
+ // Content
+ Column(children: [
+ // Drag handle
+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(top: 8, bottom: 4),
+ decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+
+ // ── Header (non-scrollable) ──
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
+ child: Column(children: [
+ // Show title (centered)
+ Text(_title, textAlign: TextAlign.center,
+ style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white)),
+ if (_author.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(_author, textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: Colors.white60)),
+ ],
+
+ // Description
+ if (_description.isNotEmpty) ...[
+ const SizedBox(height: 10),
+ GestureDetector(
+ onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),
+ child: Text(_description,
+ maxLines: _descriptionExpanded ? 100 : 2,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.center,
+ style: tt.bodySmall?.copyWith(color: Colors.white38, height: 1.4)),
+ ),
+ ],
+
+ // Metadata chips
+ const SizedBox(height: 12),
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ if (!_isLoading) _chip(Icons.podcasts_rounded, '${_episodes.length} episode${_episodes.length == 1 ? '' : 's'}'),
+ ]),
+
+ // Download All button (reactive)
+ if (_episodes.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (_, __) {
+ final dl = DownloadService();
+ int downloaded = 0;
+ int downloading = 0;
+ double totalProgress = 0;
+ for (final ep in _episodes) {
+ final eid = ep['id'] as String? ?? '';
+ final key = '$_itemId-$eid';
+ if (dl.isDownloaded(key)) {
+ downloaded++;
+ } else if (dl.isDownloading(key)) {
+ downloading++;
+ totalProgress += dl.downloadProgress(key);
+ }
+ }
+ final allDone = downloaded == _episodes.length;
+ final anyActive = _isDownloadingAll || downloading > 0;
+ final overallProgress = _episodes.isNotEmpty
+ ? (downloaded + totalProgress) / _episodes.length
+ : 0.0;
+
+ if (allDone) {
+ return GestureDetector(
+ child: Container(height: 44,
+ decoration: BoxDecoration(
+ color: Colors.greenAccent.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.greenAccent.withValues(alpha: 0.15)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(Icons.download_done_rounded, size: 16, color: Colors.greenAccent.withValues(alpha: 0.7)),
+ const SizedBox(width: 6),
+ Text('All Episodes Downloaded',
+ style: TextStyle(color: Colors.greenAccent.withValues(alpha: 0.7), fontSize: 12, fontWeight: FontWeight.w500)),
+ ])),
+ );
+ }
+
+ return GestureDetector(
+ onTap: anyActive ? null : _downloadAll,
+ child: Container(height: 44,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.1)),
+ ),
+ child: Stack(children: [
+ if (anyActive)
+ FractionallySizedBox(
+ widthFactor: overallProgress.clamp(0.0, 1.0),
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(13),
+ ),
+ ),
+ ),
+ Center(child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ if (anyActive)
+ SizedBox(width: 14, height: 14,
+ child: CircularProgressIndicator(strokeWidth: 2,
+ color: Theme.of(context).colorScheme.primary))
+ else
+ const Icon(Icons.download_rounded, size: 16, color: Colors.white54),
+ const SizedBox(width: 6),
+ Text(
+ anyActive
+ ? 'Downloading ${downloaded + downloading}/${_episodes.length} · ${(overallProgress * 100).toStringAsFixed(0)}%'
+ : downloaded > 0
+ ? 'Download Remaining (${_episodes.length - downloaded})'
+ : 'Download All Episodes',
+ style: TextStyle(
+ color: anyActive ? Theme.of(context).colorScheme.primary : Colors.white54,
+ fontSize: 12, fontWeight: FontWeight.w500)),
+ ])),
+ ]),
+ ),
+ );
+ },
+ ),
+ ],
+
+ // Episodes section header
+ const SizedBox(height: 16),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Text('Episodes', style: tt.titleSmall?.copyWith(color: Colors.white54, fontWeight: FontWeight.w600)),
+ ),
+ const SizedBox(height: 4),
+ ]),
+ ),
+
+ // ── Scrollable episode list ──
+ Expanded(
+ child: _isLoading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))
+ : _episodes.isEmpty
+ ? Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.podcasts_rounded, size: 48, color: Colors.white.withValues(alpha: 0.15)),
+ const SizedBox(height: 12),
+ Text('No episodes found', style: tt.bodyMedium?.copyWith(color: Colors.white38)),
+ ],
+ ),
+ )
+ : ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.only(bottom: 32 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: _episodes.length,
+ itemBuilder: (context, index) {
+ final ep = _episodes[index] as Map<String, dynamic>;
+ return _EpisodeRow(
+ episode: ep,
+ podcastItem: widget.podcastItem,
+ itemId: _itemId,
+ podcastTitle: _title,
+ onPlay: () => _playEpisode(ep),
+ onDownload: () => _downloadEpisode(ep),
+ );
+ },
+ ),
+ ),
+ ]),
+ ]),
+ );
+ }
+
+ Widget _chip(IconData icon, String text) {
+ return Container(
+ constraints: const BoxConstraints(maxWidth: 200),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08))),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(icon, size: 12, color: Colors.white38), const SizedBox(width: 4),
+ Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,
+ style: const TextStyle(color: Colors.white54, fontSize: 11)))]));
+ }
+}
+
+// ── Episode Detail Sheet ──
+
+class EpisodeDetailSheet extends StatefulWidget {
+ final Map<String, dynamic> podcastItem;
+ final Map<String, dynamic> episode;
+ final ScrollController? scrollController;
+
+ const EpisodeDetailSheet({super.key, required this.podcastItem, required this.episode})
+ : scrollController = null;
+
+ const EpisodeDetailSheet._({
+ required this.podcastItem,
+ required this.episode,
+ required this.scrollController,
+ }) : super(key: null);
+
+ static void show(BuildContext context, Map<String, dynamic> podcastItem, Map<String, dynamic> episode) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => DraggableScrollableSheet(
+ initialChildSize: 0.75,
+ minChildSize: 0.4,
+ maxChildSize: 0.95,
+ expand: false,
+ builder: (_, scrollController) => EpisodeDetailSheet._(
+ podcastItem: podcastItem,
+ episode: episode,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+ }
+
+ @override
+ State<EpisodeDetailSheet> createState() => _EpisodeDetailSheetState();
+}
+
+class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
+ bool _descriptionExpanded = false;
+
+ String get _itemId => widget.podcastItem['id'] as String? ?? '';
+
+ String get _showTitle {
+ final media = widget.podcastItem['media'] as Map<String, dynamic>? ?? {};
+ final meta = media['metadata'] as Map<String, dynamic>? ?? {};
+ return meta['title'] as String? ?? '';
+ }
+
+ String get _episodeTitle => widget.episode['title'] as String? ?? 'Episode';
+ String get _episodeId => widget.episode['id'] as String? ?? '';
+ double get _duration => (widget.episode['duration'] as num?)?.toDouble() ?? 0;
+ int get _publishedAt => (widget.episode['publishedAt'] as num?)?.toInt() ?? 0;
+ String? get _episodeNumber => widget.episode['episode'] as String?;
+ String? get _season => widget.episode['season'] as String?;
+
+ String get _cleanDescription {
+ final desc = widget.episode['description'] as String? ?? '';
+ return desc
+ .replaceAll(RegExp(r'<[^>]*>'), '')
+ .replaceAll('&nbsp;', ' ')
+ .replaceAll('&amp;', '&')
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .trim();
+ }
+
+ Future<void> _play() async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+
+ final cast = ChromecastService();
+ if (cast.isConnected) {
+ await cast.castItem(
+ api: api, itemId: _itemId, title: _episodeTitle, author: _showTitle,
+ coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: [],
+ );
+ if (mounted) Navigator.pop(context);
+ return;
+ }
+
+ await AudioPlayerService().playItem(
+ api: api, itemId: _itemId, title: _episodeTitle, author: _showTitle,
+ coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: [],
+ episodeId: _episodeId,
+ episodeTitle: _episodeTitle,
+ );
+ if (mounted) Navigator.pop(context);
+ }
+
+ Future<void> _download() async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+
+ final error = await DownloadService().downloadItem(
+ api: api,
+ itemId: '$_itemId-$_episodeId',
+ title: _episodeTitle,
+ author: _showTitle,
+ coverUrl: api.getCoverUrl(_itemId),
+ episodeId: _episodeId,
+ );
+ if (error != null && mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error)));
+ }
+ }
+
+ Future<void> _toggleFinished() async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+ final lib = context.read<LibraryProvider>();
+ final key = '$_itemId-$_episodeId';
+ final progressData = lib.getEpisodeProgressData(_itemId, _episodeId);
+ final isFinished = progressData?['isFinished'] == true;
+ final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;
+
+ try {
+ if (isFinished) {
+ // Un-finish — keep current position
+ await api.updateEpisodeProgress(
+ _itemId, _episodeId,
+ currentTime: currentTime,
+ duration: _duration,
+ isFinished: false,
+ );
+ await lib.refresh();
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: const Text('Marked as not finished'),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ } else {
+ // Mark finished — update server then local state for instant UI
+ await api.updateEpisodeProgress(
+ _itemId, _episodeId,
+ currentTime: _duration,
+ duration: _duration,
+ isFinished: true,
+ );
+ lib.markFinishedLocally(key);
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: const Text('Marked as finished — nice!'),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+ } catch (_) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
+ content: Text('Failed to update — check your connection')));
+ }
+ }
+ }
+
+ String? get _coverUrl {
+ final auth = context.read<AuthProvider>();
+ return auth.apiService?.getCoverUrl(_itemId, width: 800);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final coverUrl = _coverUrl;
+
+ final dlKey = '$_itemId-$_episodeId';
+
+ final progress = lib.getEpisodeProgress(_itemId, _episodeId);
+ final progressData = lib.getEpisodeProgressData(_itemId, _episodeId);
+ final isFinished = progressData?['isFinished'] == true;
+
+ String dateLabel = '';
+ if (_publishedAt > 0) {
+ final date = DateTime.fromMillisecondsSinceEpoch(_publishedAt);
+ final diff = DateTime.now().difference(date);
+ if (diff.inDays == 0) dateLabel = 'Today';
+ else if (diff.inDays == 1) dateLabel = 'Yesterday';
+ else if (diff.inDays < 7) dateLabel = '${diff.inDays}d ago';
+ else if (diff.inDays < 30) dateLabel = '${(diff.inDays / 7).floor()}w ago';
+ else dateLabel = '${date.month}/${date.day}/${date.year}';
+ }
+
+ String durationLabel = '';
+ if (_duration > 0) {
+ final h = (_duration / 3600).floor();
+ final m = ((_duration % 3600) / 60).floor();
+ durationLabel = h > 0 ? '${h}h ${m}m' : '${m}m';
+ }
+
+ return Container(
+ clipBehavior: Clip.antiAlias,
+ decoration: const BoxDecoration(
+ color: Color(0xFF111111),
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Stack(children: [
+ // Blurred cover background
+ if (coverUrl != null)
+ Positioned.fill(
+ child: RepaintBoundary(
+ child: CachedNetworkImage(
+ imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ imageBuilder: (_, p) => ImageFiltered(
+ imageFilter: ImageFilter.blur(sigmaX: 50, sigmaY: 50, tileMode: TileMode.decal),
+ child: Image(image: p, fit: BoxFit.cover)),
+ placeholder: (_, __) => const SizedBox(),
+ errorWidget: (_, __, ___) => const SizedBox(),
+ ),
+ ),
+ ),
+ // Gradient overlay
+ Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(
+ begin: Alignment.topCenter, end: Alignment.bottomCenter,
+ colors: [
+ const Color(0xFF111111).withValues(alpha: 0.6),
+ const Color(0xFF111111).withValues(alpha: 0.85),
+ const Color(0xFF111111),
+ ],
+ )))),
+ // Content
+ ListView(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(20, 8, 20, 32 + MediaQuery.of(context).viewPadding.bottom),
+ children: [
+ // Drag handle
+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),
+
+ // Episode title (centered)
+ Text(_episodeTitle, textAlign: TextAlign.center,
+ style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, color: Colors.white)),
+ const SizedBox(height: 4),
+
+ // Show title
+ if (_showTitle.isNotEmpty)
+ Text(_showTitle, textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: Colors.white60)),
+
+ const SizedBox(height: 12),
+
+ // Progress bar
+ if (progress > 0) ...[
+ ClipRRect(borderRadius: BorderRadius.circular(3),
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0), minHeight: 4,
+ backgroundColor: Colors.white.withValues(alpha: 0.1),
+ valueColor: AlwaysStoppedAnimation(
+ isFinished ? cs.primary.withValues(alpha: 0.4) : cs.primary),
+ )),
+ const SizedBox(height: 4),
+ Text('${(progress * 100).toStringAsFixed(1)}% complete', textAlign: TextAlign.center,
+ style: tt.labelSmall?.copyWith(color: Colors.white38)),
+ const SizedBox(height: 12),
+ ],
+
+ // Play button (full width, matching book detail)
+ SizedBox(height: 52, child: FilledButton.icon(
+ onPressed: _play,
+ icon: Icon(
+ progress > 0 && !isFinished ? Icons.play_arrow_rounded : Icons.podcasts_rounded,
+ size: 24,
+ ),
+ label: Text(
+ progress > 0 && !isFinished ? 'Resume' : 'Play Episode',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onPrimary),
+ ),
+ style: FilledButton.styleFrom(
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
+ ),
+ )),
+ const SizedBox(height: 12),
+
+ // Download + Finished row
+ Row(children: [
+ Expanded(child: ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (context, _) {
+ final dl = DownloadService();
+ final downloaded = dl.isDownloaded(dlKey);
+ final downloading = dl.isDownloading(dlKey);
+ final dlProgress = dl.downloadProgress(dlKey);
+
+ final IconData icon;
+ final String label;
+ final Color color;
+ if (downloaded) {
+ icon = Icons.download_done_rounded;
+ label = 'Downloaded';
+ color = Colors.greenAccent.withValues(alpha: 0.7);
+ } else if (downloading) {
+ icon = Icons.downloading_rounded;
+ label = '${(dlProgress * 100).toStringAsFixed(0)}%';
+ color = cs.primary;
+ } else {
+ icon = Icons.download_outlined;
+ label = 'Download';
+ color = Colors.white54;
+ }
+
+ return GestureDetector(
+ onTap: (downloaded || downloading) ? null : _download,
+ child: Container(
+ height: 36,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: downloaded ? Colors.greenAccent.withValues(alpha: 0.06) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: downloaded ? Colors.greenAccent.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Stack(children: [
+ if (downloading)
+ FractionallySizedBox(
+ widthFactor: dlProgress.clamp(0.0, 1.0),
+ child: Container(
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(13),
+ ),
+ ),
+ ),
+ Center(child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 16, color: color),
+ const SizedBox(width: 6),
+ Text(label, style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.w500)),
+ ])),
+ ]),
+ ),
+ );
+ },
+ )),
+ const SizedBox(width: 10),
+ Expanded(child: GestureDetector(
+ onTap: _toggleFinished,
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: isFinished ? Colors.green.withValues(alpha: 0.06) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: isFinished ? Colors.green.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(
+ isFinished ? Icons.check_circle_rounded : Icons.check_circle_outline_rounded,
+ size: 16,
+ color: isFinished ? Colors.green : Colors.white54,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ isFinished ? 'Finished' : 'Mark Finished',
+ style: TextStyle(
+ color: isFinished ? Colors.green : Colors.white54,
+ fontSize: 12, fontWeight: FontWeight.w500,
+ ),
+ ),
+ ]),
+ ),
+ )),
+ ]),
+
+ // Metadata chips
+ const SizedBox(height: 16),
+ Wrap(spacing: 8, runSpacing: 8, children: [
+ if (dateLabel.isNotEmpty) _chip(Icons.calendar_today_rounded, dateLabel),
+ if (durationLabel.isNotEmpty) _chip(Icons.schedule_rounded, durationLabel),
+ if (_episodeNumber != null) _chip(Icons.tag_rounded, 'Episode $_episodeNumber'),
+ if (_season != null) _chip(Icons.layers_rounded, 'Season $_season'),
+ ]),
+
+ // All Episodes button (series-style)
+ const SizedBox(height: 16),
+ GestureDetector(
+ onTap: () {
+ Navigator.pop(context);
+ EpisodeListSheet.show(context, widget.podcastItem);
+ },
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),
+ ),
+ child: Row(children: [
+ Icon(Icons.podcasts_rounded, size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Expanded(child: Text('All Episodes',
+ style: tt.bodySmall?.copyWith(color: cs.primary.withValues(alpha: 0.9), fontWeight: FontWeight.w500))),
+ Icon(Icons.chevron_right_rounded, size: 18, color: cs.primary.withValues(alpha: 0.5)),
+ ]),
+ ),
+ ),
+
+ // Description
+ if (_cleanDescription.isNotEmpty) ...[
+ const SizedBox(height: 16),
+ Text('About This Episode', style: tt.titleSmall?.copyWith(color: Colors.white54, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 6),
+ GestureDetector(
+ onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),
+ child: Text(_cleanDescription,
+ maxLines: _descriptionExpanded ? 200 : 4,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: Colors.white70, height: 1.5)),
+ ),
+ if (_cleanDescription.length > 200)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: GestureDetector(
+ onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),
+ child: Text(
+ _descriptionExpanded ? 'Show less' : 'Show more',
+ style: TextStyle(fontSize: 12, color: cs.primary, fontWeight: FontWeight.w500),
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ]),
+ );
+ }
+
+ Widget _chip(IconData icon, String text) {
+ return Container(
+ constraints: const BoxConstraints(maxWidth: 200),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(color: Colors.white.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.08))),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(icon, size: 12, color: Colors.white38), const SizedBox(width: 4),
+ Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,
+ style: const TextStyle(color: Colors.white54, fontSize: 11)))]));
+ }
+}
+
+// ── Episode Row ──
+
+class _EpisodeRow extends StatefulWidget {
+ final Map<String, dynamic> episode;
+ final Map<String, dynamic> podcastItem;
+ final String itemId;
+ final String podcastTitle;
+ final VoidCallback onPlay;
+ final VoidCallback onDownload;
+
+ const _EpisodeRow({
+ required this.episode,
+ required this.podcastItem,
+ required this.itemId,
+ required this.podcastTitle,
+ required this.onPlay,
+ required this.onDownload,
+ });
+
+ @override
+ State<_EpisodeRow> createState() => _EpisodeRowState();
+}
+
+class _EpisodeRowState extends State<_EpisodeRow> {
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final lib = context.watch<LibraryProvider>();
+ final ep = widget.episode;
+
+ final title = ep['title'] as String? ?? 'Episode';
+ final episodeId = ep['id'] as String? ?? '';
+ final duration = (ep['duration'] as num?)?.toDouble() ?? 0;
+ final publishedAt = (ep['publishedAt'] as num?)?.toInt() ?? 0;
+
+ // Progress
+ final progress = lib.getEpisodeProgress(widget.itemId, episodeId);
+ final progressData = lib.getEpisodeProgressData(widget.itemId, episodeId);
+ final isFinished = progressData?['isFinished'] == true;
+
+ // Download key for reactive lookups
+ final dlKey = '${widget.itemId}-$episodeId';
+
+ // Format publish date
+ String dateLabel = '';
+ if (publishedAt > 0) {
+ final date = DateTime.fromMillisecondsSinceEpoch(publishedAt);
+ final now = DateTime.now();
+ final diff = now.difference(date);
+ if (diff.inDays == 0) {
+ dateLabel = 'Today';
+ } else if (diff.inDays == 1) {
+ dateLabel = 'Yesterday';
+ } else if (diff.inDays < 7) {
+ dateLabel = '${diff.inDays}d ago';
+ } else if (diff.inDays < 30) {
+ dateLabel = '${(diff.inDays / 7).floor()}w ago';
+ } else if (diff.inDays < 365) {
+ dateLabel = '${date.month}/${date.day}';
+ } else {
+ dateLabel = '${date.month}/${date.day}/${date.year}';
+ }
+ }
+
+ // Format duration
+ String durationLabel = '';
+ if (duration > 0) {
+ final h = (duration / 3600).floor();
+ final m = ((duration % 3600) / 60).floor();
+ if (h > 0) {
+ durationLabel = '${h}h ${m}m';
+ } else {
+ durationLabel = '${m}m';
+ }
+ }
+
+ return InkWell(
+ onTap: () => EpisodeDetailSheet.show(context, widget.podcastItem, ep),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(20, 10, 12, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Play/status indicator
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: isFinished
+ ? Icon(Icons.check_circle_rounded, size: 18, color: cs.primary.withValues(alpha: 0.6))
+ : progress > 0
+ ? SizedBox(
+ width: 18, height: 18,
+ child: CircularProgressIndicator(
+ value: progress,
+ strokeWidth: 2.5,
+ backgroundColor: cs.surfaceContainerHighest,
+ color: cs.primary,
+ ),
+ )
+ : Icon(Icons.circle_outlined, size: 18,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ),
+ const SizedBox(width: 12),
+
+ // Title + metadata
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w500,
+ color: isFinished
+ ? cs.onSurfaceVariant.withValues(alpha: 0.5)
+ : Colors.white,
+ ),
+ maxLines: 2, overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 4),
+ Row(
+ children: [
+ if (dateLabel.isNotEmpty)
+ Text(dateLabel,
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
+ ),
+ if (dateLabel.isNotEmpty && durationLabel.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 6),
+ child: Text('·',
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ ),
+ if (durationLabel.isNotEmpty)
+ Text(durationLabel,
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
+ ),
+ ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (_, __) {
+ final downloaded = DownloadService().isDownloaded(dlKey);
+ if (!downloaded) return const SizedBox.shrink();
+ return Row(mainAxisSize: MainAxisSize.min, children: [
+ const SizedBox(width: 6),
+ Icon(Icons.download_done_rounded, size: 12, color: cs.primary.withValues(alpha: 0.6)),
+ ]);
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+
+ // Action buttons
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Download button (reactive)
+ ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (_, __) {
+ final dl = DownloadService();
+ final downloaded = dl.isDownloaded(dlKey);
+ final downloading = dl.isDownloading(dlKey);
+ final dlProgress = dl.downloadProgress(dlKey);
+
+ if (downloaded) {
+ return Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(Icons.download_done_rounded, size: 20,
+ color: Colors.greenAccent.withValues(alpha: 0.7)),
+ );
+ }
+ if (downloading) {
+ return Padding(
+ padding: const EdgeInsets.all(8),
+ child: SizedBox(width: 20, height: 20,
+ child: Stack(alignment: Alignment.center, children: [
+ CircularProgressIndicator(
+ value: dlProgress > 0 ? dlProgress : null,
+ strokeWidth: 2, color: cs.primary),
+ Text('${(dlProgress * 100).toStringAsFixed(0)}',
+ style: TextStyle(fontSize: 7, color: cs.primary, fontWeight: FontWeight.w600)),
+ ])),
+ );
+ }
+ return IconButton(
+ onPressed: widget.onDownload,
+ icon: Icon(Icons.download_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ visualDensity: VisualDensity.compact,
+ constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
+ );
+ },
+ ),
+
+ // Play button
+ IconButton(
+ onPressed: widget.onPlay,
+ icon: Icon(
+ progress > 0 && !isFinished
+ ? Icons.play_circle_filled_rounded
+ : Icons.play_circle_outline_rounded,
+ size: 28,
+ color: cs.primary,
+ ),
+ visualDensity: VisualDensity.compact,
+ constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
+ ),
+ ],
+ ),
+ ],
+ ),
+
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/equalizer_sheet.dart b/lib/widgets/equalizer_sheet.dart
new file mode 100644
index 00000000..ce33a295
--- /dev/null
+++ b/lib/widgets/equalizer_sheet.dart
@@ -0,0 +1,372 @@
+import 'package:flutter/material.dart';
+import '../services/equalizer_service.dart';
+
+/// Show the equalizer & audio enhancements bottom sheet.
+void showEqualizerSheet(BuildContext context, Color accent) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) => DraggableScrollableSheet(
+ expand: false,
+ initialChildSize: 0.75,
+ minChildSize: 0.5,
+ maxChildSize: 0.92,
+ builder: (ctx, sc) => _EqualizerSheetContent(accent: accent, scrollController: sc),
+ ),
+ );
+}
+
+class _EqualizerSheetContent extends StatefulWidget {
+ final Color accent;
+ final ScrollController scrollController;
+ const _EqualizerSheetContent({required this.accent, required this.scrollController});
+
+ @override
+ State<_EqualizerSheetContent> createState() => _EqualizerSheetContentState();
+}
+
+class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
+ final _eq = EqualizerService();
+
+ @override
+ void initState() {
+ super.initState();
+ _eq.addListener(_rebuild);
+ // Ensure EQ is initialized
+ if (!_eq.available) _eq.init();
+ }
+
+ @override
+ void dispose() {
+ _eq.removeListener(_rebuild);
+ super.dispose();
+ }
+
+ void _rebuild() {
+ if (mounted) setState(() {});
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final accent = widget.accent;
+
+ return Container(
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: Column(
+ children: [
+ // Drag handle
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Container(
+ width: 40, height: 4,
+ decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)),
+ ),
+ ),
+ // Header with toggle
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(
+ children: [
+ Icon(Icons.equalizer_rounded, size: 22, color: accent),
+ const SizedBox(width: 10),
+ Text('Audio Enhancements', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const Spacer(),
+ // Master toggle
+ Transform.scale(
+ scale: 0.8,
+ child: Switch(
+ value: _eq.enabled,
+ activeColor: accent,
+ onChanged: (v) => _eq.setEnabled(v),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 4),
+ // Content
+ Expanded(
+ child: ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ children: [
+ const SizedBox(height: 8),
+ // ── Presets ──
+ Text('PRESETS', style: tt.labelSmall?.copyWith(
+ color: Colors.white30, letterSpacing: 1.5, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 10),
+ Wrap(
+ spacing: 8, runSpacing: 8,
+ children: EqualizerService.presets.keys.map((name) {
+ final isActive = _eq.activePreset == name;
+ return GestureDetector(
+ onTap: _eq.enabled ? () => _eq.applyPreset(name) : null,
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 150),
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+ decoration: BoxDecoration(
+ color: isActive ? accent.withValues(alpha: 0.2) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(
+ color: isActive ? accent.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.1),
+ ),
+ ),
+ child: Text(
+ name[0].toUpperCase() + name.substring(1),
+ style: TextStyle(
+ color: _eq.enabled
+ ? (isActive ? accent : Colors.white70)
+ : Colors.white24,
+ fontSize: 12,
+ fontWeight: isActive ? FontWeight.w700 : FontWeight.w500,
+ ),
+ ),
+ ),
+ );
+ }).toList(),
+ ),
+ if (_eq.activePreset == 'custom')
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: GestureDetector(
+ onTap: _eq.enabled ? () => _eq.applyPreset('flat') : null,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+ decoration: BoxDecoration(
+ color: accent.withValues(alpha: 0.2),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: accent.withValues(alpha: 0.5)),
+ ),
+ child: Text('Custom', style: TextStyle(
+ color: accent, fontSize: 12, fontWeight: FontWeight.w700)),
+ ),
+ ),
+ ),
+ const SizedBox(height: 20),
+
+ // ── EQ Bands ──
+ Text('EQUALIZER', style: tt.labelSmall?.copyWith(
+ color: Colors.white30, letterSpacing: 1.5, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ SizedBox(
+ height: 200,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: List.generate(_eq.bandLevels.length, (i) {
+ return Expanded(
+ child: _EQBandSlider(
+ frequency: i < _eq.bandFrequencies.length ? _eq.bandFrequencies[i] : 0,
+ level: _eq.bandLevels[i],
+ minLevel: _eq.minLevel,
+ maxLevel: _eq.maxLevel,
+ accent: accent,
+ enabled: _eq.enabled,
+ onChanged: (v) => _eq.setBandLevel(i, v),
+ ),
+ );
+ }),
+ ),
+ ),
+ const SizedBox(height: 20),
+
+ // ── Audio Effects ──
+ Text('EFFECTS', style: tt.labelSmall?.copyWith(
+ color: Colors.white30, letterSpacing: 1.5, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+
+ // Bass Boost
+ _EffectRow(
+ icon: Icons.speaker_rounded,
+ label: 'Bass Boost',
+ value: _eq.bassBoost,
+ accent: accent,
+ enabled: _eq.enabled,
+ onChanged: (v) => _eq.setBassBoost(v),
+ ),
+ const SizedBox(height: 8),
+
+ // Virtualizer
+ _EffectRow(
+ icon: Icons.surround_sound_rounded,
+ label: 'Surround',
+ value: _eq.virtualizer,
+ accent: accent,
+ enabled: _eq.enabled,
+ onChanged: (v) => _eq.setVirtualizer(v),
+ ),
+ const SizedBox(height: 8),
+
+ // Loudness
+ _EffectRow(
+ icon: Icons.volume_up_rounded,
+ label: 'Loudness',
+ value: _eq.loudnessGain,
+ accent: accent,
+ enabled: _eq.enabled,
+ onChanged: (v) => _eq.setLoudnessGain(v),
+ ),
+
+ const SizedBox(height: 20),
+
+ // Reset button
+ Center(
+ child: TextButton.icon(
+ onPressed: _eq.enabled ? () => _eq.resetAll() : null,
+ icon: Icon(Icons.refresh_rounded, size: 18,
+ color: _eq.enabled ? Colors.white38 : Colors.white12),
+ label: Text('Reset All', style: TextStyle(
+ color: _eq.enabled ? Colors.white38 : Colors.white12,
+ fontSize: 13)),
+ ),
+ ),
+ const SizedBox(height: 24),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+// ── EQ Band Vertical Slider ──
+
+class _EQBandSlider extends StatelessWidget {
+ final int frequency;
+ final double level;
+ final double minLevel;
+ final double maxLevel;
+ final Color accent;
+ final bool enabled;
+ final ValueChanged<double> onChanged;
+
+ const _EQBandSlider({
+ required this.frequency,
+ required this.level,
+ required this.minLevel,
+ required this.maxLevel,
+ required this.accent,
+ required this.enabled,
+ required this.onChanged,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final eq = EqualizerService();
+ final label = eq.freqLabel(frequency);
+ final normalized = ((level - minLevel) / (maxLevel - minLevel)).clamp(0.0, 1.0);
+
+ return Column(
+ children: [
+ Text('${level >= 0 ? "+" : ""}${level.toStringAsFixed(0)}',
+ style: TextStyle(
+ color: enabled ? Colors.white54 : Colors.white.withValues(alpha: 0.2),
+ fontSize: 10, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Expanded(
+ child: RotatedBox(
+ quarterTurns: 3,
+ child: SliderTheme(
+ data: SliderThemeData(
+ trackHeight: 4,
+ thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 7),
+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 14),
+ activeTrackColor: enabled ? accent : Colors.white24,
+ inactiveTrackColor: Colors.white.withValues(alpha: 0.08),
+ thumbColor: enabled ? accent : Colors.white30,
+ overlayColor: accent.withValues(alpha: 0.15),
+ ),
+ child: Slider(
+ value: level,
+ min: minLevel,
+ max: maxLevel,
+ onChanged: enabled ? onChanged : null,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(label, style: TextStyle(
+ color: enabled ? Colors.white38 : Colors.white.withValues(alpha: 0.15),
+ fontSize: 10, fontWeight: FontWeight.w500)),
+ ],
+ );
+ }
+}
+
+// ── Effect Row with slider ──
+
+class _EffectRow extends StatelessWidget {
+ final IconData icon;
+ final String label;
+ final double value;
+ final Color accent;
+ final bool enabled;
+ final ValueChanged<double> onChanged;
+
+ const _EffectRow({
+ required this.icon,
+ required this.label,
+ required this.value,
+ required this.accent,
+ required this.enabled,
+ required this.onChanged,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Row(
+ children: [
+ Icon(icon, size: 18, color: enabled ? accent.withValues(alpha: 0.7) : Colors.white.withValues(alpha: 0.2)),
+ const SizedBox(width: 10),
+ SizedBox(
+ width: 72,
+ child: Text(label, style: TextStyle(
+ color: enabled ? Colors.white70 : Colors.white24,
+ fontSize: 12, fontWeight: FontWeight.w500)),
+ ),
+ Expanded(
+ child: SliderTheme(
+ data: SliderThemeData(
+ trackHeight: 3,
+ thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
+ activeTrackColor: enabled ? accent : Colors.white24,
+ inactiveTrackColor: Colors.white.withValues(alpha: 0.06),
+ thumbColor: enabled ? accent : Colors.white30,
+ overlayColor: accent.withValues(alpha: 0.15),
+ ),
+ child: Slider(
+ value: value,
+ min: 0.0,
+ max: 1.0,
+ onChanged: enabled ? onChanged : null,
+ ),
+ ),
+ ),
+ SizedBox(
+ width: 32,
+ child: Text('${(value * 100).round()}%',
+ textAlign: TextAlign.right,
+ style: TextStyle(
+ color: enabled ? Colors.white38 : Colors.white.withValues(alpha: 0.15),
+ fontSize: 11, fontWeight: FontWeight.w600)),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dart
new file mode 100644
index 00000000..625854ed
--- /dev/null
+++ b/lib/widgets/home_section.dart
@@ -0,0 +1,307 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+import 'book_card.dart';
+import 'author_card.dart';
+import 'series_card.dart';
+import 'episode_list_sheet.dart';
+
+class HomeSection extends StatelessWidget {
+ final String title;
+ final IconData icon;
+ final List<dynamic> entities;
+ final String sectionType;
+ final String sectionId;
+
+ const HomeSection({
+ super.key,
+ required this.title,
+ required this.icon,
+ required this.entities,
+ required this.sectionType,
+ required this.sectionId,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final isContinueListening = sectionId == 'continue-listening';
+ final isAuthorSection = sectionType == 'author' || sectionType == 'authors';
+ final isSeriesSection = sectionType == 'series';
+ final isEpisodeSection = sectionType == 'episode';
+
+ // Check if any entities have recentEpisode (podcast episode sections)
+ final hasEpisodeEntities = !isEpisodeSection && entities.isNotEmpty &&
+ entities.first is Map<String, dynamic> &&
+ (entities.first as Map<String, dynamic>)['recentEpisode'] != null;
+ final effectiveEpisode = isEpisodeSection || hasEpisodeEntities;
+
+ final double cardWidth =
+ isContinueListening ? 300 : (isAuthorSection ? 120 : 140);
+ final double cardHeight =
+ isContinueListening ? 120 : effectiveEpisode ? 200 : (isAuthorSection ? 170 : 200);
+
+ return Padding(
+ padding: const EdgeInsets.only(top: 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Section header
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(
+ children: [
+ Icon(icon, size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Text(
+ title,
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface.withValues(alpha: 0.8),
+ letterSpacing: 0.3,
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Container(
+ height: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.2),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 12),
+
+ // Snap-scrolling horizontal list
+ SizedBox(
+ height: cardHeight,
+ child: _SnapScrollList(
+ cardWidth: cardWidth,
+ itemCount: entities.length,
+ itemBuilder: (context, index) {
+ final entity = entities[index];
+
+ if (isAuthorSection) {
+ return SizedBox(
+ width: cardWidth,
+ child: AuthorCard(author: entity),
+ );
+ }
+
+ if (isSeriesSection) {
+ return SizedBox(
+ width: cardWidth,
+ child: SeriesCard(series: entity),
+ );
+ }
+
+ // Podcast episode sections — show cover with episode title overlay
+ if (isEpisodeSection && entity is Map<String, dynamic>) {
+ return SizedBox(
+ width: cardWidth,
+ child: _EpisodeCard(item: entity),
+ );
+ }
+
+ // If entity has recentEpisode (podcast continue-listening etc),
+ // use episode card even if section type isn't explicitly 'episode'
+ if (entity is Map<String, dynamic> &&
+ entity['recentEpisode'] != null) {
+ return SizedBox(
+ width: cardWidth,
+ child: _EpisodeCard(item: entity),
+ );
+ }
+
+ return SizedBox(
+ width: cardWidth,
+ child: BookCard(
+ item: entity,
+ showProgress: isContinueListening,
+ isWide: isContinueListening,
+ ),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// A horizontal scrolling list with smooth snap-to-card behavior.
+class _SnapScrollList extends StatefulWidget {
+ final double cardWidth;
+ final int itemCount;
+ final Widget Function(BuildContext, int) itemBuilder;
+
+ const _SnapScrollList({
+ required this.cardWidth,
+ required this.itemCount,
+ required this.itemBuilder,
+ });
+
+ @override
+ State<_SnapScrollList> createState() => _SnapScrollListState();
+}
+
+class _SnapScrollListState extends State<_SnapScrollList> {
+ late final ScrollController _controller;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller = ScrollController();
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final itemExtent = widget.cardWidth + 12;
+
+ return NotificationListener<ScrollEndNotification>(
+ onNotification: (notification) {
+ final offset = _controller.offset;
+ final targetIndex = (offset / itemExtent).round();
+ final targetOffset =
+ (targetIndex * itemExtent).clamp(0.0, _controller.position.maxScrollExtent);
+ if ((offset - targetOffset).abs() > 1) {
+ Future.microtask(() {
+ if (_controller.hasClients) {
+ _controller.animateTo(
+ targetOffset,
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeOutCubic,
+ );
+ }
+ });
+ }
+ return false;
+ },
+ child: ListView.separated(
+ controller: _controller,
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ physics: const BouncingScrollPhysics(),
+ itemCount: widget.itemCount,
+ separatorBuilder: (_, __) => const SizedBox(width: 12),
+ itemBuilder: widget.itemBuilder,
+ ),
+ );
+ }
+}
+
+/// Card for episodes in podcast sections (e.g. episodes-recently-added).
+/// Shows the show cover with the episode title overlaid at the bottom.
+class _EpisodeCard extends StatelessWidget {
+ final Map<String, dynamic> item;
+
+ const _EpisodeCard({required this.item});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ final itemId = item['id'] as String? ?? '';
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final showTitle = metadata['title'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+
+ // Get episode info from recentEpisode
+ final episode = item['recentEpisode'] as Map<String, dynamic>?;
+ final episodeTitle = episode?['title'] as String? ?? showTitle;
+
+ return GestureDetector(
+ onTap: () {
+ if (episode != null) {
+ EpisodeDetailSheet.show(context, item, episode);
+ } else {
+ EpisodeListSheet.show(context, item);
+ }
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Square cover
+ AspectRatio(
+ aspectRatio: 1,
+ child: Card(
+ elevation: 0,
+ margin: EdgeInsets.zero,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ if (coverUrl != null)
+ coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => Container(
+ color: cs.surfaceContainerHigh,
+ child: Icon(Icons.podcasts_rounded, size: 32,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3))))
+ : Image.network(coverUrl, fit: BoxFit.cover,
+ headers: lib.mediaHeaders,
+ errorBuilder: (_, __, ___) => Container(
+ color: cs.surfaceContainerHigh,
+ child: Icon(Icons.podcasts_rounded, size: 32,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3))))
+ else
+ Container(
+ color: cs.surfaceContainerHigh,
+ child: Icon(Icons.podcasts_rounded, size: 32,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 6),
+ // Episode title
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ episodeTitle,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelMedium?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface,
+ ),
+ ),
+ ),
+ // Show name
+ if (showTitle.isNotEmpty && episode != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ showTitle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
\ No newline at end of file
diff --git a/lib/widgets/library_selector.dart b/lib/widgets/library_selector.dart
new file mode 100644
index 00000000..9b12b7fe
--- /dev/null
+++ b/lib/widgets/library_selector.dart
@@ -0,0 +1,110 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+
+/// Maps Audiobookshelf server library icon names to Material Icons.
+/// ABS uses Material Symbols names as its icon identifiers.
+IconData _absIconToMaterial(String? icon, String? mediaType) {
+ switch (icon) {
+ case 'audiobookshelf':
+ return Icons.headphones_rounded;
+ case 'database':
+ return Icons.storage_rounded;
+ case 'podcast':
+ return Icons.podcasts_rounded;
+ case 'book-open':
+ return Icons.menu_book_rounded;
+ case 'music':
+ return Icons.music_note_rounded;
+ case 'radio':
+ return Icons.radio_rounded;
+ case 'book-2': // alternate book icon in some ABS versions
+ return Icons.auto_stories_rounded;
+ case 'hat-wizard':
+ return Icons.auto_fix_high_rounded;
+ case 'atom':
+ return Icons.science_rounded;
+ case 'rocket':
+ return Icons.rocket_launch_rounded;
+ case 'microphone':
+ case 'microphone-alt':
+ return Icons.mic_rounded;
+ default:
+ // Fallback based on media type
+ return mediaType == 'podcast'
+ ? Icons.podcasts_rounded
+ : Icons.auto_stories_rounded;
+ }
+}
+
+class LibrarySelectorButton extends StatelessWidget {
+ const LibrarySelectorButton({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return IconButton(
+ icon: const Icon(Icons.swap_horiz_rounded),
+ tooltip: 'Switch library',
+ onPressed: () => _showLibraryPicker(context),
+ );
+ }
+
+ void _showLibraryPicker(BuildContext context) {
+ final lib = context.read<LibraryProvider>();
+ final cs = Theme.of(context).colorScheme;
+
+ showModalBottomSheet(
+ context: context,
+ showDragHandle: true,
+ builder: (ctx) {
+ return SafeArea(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
+ child: Text(
+ 'Select Library',
+ style: Theme.of(context).textTheme.titleLarge?.copyWith(
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ ...lib.libraries
+ .map((library) {
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? 'Library';
+ final icon = library['icon'] as String?;
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+
+ return ListTile(
+ leading: Icon(
+ _absIconToMaterial(icon, mediaType),
+ color: isSelected ? cs.primary : cs.onSurfaceVariant,
+ ),
+ title: Text(name),
+ trailing: isSelected
+ ? Icon(Icons.check_circle_rounded,
+ color: cs.primary)
+ : null,
+ selected: isSelected,
+ onTap: () {
+ Navigator.pop(ctx);
+ if (!isSelected) {
+ lib.selectLibrary(id);
+ }
+ },
+ );
+ }),
+ const SizedBox(height: 16),
+ ],
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/metadata_lookup_sheet.dart b/lib/widgets/metadata_lookup_sheet.dart
new file mode 100644
index 00000000..de9e2c06
--- /dev/null
+++ b/lib/widgets/metadata_lookup_sheet.dart
@@ -0,0 +1,542 @@
+import 'dart:async';
+import 'package:flutter/material.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../services/api_service.dart';
+import '../services/metadata_override_service.dart';
+
+/// Bottom sheet that lets users search for book metadata via the ABS server
+/// and pick a result to store as a local override.
+class MetadataLookupSheet extends StatefulWidget {
+ final String itemId;
+ final ApiService api;
+ final String initialTitle;
+ final String initialAuthor;
+ final VoidCallback onApplied;
+
+ const MetadataLookupSheet({
+ super.key,
+ required this.itemId,
+ required this.api,
+ required this.initialTitle,
+ required this.initialAuthor,
+ required this.onApplied,
+ });
+
+ @override
+ State<MetadataLookupSheet> createState() => _MetadataLookupSheetState();
+}
+
+class _MetadataLookupSheetState extends State<MetadataLookupSheet> {
+ final _titleController = TextEditingController();
+ final _authorController = TextEditingController();
+ List<Map<String, dynamic>> _results = [];
+ bool _isSearching = false;
+ bool _hasSearched = false;
+ String _provider = 'audible';
+ Timer? _debounce;
+
+ static const _providers = [
+ ('audible', 'Audible'),
+ ('itunes', 'iTunes'),
+ ('openlibrary', 'Open Library'),
+ ];
+
+ @override
+ void initState() {
+ super.initState();
+ _titleController.text = widget.initialTitle;
+ _authorController.text = widget.initialAuthor;
+ // Auto-search on open
+ if (widget.initialTitle.isNotEmpty) {
+ Future.delayed(const Duration(milliseconds: 300), _doSearch);
+ }
+ }
+
+ @override
+ void dispose() {
+ _debounce?.cancel();
+ _titleController.dispose();
+ _authorController.dispose();
+ super.dispose();
+ }
+
+ Future<void> _doSearch() async {
+ final title = _titleController.text.trim();
+ if (title.isEmpty) return;
+
+ setState(() {
+ _isSearching = true;
+ _hasSearched = true;
+ });
+
+ final results = await widget.api.searchBooks(
+ title: title,
+ author: _authorController.text.trim(),
+ provider: _provider,
+ );
+
+ if (mounted) {
+ setState(() {
+ _results = results;
+ _isSearching = false;
+ });
+ }
+ }
+
+ Future<void> _applyResult(Map<String, dynamic> result) async {
+ final book = result['book'] as Map<String, dynamic>? ?? result;
+
+ final override = <String, dynamic>{};
+
+ void addIfPresent(String overrideKey, dynamic value) {
+ final str = _safeString(value);
+ if (str.isNotEmpty) {
+ override[overrideKey] = str;
+ }
+ }
+
+ addIfPresent('title', book['title']);
+ addIfPresent('author', book['author'] ?? book['authorName']);
+ addIfPresent('narrator', book['narrator'] ?? book['narratorName']);
+ addIfPresent('description', book['description']);
+ addIfPresent('publisher', book['publisher']);
+ addIfPresent('publishedYear', book['publishedYear'] ?? book['publishedDate']);
+ addIfPresent('asin', book['asin']);
+ addIfPresent('isbn', book['isbn']);
+
+ // Cover — use raw string value
+ final coverRaw = book['cover'] ?? book['image'];
+ if (coverRaw is String && coverRaw.isNotEmpty) {
+ override['coverUrl'] = coverRaw;
+ }
+
+ // Genres/tags
+ final genres = book['genres'] ?? book['tags'];
+ if (genres is List && genres.isNotEmpty) {
+ override['genres'] = genres;
+ }
+
+ // Series — can be a String, List, or nested object
+ final series = book['series'];
+ if (series is List && series.isNotEmpty) {
+ override['series'] = series;
+ } else if (series is String && series.isNotEmpty) {
+ override['series'] = [
+ {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}
+ ];
+ }
+
+ await MetadataOverrideService().save(widget.itemId, override);
+
+ if (mounted) {
+ widget.onApplied();
+ Navigator.pop(context);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: const Text('Metadata saved locally'),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Container(
+ decoration: const BoxDecoration(
+ color: Color(0xFF1A1A1A),
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(
+ children: [
+ // Drag handle
+ Center(
+ child: Container(
+ width: 40,
+ height: 4,
+ margin: const EdgeInsets.only(top: 12, bottom: 8),
+ decoration: BoxDecoration(
+ color: Colors.white24,
+ borderRadius: BorderRadius.circular(2),
+ ),
+ ),
+ ),
+
+ // Header
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 4, 20, 12),
+ child: Row(
+ children: [
+ Icon(Icons.manage_search_rounded, size: 22, color: cs.primary),
+ const SizedBox(width: 8),
+ Text('Lookup Metadata',
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: Colors.white)),
+ ],
+ ),
+ ),
+
+ // Search fields
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Column(
+ children: [
+ _buildField(
+ controller: _titleController,
+ label: 'Title',
+ icon: Icons.book_rounded,
+ cs: cs,
+ onSubmitted: (_) => _doSearch(),
+ ),
+ const SizedBox(height: 8),
+ _buildField(
+ controller: _authorController,
+ label: 'Author (optional)',
+ icon: Icons.person_rounded,
+ cs: cs,
+ onSubmitted: (_) => _doSearch(),
+ ),
+ const SizedBox(height: 10),
+ Row(
+ children: [
+ // Provider selector
+ Expanded(
+ child: Container(
+ height: 40,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(
+ color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ child: DropdownButtonHideUnderline(
+ child: DropdownButton<String>(
+ value: _provider,
+ isExpanded: true,
+ dropdownColor: const Color(0xFF2A2A2A),
+ style: tt.bodySmall
+ ?.copyWith(color: Colors.white70),
+ icon: Icon(Icons.expand_more_rounded,
+ size: 18, color: Colors.white38),
+ items: _providers.map((p) {
+ return DropdownMenuItem(
+ value: p.$1,
+ child: Text(p.$2),
+ );
+ }).toList(),
+ onChanged: (v) {
+ if (v != null) setState(() => _provider = v);
+ },
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ // Search button
+ SizedBox(
+ height: 40,
+ child: FilledButton.icon(
+ onPressed: _isSearching ? null : _doSearch,
+ icon: _isSearching
+ ? SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ strokeWidth: 2, color: cs.onPrimary),
+ )
+ : const Icon(Icons.search_rounded, size: 18),
+ label: const Text('Search'),
+ style: FilledButton.styleFrom(
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 12),
+ Divider(color: Colors.white.withValues(alpha: 0.08), height: 1),
+
+ // Results
+ Expanded(
+ child: _isSearching
+ ? const Center(
+ child: CircularProgressIndicator(
+ strokeWidth: 2, color: Colors.white24))
+ : _results.isEmpty
+ ? Center(
+ child: Text(
+ _hasSearched
+ ? 'No results found.\nTry adjusting your search or provider.'
+ : 'Search for metadata above',
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium
+ ?.copyWith(color: Colors.white38),
+ ),
+ )
+ : ListView.separated(
+ padding: EdgeInsets.fromLTRB(
+ 16,
+ 12,
+ 16,
+ 16 +
+ MediaQuery.of(context)
+ .viewPadding
+ .bottom),
+ itemCount: _results.length,
+ separatorBuilder: (_, __) =>
+ const SizedBox(height: 8),
+ itemBuilder: (context, index) {
+ return _buildResultCard(
+ _results[index], cs, tt);
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildField({
+ required TextEditingController controller,
+ required String label,
+ required IconData icon,
+ required ColorScheme cs,
+ void Function(String)? onSubmitted,
+ }) {
+ return SizedBox(
+ height: 44,
+ child: TextField(
+ controller: controller,
+ onSubmitted: onSubmitted,
+ textInputAction: TextInputAction.search,
+ style: const TextStyle(color: Colors.white, fontSize: 14),
+ decoration: InputDecoration(
+ labelText: label,
+ labelStyle: TextStyle(
+ color: Colors.white38, fontSize: 13),
+ prefixIcon: Icon(icon, size: 18, color: Colors.white30),
+ filled: true,
+ fillColor: Colors.white.withValues(alpha: 0.06),
+ contentPadding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide(
+ color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide(
+ color: Colors.white.withValues(alpha: 0.08)),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide:
+ BorderSide(color: cs.primary.withValues(alpha: 0.5)),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// Safely extract a string from a value that might be a String, List, or other type.
+ String _safeString(dynamic value) {
+ if (value == null) return '';
+ if (value is String) return value;
+ if (value is List) return value.whereType<String>().join(', ');
+ return value.toString();
+ }
+
+ Widget _buildResultCard(
+ Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {
+ final book = result['book'] as Map<String, dynamic>? ?? result;
+ final title = _safeString(book['title']);
+ final author = _safeString(book['author']).isNotEmpty
+ ? _safeString(book['author'])
+ : _safeString(book['authorName']);
+ final narrator = _safeString(book['narrator']).isNotEmpty
+ ? _safeString(book['narrator'])
+ : _safeString(book['narratorName']);
+ final desc = _safeString(book['description'])
+ .replaceAll(RegExp(r'<[^>]*>'), '')
+ .trim();
+ final cover = _safeString(book['cover']).isNotEmpty
+ ? _safeString(book['cover'])
+ : _safeString(book['image']);
+ final year = _safeString(book['publishedYear']).isNotEmpty
+ ? _safeString(book['publishedYear'])
+ : _safeString(book['publishedDate']);
+ final publisher = _safeString(book['publisher']);
+ final series = _safeString(book['series']);
+
+ // Match confidence from Audible provider
+ final matchKey = result['matchKey'] as String?;
+
+ return Card(
+ elevation: 0,
+ color: Colors.white.withValues(alpha: 0.05),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14),
+ side: BorderSide(color: Colors.white.withValues(alpha: 0.06)),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _showConfirmation(result, cs, tt),
+ borderRadius: BorderRadius.circular(14),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Cover thumbnail
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: SizedBox(
+ width: 60,
+ height: 60,
+ child: cover.isNotEmpty
+ ? CachedNetworkImage(
+ imageUrl: cover,
+ fit: BoxFit.cover,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ )
+ : _placeholder(cs),
+ ),
+ ),
+ const SizedBox(width: 12),
+ // Info
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: Colors.white)),
+ if (author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall
+ ?.copyWith(color: Colors.white60)),
+ ],
+ if (narrator.isNotEmpty) ...[
+ const SizedBox(height: 1),
+ Text('Narrated by $narrator',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall
+ ?.copyWith(color: Colors.white38)),
+ ],
+ const SizedBox(height: 4),
+ Wrap(
+ spacing: 6,
+ runSpacing: 4,
+ children: [
+ if (year.isNotEmpty)
+ _miniChip(Icons.calendar_today_rounded, year),
+ if (publisher.isNotEmpty)
+ _miniChip(Icons.business_rounded, publisher),
+ if (series.isNotEmpty)
+ _miniChip(Icons.auto_stories_rounded, series),
+ ],
+ ),
+ if (desc.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(desc,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: Colors.white30, height: 1.3)),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 4),
+ Icon(Icons.chevron_right_rounded,
+ size: 20, color: Colors.white24),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ void _showConfirmation(
+ Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {
+ final book = result['book'] as Map<String, dynamic>? ?? result;
+ final title = book['title'] as String? ?? 'Unknown';
+ final author =
+ book['author'] as String? ?? book['authorName'] as String? ?? '';
+
+ showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Apply This Metadata?'),
+ content: Text(
+ 'This will fill in any missing metadata for this book using:\n\n'
+ '"$title"${author.isNotEmpty ? ' by $author' : ''}\n\n'
+ 'Only empty fields will be filled — existing server data won\'t be overwritten. '
+ 'This is stored locally on your device.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () {
+ Navigator.pop(ctx);
+ _applyResult(result);
+ },
+ child: const Text('Apply')),
+ ],
+ ),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.headphones_rounded,
+ size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ );
+ }
+
+ Widget _miniChip(IconData icon, String text) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 10, color: Colors.white30),
+ const SizedBox(width: 3),
+ Flexible(
+ child: Text(text,
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ style: const TextStyle(
+ color: Colors.white38, fontSize: 10)),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/series_card.dart b/lib/widgets/series_card.dart
new file mode 100644
index 00000000..7fa7e57d
--- /dev/null
+++ b/lib/widgets/series_card.dart
@@ -0,0 +1,100 @@
+import 'package:flutter/material.dart';
+
+class SeriesCard extends StatelessWidget {
+ final Map<String, dynamic> series;
+
+ const SeriesCard({super.key, required this.series});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ final name = series['name'] as String? ?? 'Unknown Series';
+ final books = series['books'] as List<dynamic>? ?? [];
+ final bookCount = books.length;
+
+ return Card(
+ elevation: 0,
+ color: cs.tertiaryContainer.withValues(alpha: 0.4),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () {},
+ borderRadius: BorderRadius.circular(12),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ // Stacked book spines visual effect
+ Column(
+ children: [
+ Expanded(
+ child: Container(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ colors: [
+ cs.tertiaryContainer,
+ cs.tertiaryContainer.withValues(alpha: 0.6),
+ ],
+ ),
+ ),
+ child: Center(
+ child: Icon(
+ Icons.library_books_rounded,
+ size: 40,
+ color: cs.onTertiaryContainer.withValues(alpha: 0.5),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ // Info overlay at bottom
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.all(10),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [
+ Colors.transparent,
+ cs.surface.withValues(alpha: 0.9),
+ ],
+ ),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ name,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ '$bookCount book${bookCount != 1 ? 's' : ''}',
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/shimmer.dart b/lib/widgets/shimmer.dart
new file mode 100644
index 00000000..a963b5e4
--- /dev/null
+++ b/lib/widgets/shimmer.dart
@@ -0,0 +1,98 @@
+import 'package:flutter/material.dart';
+
+/// A shimmer loading placeholder that pulses.
+class ShimmerBox extends StatefulWidget {
+ final double width;
+ final double height;
+ final double borderRadius;
+
+ const ShimmerBox({
+ super.key,
+ required this.width,
+ required this.height,
+ this.borderRadius = 12,
+ });
+
+ @override
+ State<ShimmerBox> createState() => _ShimmerBoxState();
+}
+
+class _ShimmerBoxState extends State<ShimmerBox>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _controller;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1200),
+ )..repeat(reverse: true);
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ return FadeTransition(
+ opacity: Tween<double>(begin: 0.4, end: 1.0).animate(
+ CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
+ ),
+ child: Container(
+ width: widget.width,
+ height: widget.height,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(widget.borderRadius),
+ color: cs.surfaceContainerHighest,
+ ),
+ ),
+ );
+ }
+}
+
+/// Shimmer placeholder for a row of book cards.
+class ShimmerBookRow extends StatelessWidget {
+ const ShimmerBookRow({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const ShimmerBox(width: 140, height: 18, borderRadius: 6),
+ const SizedBox(height: 12),
+ SizedBox(
+ height: 150,
+ child: ListView.separated(
+ scrollDirection: Axis.horizontal,
+ physics: const NeverScrollableScrollPhysics(),
+ itemCount: 4,
+ separatorBuilder: (_, __) => const SizedBox(width: 10),
+ itemBuilder: (_, __) => const ShimmerBox(width: 110, height: 150),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Shimmer placeholder for hero cards.
+class ShimmerHeroCard extends StatelessWidget {
+ const ShimmerHeroCard({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return const Padding(
+ padding: EdgeInsets.symmetric(horizontal: 16),
+ child: ShimmerBox(width: double.infinity, height: 220, borderRadius: 18),
+ );
+ }
+}
diff --git a/lib/widgets/sleep_timer_sheet.dart b/lib/widgets/sleep_timer_sheet.dart
new file mode 100644
index 00000000..c4490ed7
--- /dev/null
+++ b/lib/widgets/sleep_timer_sheet.dart
@@ -0,0 +1,353 @@
+import 'dart:ui';
+import 'package:flutter/material.dart';
+import '../services/audio_player_service.dart';
+import '../services/sleep_timer_service.dart';
+
+// ─── SHARED SLEEP TIMER SHEET ─────────────────────────────────
+void showSleepTimerSheet(BuildContext context, Color accent) {
+ showModalBottomSheet(
+ context: context, backgroundColor: Colors.transparent,
+ isScrollControlled: true,
+ useSafeArea: true,
+ builder: (ctx) => SleepTimerSheet(accent: accent),
+ );
+}
+
+class SleepTimerSheet extends StatefulWidget {
+ final Color accent;
+ const SleepTimerSheet({super.key, required this.accent});
+ @override State<SleepTimerSheet> createState() => _SleepTimerSheetState();
+}
+
+class _SleepTimerSheetState extends State<SleepTimerSheet> {
+ int _tabIndex = 0; // 0 = Timer, 1 = End of Chapter
+ double _customMinutes = 30;
+ int _customChapters = 1;
+ bool _shakeEnabled = true;
+ int _shakeAddMinutes = 5;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadShakeSettings();
+ }
+
+ Future<void> _loadShakeSettings() async {
+ final shake = await PlayerSettings.getShakeToResetSleep();
+ final mins = await PlayerSettings.getShakeAddMinutes();
+ if (mounted) setState(() { _shakeEnabled = shake; _shakeAddMinutes = mins; });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ final accent = widget.accent;
+
+ return ListenableBuilder(
+ listenable: SleepTimerService(),
+ builder: (_, __) {
+ final sleep = SleepTimerService();
+ final isActive = sleep.isActive;
+
+ final navBarPad = MediaQuery.of(context).viewPadding.bottom;
+
+ return Container(
+ padding: EdgeInsets.fromLTRB(20, 16, 20, 24 + navBarPad),
+ decoration: BoxDecoration(
+ color: const Color(0xFF1A1A1A),
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),
+ ),
+ child: SingleChildScrollView(
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
+ const SizedBox(height: 16),
+ Text('Sleep Timer', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
+ const SizedBox(height: 16),
+
+ if (isActive)
+ _buildActiveState(sleep, accent, tt)
+ else ...[
+ // Tab bar
+ Container(
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ padding: const EdgeInsets.all(3),
+ child: Row(children: [
+ _tab('Timer', Icons.timer_outlined, 0, accent),
+ const SizedBox(width: 4),
+ _tab('End of Chapter', Icons.auto_stories_outlined, 1, accent),
+ ]),
+ ),
+ const SizedBox(height: 20),
+
+ // Tab content
+ if (_tabIndex == 0) _buildTimerTab(accent, tt)
+ else _buildChapterTab(accent, tt),
+
+ const SizedBox(height: 16),
+ Container(height: 0.5, color: Colors.white.withValues(alpha: 0.08)),
+ const SizedBox(height: 12),
+
+ // Shake toggle
+ _buildShakeToggle(accent, tt),
+ ],
+ ]),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildActiveState(SleepTimerService sleep, Color accent, TextTheme tt) {
+ final isTime = sleep.mode == SleepTimerMode.time;
+
+ String countdownLabel;
+ if (isTime) {
+ final r = sleep.timeRemaining;
+ final m = r.inMinutes;
+ final s = r.inSeconds % 60;
+ countdownLabel = '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ } else {
+ countdownLabel = '${sleep.chaptersRemaining} ${sleep.chaptersRemaining == 1 ? 'chapter' : 'chapters'} left';
+ }
+
+ return Column(children: [
+ // Countdown display
+ if (isTime) ...[
+ Text(countdownLabel,
+ style: TextStyle(color: accent, fontSize: 40, fontWeight: FontWeight.w700,
+ fontFeatures: const [FontFeature.tabularFigures()])),
+ const SizedBox(height: 8),
+ // Progress bar
+ ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: LinearProgressIndicator(
+ value: sleep.timeProgress,
+ minHeight: 4,
+ backgroundColor: Colors.white.withValues(alpha: 0.08),
+ valueColor: AlwaysStoppedAnimation(accent.withValues(alpha: 0.6)),
+ ),
+ ),
+ ] else ...[
+ Icon(Icons.auto_stories_outlined, size: 28, color: accent.withValues(alpha: 0.6)),
+ const SizedBox(height: 8),
+ Text(countdownLabel,
+ style: TextStyle(color: accent, fontSize: 24, fontWeight: FontWeight.w700)),
+ ],
+ const SizedBox(height: 20),
+
+ // Quick add buttons
+ Text('Add more time', style: TextStyle(color: Colors.white38, fontSize: 12)),
+ const SizedBox(height: 10),
+ if (isTime)
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ for (final mins in [5, 10, 15, 30])
+ _presetChip(accent, '+${mins}m', false, () {
+ sleep.addTime(Duration(minutes: mins));
+ }),
+ ])
+ else
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ for (final ch in [1, 2, 3])
+ _presetChip(accent, '+$ch ch', false, () {
+ for (int i = 0; i < ch; i++) sleep.addChapter();
+ }),
+ ]),
+ const SizedBox(height: 20),
+
+ // Cancel button
+ SizedBox(width: double.infinity, height: 44, child: OutlinedButton.icon(
+ icon: const Icon(Icons.close_rounded, size: 18),
+ label: const Text('Cancel timer'),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: Colors.white54,
+ side: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ),
+ onPressed: () {
+ sleep.cancelByUser();
+ Navigator.pop(context);
+ },
+ )),
+
+ const SizedBox(height: 12),
+ Container(height: 0.5, color: Colors.white.withValues(alpha: 0.08)),
+ const SizedBox(height: 12),
+ _buildShakeToggle(accent, tt),
+ ]);
+ }
+
+ Widget _tab(String label, IconData icon, int index, Color accent) {
+ final selected = _tabIndex == index;
+ return Expanded(
+ child: GestureDetector(
+ onTap: () => setState(() => _tabIndex = index),
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ padding: const EdgeInsets.symmetric(vertical: 10),
+ decoration: BoxDecoration(
+ color: selected ? accent.withValues(alpha: 0.2) : Colors.transparent,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 15, color: selected ? accent : Colors.white38),
+ const SizedBox(width: 6),
+ Text(label, style: TextStyle(
+ color: selected ? accent : Colors.white38,
+ fontSize: 12, fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
+ )),
+ ]),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildTimerTab(Color accent, TextTheme tt) {
+ return Column(children: [
+ // Custom slider
+ Text('${_customMinutes.round()} min',
+ style: TextStyle(color: accent, fontSize: 28, fontWeight: FontWeight.w700,
+ fontFeatures: const [FontFeature.tabularFigures()])),
+ const SizedBox(height: 8),
+ SliderTheme(
+ data: SliderThemeData(
+ activeTrackColor: accent,
+ inactiveTrackColor: Colors.white.withValues(alpha: 0.1),
+ thumbColor: accent,
+ overlayColor: accent.withValues(alpha: 0.1),
+ trackHeight: 4,
+ ),
+ child: Slider(
+ value: _customMinutes,
+ min: 1, max: 120, divisions: 119,
+ onChanged: (v) => setState(() => _customMinutes = v),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [
+ Text('1m', style: TextStyle(color: Colors.white30, fontSize: 11)),
+ Text('120m', style: TextStyle(color: Colors.white30, fontSize: 11)),
+ ]),
+ ),
+ const SizedBox(height: 12),
+ // Presets
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ for (final mins in [5, 10, 15, 30, 45, 60])
+ _presetChip(accent, '${mins}m', _customMinutes.round() == mins, () {
+ setState(() => _customMinutes = mins.toDouble());
+ }),
+ ]),
+ const SizedBox(height: 16),
+ // Start button
+ SizedBox(width: double.infinity, height: 44, child: FilledButton(
+ style: FilledButton.styleFrom(backgroundColor: accent, foregroundColor: Colors.black,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
+ onPressed: () {
+ SleepTimerService().setTimeSleep(Duration(minutes: _customMinutes.round()));
+ Navigator.pop(context);
+ },
+ child: Text('Start ${_customMinutes.round()} min timer',
+ style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14)),
+ )),
+ ]);
+ }
+
+ Widget _buildChapterTab(Color accent, TextTheme tt) {
+ return Column(children: [
+ Text('$_customChapters ${_customChapters == 1 ? 'chapter' : 'chapters'}',
+ style: TextStyle(color: accent, fontSize: 28, fontWeight: FontWeight.w700)),
+ const SizedBox(height: 16),
+ // Chapter count selector
+ Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ _circleButton(Icons.remove_rounded, accent, _customChapters > 1 ? () {
+ setState(() => _customChapters--);
+ } : null),
+ const SizedBox(width: 32),
+ _circleButton(Icons.add_rounded, accent, _customChapters < 20 ? () {
+ setState(() => _customChapters++);
+ } : null),
+ ]),
+ const SizedBox(height: 12),
+ // Quick presets
+ Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ for (final ch in [1, 2, 3, 5])
+ _presetChip(accent, '$ch ch', _customChapters == ch, () {
+ setState(() => _customChapters = ch);
+ }),
+ ]),
+ const SizedBox(height: 16),
+ // Start button
+ SizedBox(width: double.infinity, height: 44, child: FilledButton(
+ style: FilledButton.styleFrom(backgroundColor: accent, foregroundColor: Colors.black,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
+ onPressed: () {
+ SleepTimerService().setChapterSleep(_customChapters);
+ Navigator.pop(context);
+ },
+ child: Text('Sleep after $_customChapters ${_customChapters == 1 ? 'chapter' : 'chapters'}',
+ style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14)),
+ )),
+ ]);
+ }
+
+ Widget _buildShakeToggle(Color accent, TextTheme tt) {
+ return Row(children: [
+ Icon(Icons.vibration_rounded, size: 18, color: _shakeEnabled ? accent : Colors.white24),
+ const SizedBox(width: 10),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text('Shake to add time',
+ style: TextStyle(color: _shakeEnabled ? Colors.white70 : Colors.white38, fontSize: 13, fontWeight: FontWeight.w500)),
+ Text(_shakeEnabled
+ ? (_tabIndex == 0 ? 'Adds $_shakeAddMinutes min' : 'Adds 1 chapter')
+ : 'Off',
+ style: TextStyle(color: Colors.white.withValues(alpha: 0.3), fontSize: 11)),
+ ])),
+ SizedBox(
+ height: 28,
+ child: Switch(
+ value: _shakeEnabled,
+ activeColor: accent,
+ onChanged: (v) {
+ setState(() => _shakeEnabled = v);
+ PlayerSettings.setShakeToResetSleep(v);
+ },
+ ),
+ ),
+ ]);
+ }
+
+ Widget _circleButton(IconData icon, Color accent, VoidCallback? onTap) {
+ final enabled = onTap != null;
+ return GestureDetector(
+ onTap: onTap,
+ child: Container(
+ width: 48, height: 48,
+ decoration: BoxDecoration(
+ color: enabled ? accent.withValues(alpha: 0.15) : Colors.white.withValues(alpha: 0.04),
+ shape: BoxShape.circle,
+ border: Border.all(color: enabled ? accent.withValues(alpha: 0.3) : Colors.white.withValues(alpha: 0.06)),
+ ),
+ child: Icon(icon, color: enabled ? accent : Colors.white24, size: 24),
+ ),
+ );
+ }
+
+ Widget _presetChip(Color accent, String label, bool active, VoidCallback onTap) {
+ return GestureDetector(onTap: onTap, child: AnimatedContainer(
+ duration: const Duration(milliseconds: 150),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ decoration: BoxDecoration(
+ color: active ? accent.withValues(alpha: 0.2) : Colors.white.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: active ? accent.withValues(alpha: 0.4) : Colors.white.withValues(alpha: 0.1)),
+ ),
+ child: Text(label, style: TextStyle(
+ color: active ? accent : Colors.white54,
+ fontSize: 13, fontWeight: active ? FontWeight.w600 : FontWeight.w400)),
+ ));
+ }
+}
diff --git a/packages/just_audio/CHANGELOG.md b/packages/just_audio/CHANGELOG.md
new file mode 100644
index 00000000..b82e8e2f
--- /dev/null
+++ b/packages/just_audio/CHANGELOG.md
@@ -0,0 +1,583 @@
+## 0.9.46
+
+* Fix SwiftPM support on macOS.
+
+## 0.9.45
+
+* Add setWebSinkId for web (@dganzella).
+
+## 0.9.44
+
+* Add support for SwiftPM.
+
+## 0.9.43
+
+* Fix NPE in load on iOS/macOS.
+* Migrate to media3 ExoPlayer 1.4.1 on Android (@hansvdwd and @ryanheise).
+
+## 0.9.42
+
+* Fix dealloc crash on iOS/macOS (@cristian1980).
+* Fix Dart memory leak on dispose (@MinSeungHyun).
+* Bump gradle to 8.5.0.
+
+## 0.9.41
+
+* Fix stop() to cause play() to return on iOS.
+
+## 0.9.40
+
+* Fix JDK 21 compile error.
+
+## 0.9.39
+
+* Apply preferPreciseDurationAndTiming to files (@canxin121).
+* Add tag parameter to setUrl/setFilePath/setAsset (@mathisfouques).
+* Add tag parameter to setClip (@goviral-ma).
+* Support rxdart 0.28.x.
+
+## 0.9.38
+
+* Migrate to package:web.
+* Add AudioPlayer.setWebCrossOrigin for CORS on web (@danielwinkler).
+
+## 0.9.37
+
+* Support useLazyPreparation on iOS/macOS.
+* Add index in sequence to errors for Android/iOS/macOS.
+* Fix seek to index UI update on iOS/macOS.
+
+## 0.9.36
+
+* Add setAllowsExternalPlayback on iOS/macOS.
+* Support index-based seeking on Android/iOS/macOS.
+* Add option to send headers/userAgent without proxy.
+* Fix bug where user supplied headers are overwritten by defaults (@ctedgar).
+
+## 0.9.35
+
+* Fix nullable completer argument type (@srawlins).
+* Support uuid 4.0.0 (@Pante).
+
+## 0.9.34
+
+* Support AGP 8 (@josephcrowell).
+* Update AGP to 7.3.0.
+
+## 0.9.33
+
+* Update minimum flutter version to 3.0.
+
+## 0.9.32
+
+* Fix ignored tag parameter in AudioSource.asset().
+* Fix ignored tag parameter in AudioSource.file().
+* Fix nested URIs in HLS from EXT-X-MEDIA when using headers.
+
+## 0.9.31
+
+* Add a package parameter to AudioPlayer.setAsset() (@ewertonls).
+* Add AudioSource.asset(), AudioSource.file().
+* Fix tests for dart-sdk 2.5 (@ewertonls).
+
+## 0.9.30
+
+* Upgrade ExoPlayer to 2.18.1.
+* Fix bug using headers with LockCachingAudioSource.
+* Add LockCachingAudioSource.resolve().
+
+## 0.9.29
+
+* Fix bug in ConcatenatingAudioSource.clear().
+* Fix bug where proxy drains origin faster than it feeds client.
+* Fix bug where User Agent was not set on redirects (@mikel-snipd)
+* Fix bug where StreamAudioSource requests are not closed when proxy is disposed (@mikel-snipd)
+
+## 0.9.28
+
+* Recursively apply headers to HLS fragments.
+* Add positionDiscontinuityStream.
+
+## 0.9.27
+
+* Support offload scheduling on Android.
+* Fix iOS/macOS documentation for non-HTTP URLS and proxy usage.
+
+## 0.9.26
+
+* Auto-correct invalid HTTP headers in proxy.
+
+## 0.9.25
+
+* Fix compile issue with Android SDK 33.
+
+## 0.9.24
+
+* Bump Android compileSdkVersion to 31.
+
+## 0.9.23
+
+* Fallback to constant bitrate seeking on Android.
+
+## 0.9.22
+
+* Migrate to Flutter 3, Xcode 13, ExoPlayer 2.17.1.
+* Add just_audio_mpv and just_audio_windows to example.
+
+## 0.9.21
+
+* Handle and report network disconnections in StreamAudioSource.
+* Fix iOS/macOS bug starting with empty playlist.
+* Migrate from pedantic to flutter_lints.
+* Accept Longs in AndroidLivePlaybackSpeedControl where appropriate (@aam).
+
+## 0.9.20
+
+* Fix initial position on iOS/macOS when switching sources (@addie9000).
+
+## 0.9.19
+
+* Dispose players on iOS/macOS hot restart.
+* Fix initialIndex out of bounds bug on iOS/macOS.
+
+## 0.9.18
+
+* Fix null duration bug on LockCachingAudioSource.
+
+## 0.9.17
+
+* LockCachingAudioSource works with servers not supporting range requests.
+* Add StreamAudioResponse.rangeRequestsSupported.
+* Fix doc typos (@robert-j-webb)
+
+## 0.9.16
+
+* Fix pubspec declaration for Linux/Windows implementation.
+
+## 0.9.15
+
+* Fix bug initialising proxy on ConcatenatingAudioSource.add.
+
+## 0.9.14
+
+* Fix bug when pausing/stopping quickly after play.
+
+## 0.9.13
+
+* Fix MIME type in LockCachingAudioSource.
+* Add radio/livestream example.
+* Report URL from ICY metadata on iOS/macOS.
+* Update example to just_audio_libwinmedia 0.0.4 (@bdlukaa)
+
+## 0.9.12
+
+* Windows/Linux support (@bdlukaa, credit to @alexmercerind for libwinmedia).
+
+## 0.9.11
+
+* Upgrade Android to ExoPlayer 2.15.0.
+
+## 0.9.10
+
+* Fix Android bug playing after stopping.
+
+## 0.9.9
+
+* Fix web bug adding/removing items while paused.
+
+## 0.9.8
+
+* Fix bug restoring AndroidEqualizer state after stop.
+* Make exceptions implement Exception.
+* Upgrade to ExoPlayer 2.13.3.
+
+## 0.9.7
+
+* Update Gradle version.
+* Change == parameter from dynamic to Object (@cedvdb).
+* Check runtimeType in all == operators.
+* Fix Android compiler warnings.
+
+## 0.9.6
+
+* Fix iOS 12.4 `LockCachingAudioSource` fetch exception (@akindone).
+
+## 0.9.5
+
+* Fix iOS/macOS bug updating shuffle order.
+* Fix iOS/macOS bug advancing to next in shuffle order.
+
+## 0.9.4
+
+* Remember position after stop().
+
+## 0.9.3
+
+* Fix bug when updating playlist before loading.
+
+## 0.9.2
+
+* Fix Android bug when loading empty playlist.
+* Fix Android NullPointerException on stop().
+
+## 0.9.1
+
+* Fix iOS/macOS bug when setting volume before load.
+
+## 0.9.0
+
+* Update to support just_audio_background.
+
+## 0.8.1
+
+* Fix update position bug on Android.
+* Compile-time option to include/exclude microphone API.
+
+## 0.8.0
+
+* Add buffer options via AudioLoadConfiguration for iOS/Android.
+* Add setSkipSilenceEnabled for Android (@subhash279).
+* Add setPitch for Android.
+* Add audio effects:
+ * AndroidLoudnessEnhancer
+ * AndroidEqualizer
+* Dispose players when hot restarting on Android.
+
+## 0.7.5
+
+* Support rxdart 0.27.0
+* Mention INTERNET Android permission in README (@nt4f04uNd).
+
+## 0.7.4+1
+
+* Link to tutorials in README.
+
+## 0.7.4
+
+* Fix hang after stopping while loading.
+* Fix pending timers error (@minhqdao).
+
+## 0.7.3
+
+* Silence uncaught exceptions in positionStream.
+
+## 0.7.2
+
+* Propagate play() exceptions (@twogood).
+
+## 0.7.1
+
+* Fix IllegalSeekPositionException on Android (@DenisShakinov).
+* Fix error playing files when a user agent is set.
+
+## 0.7.0
+
+* Null safety.
+* Retype headers from Map to Map<String, String>
+
+## 0.6.15+1
+
+* Fix doc references.
+
+## 0.6.15
+
+* Fix bug with spaces in asset paths.
+* Fix bug setting a ClippingAudioSource after another source.
+
+## 0.6.14+1
+
+* Update ICY metadata feature status in README.
+
+## 0.6.14
+
+* Initial support for ICY metadata on iOS.
+* Upgrade to ExoPlayer 2.13.1 (@MichealReed).
+
+## 0.6.13
+
+* Add userAgent parameter to AudioPlayer constructor.
+* Support seeks during download in LockCachingAudioSource.
+* Fix negative duration bug on iOS/macOS.
+
+## 0.6.12
+
+* Fix non-completing seek-to-index bug on iOS/macOS.
+* More options to manage audio_session.
+
+## 0.6.11
+
+* Update example to indicate buffer position.
+* Document pre-release and experimental features in README.
+
+## 0.6.10
+
+* Fix range error in SequenceState (@smkhalsa).
+
+## 0.6.9
+
+* Support assets on web.
+* Support StreamAudioSource on web.
+* Fix bug on web when manipulating playlists.
+* Asset cache no longer deleted on dispose.
+* Add contentType to StreamAudioResponse.
+
+## 0.6.8
+
+* Fix pubspec description.
+
+## 0.6.7
+
+* Fix bug with bufferedPositionStream on iOS/macOS.
+
+## 0.6.6
+
+* Experimental cache support.
+* Experimental stream audio source.
+* Disable iOS/macOS logs (@pschuegr).
+* Fix bug with empty playlist (iOS/macOS/web).
+* Fix Android bug when initialIndex==null.
+* Avoid duplicates in asset cache.
+* Guard against unsupported assets on web.
+
+## 0.6.5
+
+* Rewrite setLoopMode on iOS to be gapless.
+
+## 0.6.4
+
+* Emit PlaybackEvent when playing (compatibility with 0.5.x).
+
+## 0.6.3
+
+* Fix iOS compiler warnings.
+* Fix bug where native platform wasn't disposed.
+* Remove Java compiler warnings.
+* Process play/pause state transitions in a consistent order.
+
+## 0.6.2
+
+* Fix bugs related to the new setAudioSource method:
+ * When calling setAudioSource more than once
+ * When calling setAudioSource/load/play simultaneously
+
+## 0.6.1
+
+* Fix bug with Android skipping start of audio.
+
+## 0.6.0
+
+* Breaking change: Replace load by setAudioSource.
+* Breaking change: Rename ProcessingState.none to idle.
+* Support custom shuffle order.
+* Fix bug dynamically adding to ConcatenatingAudioSource.
+* Correctly return null for unknown duration on Android.
+* Update dependency versions.
+
+## 0.5.7
+
+* Fix podspec error in web package (@timilehinjegede).
+* Fix iOS out-of-range bug.
+* Remove Objective C compiler warnings.
+* Unit tests.
+
+## 0.5.6
+
+* Fix iOS memory leak.
+* Enable useLazyPreparation by default.
+
+## 0.5.5
+
+* Add initialPosition/initialIndex parameters to load.
+* Fix iOS crash when disposing just before FlutterEngine is destroyed.
+* Fix bug with simultaneous seek requests on iOS.
+* Fix seeking when using headers (@nuc134r).
+* Fix loading state transition on Android.
+* Pass through all setSpeeds requests on iOS, ignoring canPlayFast/Slow.
+* Fix bug loading file paths containing spaces (@hsangtini).
+* Add web endorsement (@creativecreatorormaybenot).
+
+## 0.5.4
+
+* Use audio_session 0.0.9.
+
+## 0.5.3
+
+* ARC fixes on iOS.
+* Update to use platform interface 1.1.0.
+* Retain player.position after dispose.
+* Fix unnattached player bug in ConcatenatingAudioSource (@nuc134r).
+
+## 0.5.2
+
+* Fix bug in concatenating add/addAll.
+
+## 0.5.1
+
+* Fix bug in loading from assets.
+* Ignore method calls from invalid states.
+* Forward exceptions from iOS platform implementation.
+
+## 0.5.0
+
+* Convert to federated plugin.
+
+## 0.4.5
+
+* Fix iOS bug in seek/position/duration in HLS streams (@snaeji).
+* Fix web bug for audio sources with unknown durations.
+
+## 0.4.4
+
+* Fix crash when disposing of positionStream controller.
+* Handle interruptions correctly when willPauseWhenDucked is set.
+* Correct seek/position/duration in HLS streams (@snaeji).
+* Resume at correct speed after seek on iOS (@subhash279).
+
+## 0.4.3
+
+* Add section to README on configuring the audio session.
+
+## 0.4.2
+
+* Make default audio session settings compatible with iOS control center.
+* Update README to mention NSMicrophoneUsageDescription key in Info.plist.
+
+## 0.4.1
+
+* Fix setSpeed bug on iOS.
+
+## 0.4.0
+
+* Handles audio focus/interruptions via audio_session
+* Bug fixes
+
+## 0.3.4
+
+* Fix bug in icy metadata
+* Allow Android AudioAttributes to be set
+* Provide access to Android audio session ID
+
+## 0.3.3
+
+* Remove dependency on Java streams API
+
+## 0.3.2
+
+* Fix dynamic methods on ConcatenatingAudioSource for iOS/Android
+* Add sequenceStream/sequenceStateStream
+* Change asset URI from asset:// to asset:///
+
+## 0.3.1
+
+* Prevent hang in dispose
+
+## 0.3.0
+
+* Playlists
+* Looping
+* Shuffling
+* Composing
+* Clipping support added for iOS/macOS
+* New player state model consisting of:
+ * playing: true/false
+ * processingState: none/loading/buffering/ready/completed
+* Feature complete on iOS and macOS (except for DASH)
+* Improved example
+* Exception classes
+
+## 0.2.2
+
+* Fix dependencies for stable channel.
+
+## 0.2.1
+
+* Improve handling of headers.
+* Report setUrl errors and duration on web.
+
+## 0.2.0
+
+* Support dynamic duration
+* Support seeking to end of live streams
+* Support request headers
+* V2 implementation
+* Report setUrl errors on iOS
+* setUrl throws exception if interrupted
+* Return null when duration is unknown
+
+## 0.1.10
+
+* Option to set audio session category on iOS.
+
+## 0.1.9
+
+* Bug fixes.
+
+## 0.1.8
+
+* Reduce distortion at slow speeds on iOS
+
+## 0.1.7
+
+* Minor bug fixes.
+
+## 0.1.6
+
+* Eliminate event lag over method channels.
+* Report setUrl errors on Android.
+* Report Icy Metadata on Android.
+* Bug fixes.
+
+## 0.1.5
+
+* Update dependencies and documentation.
+
+## 0.1.4
+
+* Add MacOS implementation.
+* Support cross-platform redirects on Android.
+* Bug fixes.
+
+## 0.1.3
+
+* Fix bug in web implementation.
+
+## 0.1.2
+
+* Broadcast how much audio has been buffered.
+
+## 0.1.1
+
+* Web implementation.
+* iOS option to minimize stalling.
+* Fix setAsset on iOS.
+
+## 0.1.0
+
+* Separate buffering state from PlaybackState.
+* More permissive state transitions.
+* Support playing local files on iOS.
+
+## 0.0.6
+
+* Bug fixes.
+
+## 0.0.5
+
+* API change for audio clipping.
+* Performance improvements and bug fixes on Android.
+
+## 0.0.4
+
+* Remove reseeking hack.
+
+## 0.0.3
+
+* Feature to change audio speed.
+
+## 0.0.2
+
+* iOS implementation for testing (may not work).
+
+## 0.0.1
+
+* Initial release with Android implementation.
diff --git a/packages/just_audio/LICENSE b/packages/just_audio/LICENSE
new file mode 100644
index 00000000..6948574d
--- /dev/null
+++ b/packages/just_audio/LICENSE
@@ -0,0 +1,229 @@
+MIT License
+
+Copyright (c) 2019-2020 Ryan Heise and the project contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+==============================================================================
+
+This software includes the ExoPlayer library which is licensed under the Apache
+License, Version 2.0.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/just_audio/README.md b/packages/just_audio/README.md
new file mode 100644
index 00000000..a141c401
--- /dev/null
+++ b/packages/just_audio/README.md
@@ -0,0 +1,518 @@
+# just_audio
+
+just_audio is a feature-rich audio player for Android, iOS, macOS, web, Linux and Windows.
+
+[Platform Support](#platform-support) — [API Documentation](https://pub.dev/documentation/just_audio/latest/just_audio/just_audio-library.html) — [Tutorials](#tutorials) — [Background Audio](https://pub.dev/packages/just_audio_background) — [Community Support](https://stackoverflow.com/questions/tagged/just-audio)
+
+![Screenshot with arrows pointing to features](https://user-images.githubusercontent.com/19899190/125459608-e89cd6d4-9f09-426c-abcc-ed7513d9acfc.png)
+
+### Quick synopsis
+
+```dart
+import 'package:just_audio/just_audio.dart';
+
+final player = AudioPlayer(); // Create a player
+final duration = await player.setUrl( // Load a URL
+ 'https://foo.com/bar.mp3'); // Schemes: (https: | file: | asset: )
+player.play(); // Play without waiting for completion
+await player.play(); // Play while waiting for completion
+await player.pause(); // Pause but remain ready to play
+await player.seek(Duration(seconds: 10)); // Jump to the 10 second position
+await player.setSpeed(2.0); // Twice as fast
+await player.setVolume(0.5); // Half as loud
+await player.stop(); // Stop and free resources
+```
+
+### Working with multiple players
+
+```dart
+// Set up two players with different audio files
+final player1 = AudioPlayer(); await player1.setUrl(...);
+final player2 = AudioPlayer(); await player2.setUrl(...);
+
+// Play both at the same time
+player1.play();
+player2.play();
+
+// Play one after the other
+await player1.play();
+await player2.play();
+
+// Loop player1 until player2 finishes
+await player1.setLoopMode(LoopMode.one);
+player1.play(); // Don't wait
+await player2.play(); // Wait for player2 to finish
+await player1.pause(); // Finish player1
+
+// Free platform decoders and buffers for each player.
+await player1.stop();
+await player2.stop();
+```
+
+### Working with clips
+
+```dart
+// Play clip 2-4 seconds followed by clip 10-12 seconds
+await player.setClip(start: Duration(seconds: 2), end: Duration(seconds: 4));
+await player.play(); await player.pause();
+await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 12));
+await player.play(); await player.pause();
+
+await player.setClip(); // Clear clip region
+```
+
+### Working with gapless playlists
+
+```dart
+// Define the playlist
+final playlist = ConcatenatingAudioSource(
+ // Start loading next item just before reaching it
+ useLazyPreparation: true,
+ // Customise the shuffle algorithm
+ shuffleOrder: DefaultShuffleOrder(),
+ // Specify the playlist items
+ children: [
+ AudioSource.uri(Uri.parse('https://example.com/track1.mp3')),
+ AudioSource.uri(Uri.parse('https://example.com/track2.mp3')),
+ AudioSource.uri(Uri.parse('https://example.com/track3.mp3')),
+ ],
+);
+
+// Load and play the playlist
+await player.setAudioSource(playlist, initialIndex: 0, initialPosition: Duration.zero);
+await player.seekToNext(); // Skip to the next item
+await player.seekToPrevious(); // Skip to the previous item
+await player.seek(Duration.zero, index: 2); // Skip to the start of track3.mp3
+await player.setLoopMode(LoopMode.all); // Set playlist to loop (off|all|one)
+await player.setShuffleModeEnabled(true); // Shuffle playlist order (true|false)
+
+// Update the playlist
+await playlist.add(newChild1);
+await playlist.insert(3, newChild2);
+await playlist.removeAt(3);
+```
+
+### Working with headers
+
+```dart
+// Setting the HTTP user agent
+final player = AudioPlayer(
+ userAgent: 'myradioapp/1.0 (Linux;Android 11) https://myradioapp.com',
+ useProxyForRequestHeaders: true, // default
+);
+
+// Setting request headers
+final duration = await player.setUrl('https://foo.com/bar.mp3',
+ headers: {'header1': 'value1', 'header2': 'value2'});
+```
+
+Note: By default, headers are implemented via a local HTTP proxy which on Android, iOS and macOS requires non-HTTPS support to be enabled. See [Platform Specific Configuration](#platform-specific-configuration).
+
+Alternatively, settings `useProxyForRequestHeaders: false` will use the platform's native headers implementation without a proxy. Although note that iOS doesn't offer an official native API for setting headers, and so this will use the undocumented `AVURLAssetHTTPHeaderFieldsKey` API (or in the case of the user-agent header on iOS 16 and above, the official `AVURLAssetHTTPUserAgentKey` API).
+
+### Working with caches
+
+```dart
+// Clear the asset cache directory
+await AudioPlayer.clearAssetCache();
+
+// Download and cache audio while playing it (experimental)
+final audioSource = LockCachingAudioSource('https://foo.com/bar.mp3');
+await player.setAudioSource(audioSource);
+// Delete the cached file
+await audioSource.clearCache();
+```
+
+Note: `LockCachingAudioSource` is implemented via a local HTTP proxy which on Android, iOS and macOS requires non-HTTPS support to be enabled. See [Platform Specific Configuration](#platform-specific-configuration).
+
+### Working with stream audio sources
+
+```dart
+// Feed your own stream of bytes into the player
+class MyCustomSource extends StreamAudioSource {
+ final List<int> bytes;
+ MyCustomSource(this.bytes);
+
+ @override
+ Future<StreamAudioResponse> request([int? start, int? end]) async {
+ start ??= 0;
+ end ??= bytes.length;
+ return StreamAudioResponse(
+ sourceLength: bytes.length,
+ contentLength: end - start,
+ offset: start,
+ stream: Stream.value(bytes.sublist(start, end)),
+ contentType: 'audio/mpeg',
+ );
+ }
+}
+
+await player.setAudioSource(MyCustomSource());
+player.play();
+```
+
+Note: `StreamAudioSource` is implemented via a local HTTP proxy which on Android, iOS and macOS requires non-HTTPS support to be enabled. See [Platform Specific Configuration](#platform-specific-configuration).
+
+
+### Working with errors
+
+```dart
+// Catching errors at load time
+try {
+ await player.setUrl("https://s3.amazonaws.com/404-file.mp3");
+} on PlayerException catch (e) {
+ // iOS/macOS: maps to NSError.code
+ // Android: maps to ExoPlayerException.type
+ // Web: maps to MediaError.code
+ // Linux/Windows: maps to PlayerErrorCode.index
+ print("Error code: ${e.code}");
+ // iOS/macOS: maps to NSError.localizedDescription
+ // Android: maps to ExoPlaybackException.getMessage()
+ // Web/Linux: a generic message
+ // Windows: MediaPlayerError.message
+ print("Error message: ${e.message}");
+} on PlayerInterruptedException catch (e) {
+ // This call was interrupted since another audio source was loaded or the
+ // player was stopped or disposed before this audio source could complete
+ // loading.
+ print("Connection aborted: ${e.message}");
+} catch (e) {
+ // Fallback for all other errors
+ print('An error occured: $e');
+}
+
+// Catching errors during playback (e.g. lost network connection)
+player.playbackEventStream.listen((event) {}, onError: (Object e, StackTrace st) {
+ if (e is PlatformException) {
+ print('Error code: ${e.code}');
+ print('Error message: ${e.message}');
+ print('AudioSource index: ${e.details?["index"]}');
+ } else {
+ print('An error occurred: $e');
+ }
+});
+```
+
+Note: In a future release, the exception type on `playbackEventStream` will change from `PlatformException` to `PlayerException`.
+
+### Working with state streams
+
+See [The state model](#the-state-model) for details.
+
+```dart
+player.playerStateStream.listen((state) {
+ if (state.playing) ... else ...
+ switch (state.processingState) {
+ case ProcessingState.idle: ...
+ case ProcessingState.loading: ...
+ case ProcessingState.buffering: ...
+ case ProcessingState.ready: ...
+ case ProcessingState.completed: ...
+ }
+});
+
+// See also:
+// - durationStream
+// - positionStream
+// - bufferedPositionStream
+// - sequenceStateStream
+// - sequenceStream
+// - currentIndexStream
+// - icyMetadataStream
+// - playingStream
+// - processingStateStream
+// - loopModeStream
+// - shuffleModeEnabledStream
+// - volumeStream
+// - speedStream
+// - playbackEventStream
+```
+
+## Credits
+
+This project is supported by the amazing open source community of [GitHub contributors](https://github.com/ryanheise/just_audio/blob/minor/CONTRIBUTING.md) and [sponsors](https://github.com/sponsors/ryanheise). Thank you!
+
+## Platform specific configuration
+
+### Android
+
+To allow your application to access audio files on the Internet, add the following permission to your `AndroidManifest.xml` file:
+
+```xml
+ <uses-permission android:name="android.permission.INTERNET"/>
+```
+
+If you wish to connect to non-HTTPS URLs (typically HTTP), also add the following attribute to the `application` element:
+
+```xml
+ <application ... android:usesCleartextTraffic="true">
+```
+
+Note that just_audio's proxy (used to implement features such as headers, caching and stream audio sources) runs on a `localhost` HTTP server, and this also requires cleartext access to be enabled. You can either enable this via the option above which also enables access to any non-HTTPS URL, or you can instead limit cleartext access to just `localhost` URLs by defining a network security config. To use this approach, create the file `android/app/src/main/res/xml/network_security_config.xml`:
+
+```xml
+<?xml version="1.0" encoding="utf-8"?>
+<network-security-config>
+ <domain-config cleartextTrafficPermitted="true">
+ <domain includeSubdomains="false">127.0.0.1</domain>
+ </domain-config>
+</network-security-config>
+```
+
+Then reference this network security config in your `AndroidManifest.xml` file by adding the following attribute to the `application` element:
+
+```xml
+ <application ... android:networkSecurityConfig="@xml/network_security_config">
+```
+
+If you need access to the player's AudioSession ID, you can listen to `AudioPlayer.androidAudioSessionIdStream`. Note that the AudioSession ID will change whenever you set new AudioAttributes.
+
+If there are multiple plugins in your app that use ExoPlayer to decode media, it is possible to encounter a `Duplicate class` error if those plugins use different versions of ExoPlayer. In this case you may report an issue for each respective plugin to upgrade to the latest version of ExoPlayer, or you may downgrade one or more of your app's plugins until the versions match. In some cases where a plugin uses non-breaking parts of the ExoPlayer API, you can also try forcing all plugins to use the same version of ExoPlayer by editing your own app's `android/app/build.gradle` file and inserting the dependencies for the desired Exoplayer version:
+
+```
+dependencies {
+ def exoplayer_version = "...specify-version-here...."
+ implementation "com.google.android.exoplayer:exoplayer-core:$exoplayer_version"
+ implementation "com.google.android.exoplayer:exoplayer-dash:$exoplayer_version"
+ implementation "com.google.android.exoplayer:exoplayer-hls:$exoplayer_version"
+ implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:$exoplayer_version"
+}
+```
+
+### iOS
+
+If you wish to connect to non-HTTPS URLs, or if you use a feature that depends on the proxy such as headers, caching or stream audio sources, add the following to your `Info.plist` file:
+
+```xml
+<key>NSAppTransportSecurity</key>
+<dict>
+ <key>NSAllowsArbitraryLoads</key>
+ <true/>
+</dict>
+```
+
+Using the default configuration, the App Store will detect that your app uses the AVAudioSession API which includes a microphone API, and for privacy reasons it will ask you to describe your app's usage of the microphone. If your app does indeed use the microphone, you can describe your usage by editing the `Info.plist` file as follows:
+
+```xml
+<key>NSMicrophoneUsageDescription</key>
+<string>... explain why the app uses the microphone here ...</string>
+```
+
+But if your app doesn't use the microphone, you can pass a build option to "compile out" any microphone code so that the App Store won't ask for the above usage description. This can be done with either CocoaPods or SwiftPM builds.
+
+#### CocoaPods
+
+Edit your `ios/Podfile` as follows:
+
+```ruby
+post_install do |installer|
+ installer.pods_project.targets.each do |target|
+ flutter_additional_ios_build_settings(target)
+
+ # ADD THE NEXT SECTION
+ target.build_configurations.each do |config|
+ config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
+ '$(inherited)',
+ 'AUDIO_SESSION_MICROPHONE=0'
+ ]
+ end
+
+ end
+end
+```
+
+#### SwiftPM
+
+Run `flutter clean` to force SwiftPM to pick up your new settings:
+
+```
+flutter clean
+```
+
+Export the environment variable `AUDIO_SESSION_MICROPHONE=0` before running your build command. E.g. Using the bash command line:
+
+```
+AUDIO_SESSION_MICROPHONE=0 flutter run
+```
+
+Note: `flutter clean` is needed whenever the value of `AUDIO_SESSION_MICROPHONE` changes, or whenever you switch between different projects that use audio_session with different `AUDIO_SESSION_MICROPHONE` values.
+
+### macOS
+
+To allow your macOS application to access audio files on the Internet, add the following to your `DebugProfile.entitlements` and `Release.entitlements` files:
+
+```xml
+ <key>com.apple.security.network.client</key>
+ <true/>
+```
+
+If you wish to connect to non-HTTPS URLs, or if you use a feature that depends on the proxy such as headers, caching or stream audio sources, add the following to your `Info.plist` file:
+
+```xml
+<key>NSAppTransportSecurity</key>
+<dict>
+ <key>NSAllowsArbitraryLoads</key>
+ <true/>
+</dict>
+```
+
+The macOS player relies on server headers (e.g. `Content-Type`, `Content-Length` and [byte range requests](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/CreatingVideoforSafarioniPhone/CreatingVideoforSafarioniPhone.html#//apple_ref/doc/uid/TP40006514-SW6)) to know how to decode the file and where applicable to report its duration. In the case of files, macOS relies on the file extension.
+
+### Windows
+
+Windows support is enabled by adding an additional dependency to your `pubspec.yaml` alongside `just_audio`. There are a number of alternative options:
+
+* [just_audio_windows](https://pub.dev/packages/just_audio_windows)
+* [just_audio_libwinmedia](https://pub.dev/packages/just_audio_libwinmedia)
+
+Example:
+
+```yaml
+dependencies:
+ just_audio: any # substitute version number
+ just_audio_windows: any # substitute version number
+```
+
+For issues with the Windows implementation, please open an issue on the respective implementation's GitHub issues page.
+
+### Linux
+
+Linux support is enabled by adding an additional dependency to your `pubspec.yaml` alongside `just_audio`. There are a number of alternative options:
+
+* [just_audio_mpv](https://pub.dev/packages/just_audio_mpv)
+* [just_audio_libwinmedia](https://pub.dev/packages/just_audio_libwinmedia) (untested)
+
+```yaml
+dependencies:
+ just_audio: any # substitute version number
+ just_audio_mpv: any # substitute version number
+```
+
+For issues with the Linux implementation, please open an issue on the respective implementation's GitHub issues page.
+
+## Troubleshooting
+
+Most problems you encounter when playing an audio file will likely relate to the audio file format, the server headers, or the file name.
+
+### Audio file formats/encodings
+
+Different platforms support different audio formats and encodings. For a list, see this [StackOverflow](https://stackoverflow.com/questions/73557707/which-audio-formats-extensions-work-on-ios-and-android-with-the-just-audio-flu) answer.
+
+Different audio formats have different seeking support. If you have control over the encoding of the audio files your app needs to play, then it is recommended to encode audio as M4A because this is capable of embedding an accurate seek table. With MP3, there are multiple different methods of encoding that permit seeking, although all such methods are approximate. When your app needs to play from arbitrary audio sources requested by the user, you are at the mercy of the source audio format.
+
+Different audio formats may or may not embed duration metadata, and the absence of this metadata is a common reason why just_audio may sometimes return a null duration. This behaviour is platform specific, however, and Android can sometimes infer the missing duration by decoding the entire file and measuring the duration.
+
+### Server headers
+
+A server that hosts audio content should return appropriate HTTP response headers to the client. This includes an appropriate `Content-Length` header and a correct `Content-Type` header so that the player knows which decoder to use to read the data.
+
+Servers should also support range requests. These allow just_audio to make requests for a part of the whole file within a given byte range as opposed to always requesting the whole file. If the user seeks to a position near the end of the audio file that hasn't been downloaded yet (and if there is a seek table), just_audio will try to make a range request for the end of the file.
+
+Range requests can also impact on just_audio's ability to determine an audio file's duration. In many cases, certain audio formats embed metadata (which includes the audio duration) at the END of the audio file, and range requests allow just_audio to jump to the end of the file to fetch the metadata first, without having to wait for the entire file to download, and then inform you up front what the audio file duration is. If just_audio returns a null duration when the audio file has duration metadata, this may suggest that the server does not support range requests.
+
+If you host audio files on your own server, remember to correctly configure the headers described above.
+
+### File names
+
+When playing audio from a local file, just_audio cannot use any `Content-Type` header to figure out which decoder to use to read the file. Instead, the file name extension will generally be used to determine the file type. For example, if a file name ends with `.mp3`, the MP3 decoder will be used to read it, while if the file name ends with `.wav`, the WAV decoder will be used. If the file name has an `.mp3` extension but the actual file content is not in the MP3 format, then just_audio may potentially fail to read it. iOS enforces this fairly strictly, while Android is more likely to be forgiving by taking a peek at the data to make an educated guess as to what the data format really is. In general, however, it is recommended to use correct file name extensions for any audio file that is under your control.
+
+## Mixing and matching audio plugins
+
+The flutter plugin ecosystem contains a wide variety of useful audio plugins. In order to allow these to work together in a single app, just_audio "just" plays audio. By focusing on a single responsibility, different audio plugins can safely work together without overlapping responsibilities causing runtime conflicts.
+
+Other common audio capabilities are optionally provided by separate plugins:
+
+* [just_audio_background](https://pub.dev/packages/just_audio_background): Use this to allow your app to play audio in the background and respond to controls on the lockscreen, media notification, headset, AndroidAuto/CarPlay or smart watch.
+* [audio_service](https://pub.dev/packages/audio_service): Use this if your app has more advanced background audio requirements than can be supported by `just_audio_background`.
+* [audio_session](https://pub.dev/packages/audio_session): Use this to configure and manage how your app interacts with other audio apps (e.g. phone call or navigator interruptions).
+* [just_waveform](https://pub.dev/packages/just_waveform): Use this to extract an audio file's waveform suitable for visual rendering.
+
+## Tutorials
+
+* [Create a simple Flutter music player app](https://ishouldgotosleep.com/simple-flutter-music-player-app/) by @mvolpato
+* [Playing short audio clips in Flutter with Just Audio](https://suragch.medium.com/playing-short-audio-clips-in-flutter-with-just-audio-3c80eb7eb6ea?sk=aaf6cc523c2c6fc747b5087277932607) by @suragch
+* [Streaming audio in Flutter with Just Audio](https://suragch.medium.com/steaming-audio-in-flutter-with-just-audio-7435fcf672bf?sk=c7163e8496b914c9e0e5446ec6020f04) by @suragch
+* [Managing playlists in Flutter with Just Audio](https://suragch.medium.com/managing-playlists-in-flutter-with-just-audio-c4b8f2af12eb?sk=1b1ffa2cb0b3ed50a320d8cc32cef342) by @suragch
+
+## Vote on upcoming features
+
+Press the thumbs up icon on the GitHub issues you would like to vote on:
+
+* Pitch shifting: [#329](https://github.com/ryanheise/just_audio/issues/329)
+* Equaliser: [#147](https://github.com/ryanheise/just_audio/issues/147)
+* Casting support (Chromecast and AirPlay): [#211](https://github.com/ryanheise/just_audio/issues/211)
+* Volume boost and skip silence: [#307](https://github.com/ryanheise/just_audio/issues/307)
+* [All feature requests sorted by popularity](https://github.com/ryanheise/just_audio/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement+sort%3Areactions-%2B1-desc)
+
+Please also consider pressing the thumbs up button at the top of [this page](https://pub.dev/packages/just_audio) (pub.dev) if you would like to bring more momentum to the project. More users leads to more bug reports and feature requests, which leads to increased stability and functionality.
+
+## Platform support
+
+| Feature | Android | iOS | macOS | Web | Windows | Linux |
+| ------------------------------ | :-----: | :-: | :---: | :-: | :-----: | :---: |
+| read from URL | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| read from file | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| read from asset | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| read from byte stream | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| request headers | ✅ | ✅ | ✅ | * | ✅ | ✅ |
+| DASH | ✅ | | | | ✅ | ✅ |
+| HLS | ✅ | ✅ | ✅ | | ✅ | ✅ |
+| ICY metadata | ✅ | ✅ | ✅ | | | |
+| buffer status/position | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| play/pause/seek | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| set volume/speed | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| clip audio | ✅ | ✅ | ✅ | ✅ | | ✅ |
+| playlists | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| looping/shuffling | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| compose audio | ✅ | ✅ | ✅ | ✅ | | ✅ |
+| gapless playback | ✅ | ✅ | ✅ | | ✅ | ✅ |
+| report player errors | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| handle phonecall interruptions | ✅ | ✅ | | | | |
+| buffering/loading options | ✅ | ✅ | ✅ | | | |
+| set pitch | ✅ | | | | | |
+| skip silence | ✅ | | | | | |
+| equalizer | ✅ | | | | | ✅ |
+| volume boost | ✅ | | | | | ✅ |
+
+(*): While request headers cannot be set directly on Web, cookies can be used to send information in the [Cookie header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie). See also `AudioPlayer.setWebCrossOrigin` to allow sending cookies when loading audio files from the same origin or a different origin.
+
+
+## Experimental features
+
+| Feature | Android | iOS | macOS | Web |
+| ------- | :-------: | :-----: | :-----: | :-----: |
+| Simultaneous downloading+caching | ✅ | ✅ | ✅ | |
+| Waveform visualizer (See [#97](https://github.com/ryanheise/just_audio/issues/97)) | ✅ | ✅ | | |
+| FFT visualizer (See [#97](https://github.com/ryanheise/just_audio/issues/97)) | ✅ | ✅ | ✅ | |
+| Background | ✅ | ✅ | ✅ | ✅ |
+
+Please consider reporting any bugs you encounter [here](https://github.com/ryanheise/just_audio/issues) or submitting pull requests [here](https://github.com/ryanheise/just_audio/pulls).
+
+## The state model
+
+The state of the player consists of two orthogonal states: `playing` and `processingState`. The `playing` state typically maps to the app's play/pause button and only ever changes in response to direct method calls by the app. By contrast, `processingState` reflects the state of the underlying audio decoder and can change both in response to method calls by the app and also in response to events occurring asynchronously within the audio processing pipeline. The following diagram depicts the valid state transitions:
+
+![just_audio_states](https://user-images.githubusercontent.com/19899190/103147563-e6601100-47aa-11eb-8baf-dee00d8e2cd4.png)
+
+This state model provides a flexible way to capture different combinations of states such as playing+buffering vs paused+buffering, and this allows state to be more accurately represented in an app's UI. It is important to understand that even when `playing == true`, no sound will actually be audible unless `processingState == ready` which indicates that the buffers are filled and ready to play. This makes intuitive sense when imagining the `playing` state as mapping onto an app's play/pause button:
+
+* When the user presses "play" to start a new track, the button will immediately reflect the "playing" state change although there will be a few moments of silence while the audio is loading (while `processingState == loading`) but once the buffers are finally filled (i.e. `processingState == ready`), audio playback will begin.
+* When buffering occurs during playback (e.g. due to a slow network connection), the app's play/pause button remains in the `playing` state, although temporarily no sound will be audible while `processingState == buffering`. Sound will be audible again as soon as the buffers are filled again and `processingState == ready`.
+* When playback reaches the end of the audio stream, the player remains in the `playing` state with the seek bar positioned at the end of the track. No sound will be audible until the app seeks to an earlier point in the stream. Some apps may choose to display a "replay" button in place of the play/pause button at this point, which calls `seek(Duration.zero)`. When clicked, playback will automatically continue from the seek point (because it was never paused in the first place). Other apps may instead wish to listen for the `processingState == completed` event and programmatically pause and rewind the audio at that point.
+
+Apps that wish to react to both orthogonal states through a single combined stream may listen to `playerStateStream`. This stream will emit events that contain the latest value of both `playing` and `processingState`.
+
+## Configuring the audio session
+
+If your app uses audio, you should tell the operating system what kind of usage scenario your app has and how your app will interact with other audio apps on the device. Different audio apps often have unique requirements. For example, when a navigator app speaks driving instructions, a music player should duck its audio while a podcast player should pause its audio. Depending on which one of these three apps you are building, you will need to configure your app's audio settings and callbacks to appropriately handle these interactions.
+
+just_audio will by default choose settings that are appropriate for a music player app which means that it will automatically duck audio when a navigator starts speaking, but should pause when a phone call or another music player starts. If you are building a podcast player or audio book reader, this behaviour would not be appropriate. While the user may be able to comprehend the navigator instructions while ducked music is playing in the background, it would be much more difficult to understand the navigator instructions while simultaneously listening to an audio book or podcast.
+
+You can use the [audio_session](https://pub.dev/packages/audio_session) package to change the default audio session configuration for your app. E.g. for a podcast player, you may use:
+
+```dart
+final session = await AudioSession.instance;
+await session.configure(AudioSessionConfiguration.speech());
+```
+
+Note: If your app uses a number of different audio plugins, e.g. for audio recording, or text to speech, or background audio, it is possible that those plugins may internally override each other's audio session settings, so it is recommended that you apply your own preferred configuration using audio_session after all other audio plugins have loaded. You may consider asking the developer of each audio plugin you use to provide an option to not overwrite these global settings and allow them be managed externally.
diff --git a/packages/just_audio/analysis_options.yaml b/packages/just_audio/analysis_options.yaml
new file mode 100644
index 00000000..46c84488
--- /dev/null
+++ b/packages/just_audio/analysis_options.yaml
@@ -0,0 +1,12 @@
+include: package:flutter_lints/flutter.yaml
+
+analyzer:
+ language:
+ strict-casts: true
+ strict-inference: true
+ strict-raw-types: true
+
+linter:
+ rules:
+ prefer_single_quotes: false
+ unawaited_futures: false
diff --git a/packages/just_audio/android/build.gradle b/packages/just_audio/android/build.gradle
new file mode 100644
index 00000000..ac46ef64
--- /dev/null
+++ b/packages/just_audio/android/build.gradle
@@ -0,0 +1,57 @@
+group 'com.ryanheise.just_audio'
+version '1.0'
+def args = ["-Xlint:deprecation","-Xlint:unchecked"]
+
+buildscript {
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath 'com.android.tools.build:gradle:8.5.0'
+ }
+}
+
+rootProject.allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+project.getTasks().withType(JavaCompile) {
+ options.compilerArgs.addAll(args)
+}
+
+apply plugin: 'com.android.library'
+
+android {
+ // Conditional for compatibility with AGP <4.2.
+ if (project.android.hasProperty("namespace")) {
+ namespace 'com.ryanheise.just_audio'
+ }
+ compileSdk 34
+
+ defaultConfig {
+ minSdk 16
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ lintOptions {
+ disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable'
+ }
+
+ compileOptions {
+ sourceCompatibility 1.8
+ targetCompatibility 1.8
+ }
+
+ dependencies {
+ def exoplayer_version = "1.4.1"
+ implementation "androidx.media3:media3-exoplayer:$exoplayer_version"
+ implementation "androidx.media3:media3-exoplayer-dash:$exoplayer_version"
+ implementation "androidx.media3:media3-exoplayer-hls:$exoplayer_version"
+ implementation "androidx.media3:media3-exoplayer-smoothstreaming:$exoplayer_version"
+ }
+}
diff --git a/packages/just_audio/android/gradle.properties b/packages/just_audio/android/gradle.properties
new file mode 100644
index 00000000..38c8d454
--- /dev/null
+++ b/packages/just_audio/android/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx1536M
+android.enableR8=true
+android.useAndroidX=true
+android.enableJetifier=true
diff --git a/packages/just_audio/android/settings.gradle b/packages/just_audio/android/settings.gradle
new file mode 100644
index 00000000..c17dc371
--- /dev/null
+++ b/packages/just_audio/android/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'just_audio'
diff --git a/packages/just_audio/android/src/main/AndroidManifest.xml b/packages/just_audio/android/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..e83e8416
--- /dev/null
+++ b/packages/just_audio/android/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.ryanheise.just_audio">
+</manifest>
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
new file mode 100644
index 00000000..fa49de27
--- /dev/null
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
@@ -0,0 +1,1110 @@
+package com.ryanheise.just_audio;
+
+import android.content.Context;
+import android.media.audiofx.AudioEffect;
+import android.media.audiofx.Equalizer;
+import android.media.audiofx.LoudnessEnhancer;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Handler;
+import android.os.Looper;
+import androidx.media3.common.C;
+import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl;
+import androidx.media3.exoplayer.DefaultLoadControl;
+import androidx.media3.exoplayer.DefaultRenderersFactory;
+import androidx.media3.exoplayer.ExoPlaybackException;
+import androidx.media3.exoplayer.LivePlaybackSpeedControl;
+import androidx.media3.exoplayer.LoadControl;
+import androidx.media3.exoplayer.RenderersFactory;
+import androidx.media3.exoplayer.audio.AudioSink;
+import androidx.media3.exoplayer.audio.DefaultAudioSink;
+import androidx.media3.common.MediaItem;
+import androidx.media3.common.PlaybackException;
+import androidx.media3.common.PlaybackParameters;
+import androidx.media3.common.Player;
+import androidx.media3.common.Player.PositionInfo;
+import androidx.media3.exoplayer.ExoPlayer;
+import androidx.media3.common.Timeline;
+import androidx.media3.common.Tracks;
+import androidx.media3.common.TrackSelectionParameters;
+import androidx.media3.common.TrackSelectionParameters.AudioOffloadPreferences;
+import androidx.media3.common.AudioAttributes;
+import androidx.media3.extractor.DefaultExtractorsFactory;
+import androidx.media3.common.Metadata;
+import androidx.media3.exoplayer.metadata.MetadataOutput;
+import androidx.media3.extractor.metadata.icy.IcyHeaders;
+import androidx.media3.extractor.metadata.icy.IcyInfo;
+import androidx.media3.exoplayer.source.ClippingMediaSource; // Deprecated
+// For some reason, this import triggers the [deprecation] warning, despite the
+// warnings being suppressed at each use.
+// import androidx.media3.exoplayer.source.ConcatenatingMediaSource; // Deprecated
+import androidx.media3.exoplayer.source.MediaSource; // Deprecated
+import androidx.media3.exoplayer.source.ProgressiveMediaSource; // Deprecated
+import androidx.media3.exoplayer.source.ShuffleOrder;
+import androidx.media3.exoplayer.source.ShuffleOrder.DefaultShuffleOrder;
+import androidx.media3.exoplayer.source.SilenceMediaSource; // Deprecated
+import androidx.media3.common.TrackGroup;
+import androidx.media3.exoplayer.dash.DashMediaSource; // Deprecated
+import androidx.media3.exoplayer.hls.HlsMediaSource; // Deprecated
+import androidx.media3.exoplayer.trackselection.TrackSelectionArray;
+import androidx.media3.datasource.DataSource;
+import androidx.media3.datasource.DefaultDataSource;
+import androidx.media3.datasource.DefaultHttpDataSource;
+import androidx.media3.common.MimeTypes;
+import androidx.media3.common.util.Util;
+import io.flutter.Log;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.EventChannel;
+import io.flutter.plugin.common.EventChannel.EventSink;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+
+public class AudioPlayer implements MethodCallHandler, Player.Listener, MetadataOutput {
+
+ static final String TAG = "AudioPlayer";
+
+ private static Random random = new Random();
+
+ private final Context context;
+ private final MethodChannel methodChannel;
+ private final BetterEventChannel eventChannel;
+ private final BetterEventChannel dataEventChannel;
+
+ private ProcessingState processingState;
+ private long updatePosition;
+ private long updateTime;
+ private long bufferedPosition;
+ private Long seekPos;
+ private long initialPos;
+ private Integer initialIndex;
+ private Result prepareResult;
+ private Result playResult;
+ private Result seekResult;
+ private Map<String, MediaSource> mediaSources = new HashMap<String, MediaSource>();
+ private IcyInfo icyInfo;
+ private IcyHeaders icyHeaders;
+ private int errorCount;
+ private AudioAttributes pendingAudioAttributes;
+ private LoadControl loadControl;
+ private boolean offloadSchedulingEnabled;
+ private LivePlaybackSpeedControl livePlaybackSpeedControl;
+ private List<Object> rawAudioEffects;
+ private List<AudioEffect> audioEffects = new ArrayList<AudioEffect>();
+ private Map<String, AudioEffect> audioEffectsMap = new HashMap<String, AudioEffect>();
+ private int lastPlaylistLength = 0;
+ private Map<String, Object> pendingPlaybackEvent;
+
+ private ExoPlayer player;
+ private Integer audioSessionId;
+ private MediaSource mediaSource;
+ private Integer currentIndex;
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private final Runnable bufferWatcher = new Runnable() {
+ @Override
+ public void run() {
+ if (player == null) {
+ return;
+ }
+
+ long newBufferedPosition = player.getBufferedPosition();
+ if (newBufferedPosition != bufferedPosition) {
+ // This method updates bufferedPosition.
+ broadcastImmediatePlaybackEvent();
+ }
+ switch (player.getPlaybackState()) {
+ case Player.STATE_BUFFERING:
+ handler.postDelayed(this, 200);
+ break;
+ case Player.STATE_READY:
+ if (player.getPlayWhenReady()) {
+ handler.postDelayed(this, 500);
+ } else {
+ handler.postDelayed(this, 1000);
+ }
+ break;
+ default:
+ // Stop watching buffer
+ }
+ }
+ };
+
+ public AudioPlayer(
+ final Context applicationContext,
+ final BinaryMessenger messenger,
+ final String id,
+ Map<?, ?> audioLoadConfiguration,
+ List<Object> rawAudioEffects,
+ Boolean offloadSchedulingEnabled
+ ) {
+ this.context = applicationContext;
+ this.rawAudioEffects = rawAudioEffects;
+ this.offloadSchedulingEnabled = offloadSchedulingEnabled != null ? offloadSchedulingEnabled : false;
+ methodChannel = new MethodChannel(messenger, "com.ryanheise.just_audio.methods." + id);
+ methodChannel.setMethodCallHandler(this);
+ eventChannel = new BetterEventChannel(messenger, "com.ryanheise.just_audio.events." + id);
+ dataEventChannel = new BetterEventChannel(messenger, "com.ryanheise.just_audio.data." + id);
+ processingState = ProcessingState.none;
+ if (audioLoadConfiguration != null) {
+ Map<?, ?> loadControlMap = (Map<?, ?>)audioLoadConfiguration.get("androidLoadControl");
+ if (loadControlMap != null) {
+ DefaultLoadControl.Builder builder = new DefaultLoadControl.Builder()
+ .setBufferDurationsMs(
+ (int)((getLong(loadControlMap.get("minBufferDuration")))/1000),
+ (int)((getLong(loadControlMap.get("maxBufferDuration")))/1000),
+ (int)((getLong(loadControlMap.get("bufferForPlaybackDuration")))/1000),
+ (int)((getLong(loadControlMap.get("bufferForPlaybackAfterRebufferDuration")))/1000)
+ )
+ .setPrioritizeTimeOverSizeThresholds((Boolean)loadControlMap.get("prioritizeTimeOverSizeThresholds"))
+ .setBackBuffer((int)((getLong(loadControlMap.get("backBufferDuration")))/1000), false);
+ if (loadControlMap.get("targetBufferBytes") != null) {
+ builder.setTargetBufferBytes((Integer)loadControlMap.get("targetBufferBytes"));
+ }
+ loadControl = builder.build();
+ }
+ Map<?, ?> livePlaybackSpeedControlMap = (Map<?, ?>)audioLoadConfiguration.get("androidLivePlaybackSpeedControl");
+ if (livePlaybackSpeedControlMap != null) {
+ DefaultLivePlaybackSpeedControl.Builder builder = new DefaultLivePlaybackSpeedControl.Builder()
+ .setFallbackMinPlaybackSpeed((float)((double)((Double)livePlaybackSpeedControlMap.get("fallbackMinPlaybackSpeed"))))
+ .setFallbackMaxPlaybackSpeed((float)((double)((Double)livePlaybackSpeedControlMap.get("fallbackMaxPlaybackSpeed"))))
+ .setMinUpdateIntervalMs(((getLong(livePlaybackSpeedControlMap.get("minUpdateInterval")))/1000))
+ .setProportionalControlFactor((float)((double)((Double)livePlaybackSpeedControlMap.get("proportionalControlFactor"))))
+ .setMaxLiveOffsetErrorMsForUnitSpeed(((getLong(livePlaybackSpeedControlMap.get("maxLiveOffsetErrorForUnitSpeed")))/1000))
+ .setTargetLiveOffsetIncrementOnRebufferMs(((getLong(livePlaybackSpeedControlMap.get("targetLiveOffsetIncrementOnRebuffer")))/1000))
+ .setMinPossibleLiveOffsetSmoothingFactor((float)((double)((Double)livePlaybackSpeedControlMap.get("minPossibleLiveOffsetSmoothingFactor"))));
+ livePlaybackSpeedControl = builder.build();
+ }
+ }
+ }
+
+ private void startWatchingBuffer() {
+ handler.removeCallbacks(bufferWatcher);
+ handler.post(bufferWatcher);
+ }
+
+ private void setAudioSessionId(int audioSessionId) {
+ if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) {
+ this.audioSessionId = null;
+ } else {
+ this.audioSessionId = audioSessionId;
+ }
+ clearAudioEffects();
+ if (this.audioSessionId != null) {
+ for (Object rawAudioEffect : rawAudioEffects) {
+ Map<?, ?> json = (Map<?, ?>)rawAudioEffect;
+ AudioEffect audioEffect = decodeAudioEffect(rawAudioEffect, this.audioSessionId);
+ if ((Boolean)json.get("enabled")) {
+ audioEffect.setEnabled(true);
+ }
+ audioEffects.add(audioEffect);
+ audioEffectsMap.put((String)json.get("type"), audioEffect);
+ }
+ }
+ enqueuePlaybackEvent();
+ }
+
+ @Override
+ public void onAudioSessionIdChanged(int audioSessionId) {
+ setAudioSessionId(audioSessionId);
+ broadcastPendingPlaybackEvent();
+ }
+
+ @Override
+ public void onMetadata(Metadata metadata) {
+ for (int i = 0; i < metadata.length(); i++) {
+ final Metadata.Entry entry = metadata.get(i);
+ if (entry instanceof IcyInfo) {
+ icyInfo = (IcyInfo) entry;
+ broadcastImmediatePlaybackEvent();
+ }
+ }
+ }
+
+ @Override
+ public void onTracksChanged(Tracks tracks) {
+ for (int i = 0; i < tracks.getGroups().size(); i++) {
+ TrackGroup trackGroup = tracks.getGroups().get(i).getMediaTrackGroup();
+
+ for (int j = 0; j < trackGroup.length; j++) {
+ Metadata metadata = trackGroup.getFormat(j).metadata;
+
+ if (metadata != null) {
+ for (int k = 0; k < metadata.length(); k++) {
+ final Metadata.Entry entry = metadata.get(k);
+ if (entry instanceof IcyHeaders) {
+ icyHeaders = (IcyHeaders) entry;
+ broadcastImmediatePlaybackEvent();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private boolean updatePositionIfChanged() {
+ if (getCurrentPosition() == updatePosition) return false;
+ updatePosition = getCurrentPosition();
+ updateTime = System.currentTimeMillis();
+ return true;
+ }
+
+ private void updatePosition() {
+ updatePosition = getCurrentPosition();
+ updateTime = System.currentTimeMillis();
+ }
+
+ @Override
+ public void onPositionDiscontinuity(PositionInfo oldPosition, PositionInfo newPosition, int reason) {
+ updatePosition();
+ switch (reason) {
+ case Player.DISCONTINUITY_REASON_AUTO_TRANSITION:
+ case Player.DISCONTINUITY_REASON_SEEK:
+ updateCurrentIndex();
+ break;
+ }
+ broadcastImmediatePlaybackEvent();
+ }
+
+ @Override
+ public void onTimelineChanged(Timeline timeline, int reason) {
+ if (initialPos != C.TIME_UNSET || initialIndex != null) {
+ int windowIndex = initialIndex != null ? initialIndex : 0;
+ player.seekTo(windowIndex, initialPos);
+ initialIndex = null;
+ initialPos = C.TIME_UNSET;
+ }
+ if (updateCurrentIndex()) {
+ broadcastImmediatePlaybackEvent();
+ }
+ if (player.getPlaybackState() == Player.STATE_ENDED) {
+ try {
+ if (player.getPlayWhenReady()) {
+ if (lastPlaylistLength == 0 && player.getMediaItemCount() > 0) {
+ player.seekTo(0, 0L);
+ } else if (player.hasNextMediaItem()) {
+ player.seekToNextMediaItem();
+ }
+ } else {
+ if (player.getCurrentMediaItemIndex() < player.getMediaItemCount()) {
+ player.seekTo(player.getCurrentMediaItemIndex(), 0L);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ lastPlaylistLength = player.getMediaItemCount();
+ }
+
+ private boolean updateCurrentIndex() {
+ Integer newIndex = player.getCurrentMediaItemIndex();
+ // newIndex is never null.
+ // currentIndex is sometimes null.
+ if (!newIndex.equals(currentIndex)) {
+ currentIndex = newIndex;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void onPlaybackStateChanged(int playbackState) {
+ switch (playbackState) {
+ case Player.STATE_READY:
+ if (player.getPlayWhenReady())
+ updatePosition();
+ processingState = ProcessingState.ready;
+ broadcastImmediatePlaybackEvent();
+ if (prepareResult != null) {
+ Map<String, Object> response = new HashMap<>();
+ response.put("duration", getDuration() == C.TIME_UNSET ? null : (1000 * getDuration()));
+ prepareResult.success(response);
+ prepareResult = null;
+ if (pendingAudioAttributes != null) {
+ player.setAudioAttributes(pendingAudioAttributes, false);
+ pendingAudioAttributes = null;
+ }
+ }
+ if (seekResult != null) {
+ completeSeek();
+ }
+ break;
+ case Player.STATE_BUFFERING:
+ updatePositionIfChanged();
+ if (processingState != ProcessingState.buffering && processingState != ProcessingState.loading) {
+ processingState = ProcessingState.buffering;
+ broadcastImmediatePlaybackEvent();
+ }
+ startWatchingBuffer();
+ break;
+ case Player.STATE_ENDED:
+ if (processingState != ProcessingState.completed) {
+ updatePosition();
+ processingState = ProcessingState.completed;
+ broadcastImmediatePlaybackEvent();
+ }
+ if (prepareResult != null) {
+ Map<String, Object> response = new HashMap<>();
+ prepareResult.success(response);
+ prepareResult = null;
+ if (pendingAudioAttributes != null) {
+ player.setAudioAttributes(pendingAudioAttributes, false);
+ pendingAudioAttributes = null;
+ }
+ }
+ if (playResult != null) {
+ playResult.success(new HashMap<String, Object>());
+ playResult = null;
+ }
+ break;
+ }
+ }
+
+ @Override
+ public void onPlayerError(PlaybackException error) {
+ if (error instanceof ExoPlaybackException) {
+ final ExoPlaybackException exoError = (ExoPlaybackException)error;
+ switch (exoError.type) {
+ case ExoPlaybackException.TYPE_SOURCE:
+ Log.e(TAG, "TYPE_SOURCE: " + exoError.getSourceException().getMessage());
+ break;
+
+ case ExoPlaybackException.TYPE_RENDERER:
+ Log.e(TAG, "TYPE_RENDERER: " + exoError.getRendererException().getMessage());
+ break;
+
+ case ExoPlaybackException.TYPE_UNEXPECTED:
+ Log.e(TAG, "TYPE_UNEXPECTED: " + exoError.getUnexpectedException().getMessage());
+ break;
+
+ default:
+ Log.e(TAG, "default ExoPlaybackException: " + exoError.getUnexpectedException().getMessage());
+ }
+ // TODO: send both errorCode and type
+ sendError(String.valueOf(exoError.type), exoError.getMessage(), mapOf("index", currentIndex));
+ } else {
+ Log.e(TAG, "default PlaybackException: " + error.getMessage());
+ sendError(String.valueOf(error.errorCode), error.getMessage(), mapOf("index", currentIndex));
+ }
+ errorCount++;
+ if (player.hasNextMediaItem() && currentIndex != null && errorCount <= 5) {
+ int nextIndex = currentIndex + 1;
+ Timeline timeline = player.getCurrentTimeline();
+ // This condition is due to: https://github.com/ryanheise/just_audio/pull/310
+ if (nextIndex < timeline.getWindowCount()) {
+ // TODO: pass in initial position here.
+ player.setMediaSource(mediaSource);
+ player.prepare();
+ player.seekTo(nextIndex, 0);
+ }
+ }
+ }
+
+ private void completeSeek() {
+ seekPos = null;
+ seekResult.success(new HashMap<String, Object>());
+ seekResult = null;
+ }
+
+ @Override
+ public void onMethodCall(final MethodCall call, final Result result) {
+ ensurePlayerInitialized();
+
+ try {
+ switch (call.method) {
+ case "load":
+ Long initialPosition = getLong(call.argument("initialPosition"));
+ Integer initialIndex = call.argument("initialIndex");
+ load(getAudioSource(call.argument("audioSource")),
+ initialPosition == null ? C.TIME_UNSET : initialPosition / 1000,
+ initialIndex, result);
+ break;
+ case "play":
+ play(result);
+ break;
+ case "pause":
+ pause();
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setVolume":
+ setVolume((float) ((double) ((Double) call.argument("volume"))));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setSpeed":
+ setSpeed((float) ((double) ((Double) call.argument("speed"))));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setPitch":
+ setPitch((float) ((double) ((Double) call.argument("pitch"))));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setSkipSilence":
+ setSkipSilenceEnabled((Boolean) call.argument("enabled"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setLoopMode":
+ setLoopMode((Integer) call.argument("loopMode"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setShuffleMode":
+ setShuffleModeEnabled((Integer) call.argument("shuffleMode") == 1);
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setShuffleOrder":
+ setShuffleOrder(call.argument("audioSource"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setAutomaticallyWaitsToMinimizeStalling":
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setCanUseNetworkResourcesForLiveStreamingWhilePaused":
+ result.success(new HashMap<String, Object>());
+ break;
+ case "setPreferredPeakBitRate":
+ result.success(new HashMap<String, Object>());
+ break;
+ case "seek":
+ Long position = getLong(call.argument("position"));
+ Integer index = call.argument("index");
+ seek(position == null ? C.TIME_UNSET : position / 1000, index, result);
+ break;
+ case "concatenatingInsertAll":
+ concatenating(call.argument("id"))
+ .addMediaSources(call.argument("index"), getAudioSources(call.argument("children")), handler, () -> result.success(new HashMap<String, Object>()));
+ concatenating(call.argument("id"))
+ .setShuffleOrder(decodeShuffleOrder(call.argument("shuffleOrder")));
+ break;
+ case "concatenatingRemoveRange":
+ concatenating(call.argument("id"))
+ .removeMediaSourceRange(call.argument("startIndex"), call.argument("endIndex"), handler, () -> result.success(new HashMap<String, Object>()));
+ concatenating(call.argument("id"))
+ .setShuffleOrder(decodeShuffleOrder(call.argument("shuffleOrder")));
+ break;
+ case "concatenatingMove":
+ concatenating(call.argument("id"))
+ .moveMediaSource(call.argument("currentIndex"), call.argument("newIndex"), handler, () -> result.success(new HashMap<String, Object>()));
+ concatenating(call.argument("id"))
+ .setShuffleOrder(decodeShuffleOrder(call.argument("shuffleOrder")));
+ break;
+ case "setAndroidAudioAttributes":
+ setAudioAttributes(call.argument("contentType"), call.argument("flags"), call.argument("usage"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "audioEffectSetEnabled":
+ audioEffectSetEnabled(call.argument("type"), call.argument("enabled"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "androidLoudnessEnhancerSetTargetGain":
+ loudnessEnhancerSetTargetGain(call.argument("targetGain"));
+ result.success(new HashMap<String, Object>());
+ break;
+ case "androidEqualizerGetParameters":
+ result.success(equalizerAudioEffectGetParameters());
+ break;
+ case "androidEqualizerBandSetGain":
+ equalizerBandSetGain(call.argument("bandIndex"), call.argument("gain"));
+ result.success(new HashMap<String, Object>());
+ break;
+ default:
+ result.notImplemented();
+ break;
+ }
+ } catch (IllegalStateException e) {
+ e.printStackTrace();
+ result.error("Illegal state: " + e.getMessage(), e.toString(), null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ result.error("Error: " + e, e.toString(), null);
+ } finally {
+ broadcastPendingPlaybackEvent();
+ }
+ }
+
+ private ShuffleOrder decodeShuffleOrder(List<Integer> indexList) {
+ int[] shuffleIndices = new int[indexList.size()];
+ for (int i = 0; i < shuffleIndices.length; i++) {
+ shuffleIndices[i] = indexList.get(i);
+ }
+ return new DefaultShuffleOrder(shuffleIndices, random.nextLong());
+ }
+
+ private static int[] shuffle(int length, Integer firstIndex) {
+ final int[] shuffleOrder = new int[length];
+ for (int i = 0; i < length; i++) {
+ final int j = random.nextInt(i + 1);
+ shuffleOrder[i] = shuffleOrder[j];
+ shuffleOrder[j] = i;
+ }
+ if (firstIndex != null) {
+ for (int i = 1; i < length; i++) {
+ if (shuffleOrder[i] == firstIndex) {
+ final int v = shuffleOrder[0];
+ shuffleOrder[0] = shuffleOrder[i];
+ shuffleOrder[i] = v;
+ break;
+ }
+ }
+ }
+ return shuffleOrder;
+ }
+
+ // Create a shuffle order optionally fixing the first index.
+ private ShuffleOrder createShuffleOrder(int length, Integer firstIndex) {
+ int[] shuffleIndices = shuffle(length, firstIndex);
+ return new DefaultShuffleOrder(shuffleIndices, random.nextLong());
+ }
+
+
+ @SuppressWarnings("deprecation")
+ private androidx.media3.exoplayer.source.ConcatenatingMediaSource concatenating(final Object index) {
+ return (androidx.media3.exoplayer.source.ConcatenatingMediaSource)mediaSources.get((String)index);
+ }
+
+ @SuppressWarnings("deprecation")
+ private void setShuffleOrder(final Object json) {
+ Map<?, ?> map = (Map<?, ?>)json;
+ String id = mapGet(map, "id");
+ MediaSource mediaSource = mediaSources.get(id);
+ if (mediaSource == null) return;
+ switch ((String)mapGet(map, "type")) {
+ case "concatenating":
+ androidx.media3.exoplayer.source.ConcatenatingMediaSource concatenatingMediaSource = (androidx.media3.exoplayer.source.ConcatenatingMediaSource)mediaSource;
+ concatenatingMediaSource.setShuffleOrder(decodeShuffleOrder(mapGet(map, "shuffleOrder")));
+ List<Object> children = mapGet(map, "children");
+ for (Object child : children) {
+ setShuffleOrder(child);
+ }
+ break;
+ case "looping":
+ setShuffleOrder(mapGet(map, "child"));
+ break;
+ }
+ }
+
+ private MediaSource getAudioSource(final Object json) {
+ Map<?, ?> map = (Map<?, ?>)json;
+ String id = (String)map.get("id");
+ MediaSource mediaSource = mediaSources.get(id);
+ if (mediaSource == null) {
+ mediaSource = decodeAudioSource(map);
+ mediaSources.put(id, mediaSource);
+ }
+ return mediaSource;
+ }
+
+ private DefaultExtractorsFactory buildExtractorsFactory(Map<?, ?> options) {
+ DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
+ boolean constantBitrateSeekingEnabled = true;
+ boolean constantBitrateSeekingAlwaysEnabled = false;
+ int mp3Flags = 0;
+ if (options != null) {
+ Map<?, ?> androidExtractorOptions = (Map<?, ?>)options.get("androidExtractorOptions");
+ if (androidExtractorOptions != null) {
+ constantBitrateSeekingEnabled = (Boolean)androidExtractorOptions.get("constantBitrateSeekingEnabled");
+ constantBitrateSeekingAlwaysEnabled = (Boolean)androidExtractorOptions.get("constantBitrateSeekingAlwaysEnabled");
+ mp3Flags = (Integer)androidExtractorOptions.get("mp3Flags");
+ }
+ }
+ extractorsFactory.setConstantBitrateSeekingEnabled(constantBitrateSeekingEnabled);
+ extractorsFactory.setConstantBitrateSeekingAlwaysEnabled(constantBitrateSeekingAlwaysEnabled);
+ extractorsFactory.setMp3ExtractorFlags(mp3Flags);
+ return extractorsFactory;
+ }
+
+ @SuppressWarnings("deprecation")
+ private MediaSource decodeAudioSource(final Object json) {
+ Map<?, ?> map = (Map<?, ?>)json;
+ String id = (String)map.get("id");
+ switch ((String)map.get("type")) {
+ case "progressive":
+ return new ProgressiveMediaSource.Factory(buildDataSourceFactory(mapGet(map, "headers")), buildExtractorsFactory(mapGet(map, "options")))
+ .createMediaSource(new MediaItem.Builder()
+ .setUri(Uri.parse((String)map.get("uri")))
+ .setTag(id)
+ .build());
+ case "dash":
+ return new DashMediaSource.Factory(buildDataSourceFactory(mapGet(map, "headers")))
+ .createMediaSource(new MediaItem.Builder()
+ .setUri(Uri.parse((String)map.get("uri")))
+ .setMimeType(MimeTypes.APPLICATION_MPD)
+ .setTag(id)
+ .build());
+ case "hls":
+ return new HlsMediaSource.Factory(buildDataSourceFactory(mapGet(map, "headers")))
+ .createMediaSource(new MediaItem.Builder()
+ .setUri(Uri.parse((String)map.get("uri")))
+ .setMimeType(MimeTypes.APPLICATION_M3U8)
+ .build());
+ case "silence":
+ return new SilenceMediaSource.Factory()
+ .setDurationUs(getLong(map.get("duration")))
+ .setTag(id)
+ .createMediaSource();
+ case "concatenating":
+ MediaSource[] mediaSources = getAudioSourcesArray(map.get("children"));
+ return new androidx.media3.exoplayer.source.ConcatenatingMediaSource(
+ false, // isAtomic
+ (Boolean)map.get("useLazyPreparation"),
+ decodeShuffleOrder(mapGet(map, "shuffleOrder")),
+ mediaSources);
+ case "clipping":
+ Long start = getLong(map.get("start"));
+ Long end = getLong(map.get("end"));
+ return new ClippingMediaSource(getAudioSource(map.get("child")),
+ start != null ? start : 0,
+ end != null ? end : C.TIME_END_OF_SOURCE);
+ case "looping":
+ Integer count = (Integer)map.get("count");
+ MediaSource looperChild = getAudioSource(map.get("child"));
+ MediaSource[] looperChildren = new MediaSource[count];
+ for (int i = 0; i < looperChildren.length; i++) {
+ looperChildren[i] = looperChild;
+ }
+ return new androidx.media3.exoplayer.source.ConcatenatingMediaSource(looperChildren);
+ default:
+ throw new IllegalArgumentException("Unknown AudioSource type: " + map.get("type"));
+ }
+ }
+
+ private MediaSource[] getAudioSourcesArray(final Object json) {
+ List<MediaSource> mediaSources = getAudioSources(json);
+ MediaSource[] mediaSourcesArray = new MediaSource[mediaSources.size()];
+ mediaSources.toArray(mediaSourcesArray);
+ return mediaSourcesArray;
+ }
+
+ private List<MediaSource> getAudioSources(final Object json) {
+ if (!(json instanceof List)) throw new RuntimeException("List expected: " + json);
+ List<?> audioSources = (List<?>)json;
+ List<MediaSource> mediaSources = new ArrayList<MediaSource>();
+ for (int i = 0 ; i < audioSources.size(); i++) {
+ mediaSources.add(getAudioSource(audioSources.get(i)));
+ }
+ return mediaSources;
+ }
+
+ private AudioEffect decodeAudioEffect(final Object json, int audioSessionId) {
+ Map<?, ?> map = (Map<?, ?>)json;
+ String type = (String)map.get("type");
+ switch (type) {
+ case "AndroidLoudnessEnhancer":
+ if (Build.VERSION.SDK_INT < 19)
+ throw new RuntimeException("AndroidLoudnessEnhancer requires minSdkVersion >= 19");
+ int targetGain = (int)Math.round((((Double)map.get("targetGain")) * 1000.0));
+ LoudnessEnhancer loudnessEnhancer = new LoudnessEnhancer(audioSessionId);
+ loudnessEnhancer.setTargetGain(targetGain);
+ return loudnessEnhancer;
+ case "AndroidEqualizer":
+ Equalizer equalizer = new Equalizer(0, audioSessionId);
+ return equalizer;
+ default:
+ throw new IllegalArgumentException("Unknown AudioEffect type: " + map.get("type"));
+ }
+ }
+
+ private void clearAudioEffects() {
+ for (Iterator<AudioEffect> it = audioEffects.iterator(); it.hasNext();) {
+ AudioEffect audioEffect = it.next();
+ audioEffect.release();
+ it.remove();
+ }
+ audioEffectsMap.clear();
+ }
+
+ private DataSource.Factory buildDataSourceFactory(Map<?, ?> headers) {
+ final Map<String, String> stringHeaders = castToStringMap(headers);
+ String userAgent = null;
+ if (stringHeaders != null) {
+ userAgent = stringHeaders.remove("User-Agent");
+ if (userAgent == null) {
+ userAgent = stringHeaders.remove("user-agent");
+ }
+ }
+ if (userAgent == null) {
+ userAgent = Util.getUserAgent(context, "just_audio");
+ }
+ DefaultHttpDataSource.Factory httpDataSourceFactory = new DefaultHttpDataSource.Factory()
+ .setUserAgent(userAgent)
+ .setAllowCrossProtocolRedirects(true);
+ if (stringHeaders != null && stringHeaders.size() > 0) {
+ httpDataSourceFactory.setDefaultRequestProperties(stringHeaders);
+ }
+ return new DefaultDataSource.Factory(context, httpDataSourceFactory);
+ }
+
+ private void load(final MediaSource mediaSource, final long initialPosition, final Integer initialIndex, final Result result) {
+ this.initialPos = initialPosition;
+ this.initialIndex = initialIndex;
+ currentIndex = initialIndex != null ? initialIndex : 0;
+ switch (processingState) {
+ case none:
+ break;
+ case loading:
+ abortExistingConnection();
+ player.stop();
+ break;
+ default:
+ player.stop();
+ break;
+ }
+ errorCount = 0;
+ prepareResult = result;
+ updatePosition();
+ processingState = ProcessingState.loading;
+ enqueuePlaybackEvent();
+ this.mediaSource = mediaSource;
+ // TODO: pass in initial position here.
+ player.setMediaSource(mediaSource);
+ player.prepare();
+ }
+
+ private void ensurePlayerInitialized() {
+ if (player == null) {
+ androidx.media3.common.audio.SonicAudioProcessor sonicAudioProcessor = new androidx.media3.common.audio.SonicAudioProcessor();
+ RenderersFactory renderersFactory = new DefaultRenderersFactory(context) {
+ @Override
+ protected AudioSink buildAudioSink(
+ Context context,
+ boolean enableFloatOutput,
+ boolean enableAudioTrackPlaybackParams) {
+ Log.i(TAG, "PATCH ACTIVE: buildAudioSink with SonicAudioProcessor, AudioTrack speed DISABLED");
+ return new DefaultAudioSink.Builder(context)
+ .setEnableFloatOutput(enableFloatOutput)
+ .setEnableAudioTrackPlaybackParams(false)
+ .setAudioProcessors(new androidx.media3.common.audio.AudioProcessor[]{sonicAudioProcessor})
+ .build();
+ }
+ };
+ ExoPlayer.Builder builder = new ExoPlayer.Builder(context, renderersFactory);
+ if (loadControl != null) {
+ builder.setLoadControl(loadControl);
+ }
+ if (livePlaybackSpeedControl != null) {
+ builder.setLivePlaybackSpeedControl(livePlaybackSpeedControl);
+ }
+ player = builder.build();
+ // player.setTrackSelectionParameters(
+ // player.getTrackSelectionParameters()
+ // .buildUpon()
+ // .setAudioOffloadPreferences(
+ // new AudioOffloadPreferences.Builder()
+ // .setIsGaplessSupportRequired(!offloadSchedulingEnabled)
+ // .setIsSpeedChangeSupportRequired(!offloadSchedulingEnabled)
+ // .setAudioOffloadMode(AudioOffloadPreferences.AUDIO_OFFLOAD_MODE_ENABLED)
+ // .build()
+ // )
+ // .build()
+ // );
+ setAudioSessionId(player.getAudioSessionId());
+ player.addListener(this);
+ }
+ }
+
+ private void setAudioAttributes(int contentType, int flags, int usage) {
+ AudioAttributes.Builder builder = new AudioAttributes.Builder();
+ builder.setContentType(contentType);
+ builder.setFlags(flags);
+ builder.setUsage(usage);
+ //builder.setAllowedCapturePolicy((Integer)json.get("allowedCapturePolicy"));
+ AudioAttributes audioAttributes = builder.build();
+ if (processingState == ProcessingState.loading) {
+ // audio attributes should be set either before or after loading to
+ // avoid an ExoPlayer glitch.
+ pendingAudioAttributes = audioAttributes;
+ } else {
+ player.setAudioAttributes(audioAttributes, false);
+ }
+ }
+
+ private void audioEffectSetEnabled(String type, boolean enabled) {
+ audioEffectsMap.get(type).setEnabled(enabled);
+ }
+
+ private void loudnessEnhancerSetTargetGain(double targetGain) {
+ int targetGainMillibels = (int)Math.round(targetGain * 1000.0);
+ ((LoudnessEnhancer)audioEffectsMap.get("AndroidLoudnessEnhancer")).setTargetGain(targetGainMillibels);
+ }
+
+ private Map<String, Object> equalizerAudioEffectGetParameters() {
+ Equalizer equalizer = (Equalizer)audioEffectsMap.get("AndroidEqualizer");
+ ArrayList<Object> rawBands = new ArrayList<>();
+ for (short i = 0; i < equalizer.getNumberOfBands(); i++) {
+ rawBands.add(mapOf(
+ "index", i,
+ "lowerFrequency", (double)equalizer.getBandFreqRange(i)[0] / 1000.0,
+ "upperFrequency", (double)equalizer.getBandFreqRange(i)[1] / 1000.0,
+ "centerFrequency", (double)equalizer.getCenterFreq(i) / 1000.0,
+ "gain", equalizer.getBandLevel(i) / 1000.0
+ ));
+ }
+ return mapOf(
+ "parameters", mapOf(
+ "minDecibels", equalizer.getBandLevelRange()[0] / 1000.0,
+ "maxDecibels", equalizer.getBandLevelRange()[1] / 1000.0,
+ "bands", rawBands
+ )
+ );
+ }
+
+ private void equalizerBandSetGain(int bandIndex, double gain) {
+ ((Equalizer)audioEffectsMap.get("AndroidEqualizer")).setBandLevel((short)bandIndex, (short)(Math.round(gain * 1000.0)));
+ }
+
+ /// Creates an event based on the current state.
+ private Map<String, Object> createPlaybackEvent() {
+ final Map<String, Object> event = new HashMap<String, Object>();
+ Long duration = getDuration() == C.TIME_UNSET ? null : (1000 * getDuration());
+ bufferedPosition = player != null ? player.getBufferedPosition() : 0L;
+ event.put("processingState", processingState.ordinal());
+ event.put("updatePosition", 1000 * updatePosition);
+ event.put("updateTime", updateTime);
+ event.put("bufferedPosition", 1000 * Math.max(updatePosition, bufferedPosition));
+ event.put("icyMetadata", collectIcyMetadata());
+ event.put("duration", duration);
+ event.put("currentIndex", currentIndex);
+ event.put("androidAudioSessionId", audioSessionId);
+ return event;
+ }
+
+ // Broadcast the pending playback event if it was set.
+ private void broadcastPendingPlaybackEvent() {
+ if (pendingPlaybackEvent != null) {
+ eventChannel.success(pendingPlaybackEvent);
+ pendingPlaybackEvent = null;
+ }
+ }
+
+ private void enqueuePlaybackEvent() {
+ final Map<String, Object> event = new HashMap<String, Object>();
+ pendingPlaybackEvent = createPlaybackEvent();
+ }
+
+ // Broadcasts a new event immediately.
+ private void broadcastImmediatePlaybackEvent() {
+ enqueuePlaybackEvent();
+ broadcastPendingPlaybackEvent();
+ }
+
+ private Map<String, Object> collectIcyMetadata() {
+ final Map<String, Object> icyData = new HashMap<>();
+ if (icyInfo != null) {
+ final Map<String, String> info = new HashMap<>();
+ info.put("title", icyInfo.title);
+ info.put("url", icyInfo.url);
+ icyData.put("info", info);
+ }
+ if (icyHeaders != null) {
+ final Map<String, Object> headers = new HashMap<>();
+ headers.put("bitrate", icyHeaders.bitrate);
+ headers.put("genre", icyHeaders.genre);
+ headers.put("name", icyHeaders.name);
+ headers.put("metadataInterval", icyHeaders.metadataInterval);
+ headers.put("url", icyHeaders.url);
+ headers.put("isPublic", icyHeaders.isPublic);
+ icyData.put("headers", headers);
+ }
+ return icyData;
+ }
+
+ private long getCurrentPosition() {
+ if (initialPos != C.TIME_UNSET) {
+ return initialPos;
+ } else if (processingState == ProcessingState.none || processingState == ProcessingState.loading) {
+ long pos = player.getCurrentPosition();
+ if (pos < 0) pos = 0;
+ return pos;
+ } else if (seekPos != null && seekPos != C.TIME_UNSET) {
+ return seekPos;
+ } else {
+ return player.getCurrentPosition();
+ }
+ }
+
+ private long getDuration() {
+ if (processingState == ProcessingState.none || processingState == ProcessingState.loading || player == null) {
+ return C.TIME_UNSET;
+ } else {
+ return player.getDuration();
+ }
+ }
+
+ private void sendError(String errorCode, String errorMsg) {
+ sendError(errorCode, errorMsg, null);
+ }
+
+ private void sendError(String errorCode, String errorMsg, Object details) {
+ if (prepareResult != null) {
+ prepareResult.error(errorCode, errorMsg, details);
+ prepareResult = null;
+ }
+
+ eventChannel.error(errorCode, errorMsg, details);
+ }
+
+ private String getLowerCaseExtension(Uri uri) {
+ String fragment = uri.getFragment();
+ String filename = fragment != null && fragment.contains(".") ? fragment : uri.getPath();
+ return filename.replaceAll("^.*\\.", "").toLowerCase();
+ }
+
+ public void play(Result result) {
+ if (player.getPlayWhenReady()) {
+ result.success(new HashMap<String, Object>());
+ return;
+ }
+ if (playResult != null) {
+ playResult.success(new HashMap<String, Object>());
+ }
+ playResult = result;
+ player.setPlayWhenReady(true);
+ updatePosition();
+ if (processingState == ProcessingState.completed && playResult != null) {
+ playResult.success(new HashMap<String, Object>());
+ playResult = null;
+ }
+ }
+
+ public void pause() {
+ if (!player.getPlayWhenReady()) return;
+ player.setPlayWhenReady(false);
+ updatePosition();
+ if (playResult != null) {
+ playResult.success(new HashMap<String, Object>());
+ playResult = null;
+ }
+ }
+
+ public void setVolume(final float volume) {
+ player.setVolume(volume);
+ }
+
+ public void setSpeed(final float speed) {
+ PlaybackParameters params = player.getPlaybackParameters();
+ if (params.speed == speed) return;
+ player.setPlaybackParameters(new PlaybackParameters(speed, params.pitch));
+ if (player.getPlayWhenReady())
+ updatePosition();
+ enqueuePlaybackEvent();
+ }
+
+ public void setPitch(final float pitch) {
+ PlaybackParameters params = player.getPlaybackParameters();
+ if (params.pitch == pitch) return;
+ player.setPlaybackParameters(new PlaybackParameters(params.speed, pitch));
+ enqueuePlaybackEvent();
+ }
+
+ public void setSkipSilenceEnabled(final boolean enabled) {
+ player.setSkipSilenceEnabled(enabled);
+ }
+
+ public void setLoopMode(final int mode) {
+ player.setRepeatMode(mode);
+ }
+
+ public void setShuffleModeEnabled(final boolean enabled) {
+ player.setShuffleModeEnabled(enabled);
+ }
+
+ public void seek(final long position, final Integer index, final Result result) {
+ if (processingState == ProcessingState.none || processingState == ProcessingState.loading) {
+ result.success(new HashMap<String, Object>());
+ return;
+ }
+ abortSeek();
+ seekPos = position;
+ seekResult = result;
+ try {
+ int windowIndex = index != null ? index : player.getCurrentMediaItemIndex();
+ player.seekTo(windowIndex, position);
+ } catch (RuntimeException e) {
+ seekResult = null;
+ seekPos = null;
+ throw e;
+ }
+ }
+
+ public void dispose() {
+ if (processingState == ProcessingState.loading) {
+ abortExistingConnection();
+ }
+ if (playResult != null) {
+ playResult.success(new HashMap<String, Object>());
+ playResult = null;
+ }
+ mediaSources.clear();
+ mediaSource = null;
+ clearAudioEffects();
+ if (player != null) {
+ player.release();
+ player = null;
+ processingState = ProcessingState.none;
+ broadcastImmediatePlaybackEvent();
+ }
+ eventChannel.endOfStream();
+ dataEventChannel.endOfStream();
+ }
+
+ private void abortSeek() {
+ if (seekResult != null) {
+ try {
+ seekResult.success(new HashMap<String, Object>());
+ } catch (RuntimeException e) {
+ // Result already sent
+ }
+ seekResult = null;
+ seekPos = null;
+ }
+ }
+
+ private void abortExistingConnection() {
+ sendError("abort", "Connection aborted");
+ }
+
+ public static Long getLong(Object o) {
+ return (o == null || o instanceof Long) ? (Long)o : Long.valueOf(((Integer)o).intValue());
+ }
+
+ @SuppressWarnings("unchecked")
+ static <T> T mapGet(Object o, String key) {
+ if (o instanceof Map) {
+ return (T) ((Map<?, ?>)o).get(key);
+ } else {
+ return null;
+ }
+ }
+
+ static Map<String, Object> mapOf(Object... args) {
+ Map<String, Object> map = new HashMap<>();
+ for (int i = 0; i < args.length; i += 2) {
+ map.put((String)args[i], args[i + 1]);
+ }
+ return map;
+ }
+
+ static Map<String, String> castToStringMap(Map<?, ?> map) {
+ if (map == null) return null;
+ Map<String, String> map2 = new HashMap<>();
+ for (Object key : map.keySet()) {
+ map2.put((String)key, (String)map.get(key));
+ }
+ return map2;
+ }
+
+ enum ProcessingState {
+ none,
+ loading,
+ buffering,
+ ready,
+ completed
+ }
+}
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/BetterEventChannel.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/BetterEventChannel.java
new file mode 100644
index 00000000..2fdb4436
--- /dev/null
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/BetterEventChannel.java
@@ -0,0 +1,39 @@
+package com.ryanheise.just_audio;
+
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.EventChannel;
+import io.flutter.plugin.common.EventChannel.EventSink;
+
+public class BetterEventChannel implements EventSink {
+ private EventSink eventSink;
+
+ public BetterEventChannel(final BinaryMessenger messenger, final String id) {
+ EventChannel eventChannel = new EventChannel(messenger, id);
+ eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
+ @Override
+ public void onListen(final Object arguments, final EventSink eventSink) {
+ BetterEventChannel.this.eventSink = eventSink;
+ }
+
+ @Override
+ public void onCancel(final Object arguments) {
+ eventSink = null;
+ }
+ });
+ }
+
+ @Override
+ public void success(Object event) {
+ if (eventSink != null) eventSink.success(event);
+ }
+
+ @Override
+ public void error(String errorCode, String errorMessage, Object errorDetails) {
+ if (eventSink != null) eventSink.error(errorCode, errorMessage, errorDetails);
+ }
+
+ @Override
+ public void endOfStream() {
+ if (eventSink != null) eventSink.endOfStream();
+ }
+}
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/JustAudioPlugin.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/JustAudioPlugin.java
new file mode 100644
index 00000000..c3ed48b3
--- /dev/null
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/JustAudioPlugin.java
@@ -0,0 +1,50 @@
+package com.ryanheise.just_audio;
+
+import android.content.Context;
+import androidx.annotation.NonNull;
+import io.flutter.embedding.engine.FlutterEngine;
+import io.flutter.embedding.engine.FlutterEngine.EngineLifecycleListener;
+import io.flutter.embedding.engine.plugins.FlutterPlugin;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+
+/**
+ * JustAudioPlugin
+ */
+public class JustAudioPlugin implements FlutterPlugin {
+ private MethodChannel channel;
+ private MainMethodCallHandler methodCallHandler;
+
+ @Override
+ public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
+ Context applicationContext = binding.getApplicationContext();
+ BinaryMessenger messenger = binding.getBinaryMessenger();
+ methodCallHandler = new MainMethodCallHandler(applicationContext, messenger);
+
+ channel = new MethodChannel(messenger, "com.ryanheise.just_audio.methods");
+ channel.setMethodCallHandler(methodCallHandler);
+ @SuppressWarnings("deprecation")
+ FlutterEngine engine = binding.getFlutterEngine();
+ engine.addEngineLifecycleListener(new EngineLifecycleListener() {
+ @Override
+ public void onPreEngineRestart() {
+ methodCallHandler.dispose();
+ }
+
+ @Override
+ public void onEngineWillDestroy() {
+ }
+ });
+ }
+
+ @Override
+ public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
+ methodCallHandler.dispose();
+ methodCallHandler = null;
+
+ channel.setMethodCallHandler(null);
+ }
+}
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java
new file mode 100644
index 00000000..916423e9
--- /dev/null
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java
@@ -0,0 +1,78 @@
+package com.ryanheise.just_audio;
+
+import android.content.Context;
+import androidx.annotation.NonNull;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Map;
+
+public class MainMethodCallHandler implements MethodCallHandler {
+
+ private final Context applicationContext;
+ private final BinaryMessenger messenger;
+
+ private final Map<String, AudioPlayer> players = new HashMap<>();
+
+ public MainMethodCallHandler(Context applicationContext,
+ BinaryMessenger messenger) {
+ this.applicationContext = applicationContext;
+ this.messenger = messenger;
+ }
+
+ @Override
+ public void onMethodCall(MethodCall call, @NonNull Result result) {
+ switch (call.method) {
+ case "init": {
+ String id = call.argument("id");
+ if (players.containsKey(id)) {
+ result.error("Platform player " + id + " already exists", null, null);
+ break;
+ }
+ List<Object> rawAudioEffects = call.argument("androidAudioEffects");
+ players.put(
+ id,
+ new AudioPlayer(
+ applicationContext,
+ messenger,
+ id,
+ call.argument("audioLoadConfiguration"),
+ rawAudioEffects,
+ call.argument("androidOffloadSchedulingEnabled")
+ )
+ );
+ result.success(null);
+ break;
+ }
+ case "disposePlayer": {
+ String id = call.argument("id");
+ AudioPlayer player = players.get(id);
+ if (player != null) {
+ player.dispose();
+ players.remove(id);
+ }
+ result.success(new HashMap<String, Object>());
+ break;
+ }
+ case "disposeAllPlayers": {
+ dispose();
+ result.success(new HashMap<String, Object>());
+ break;
+ }
+ default:
+ result.notImplemented();
+ break;
+ }
+ }
+
+ void dispose() {
+ for (AudioPlayer player : new ArrayList<AudioPlayer>(players.values())) {
+ player.dispose();
+ }
+ players.clear();
+ }
+}
diff --git a/packages/just_audio/darwin/just_audio.podspec b/packages/just_audio/darwin/just_audio.podspec
new file mode 100644
index 00000000..0805c37d
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio.podspec
@@ -0,0 +1,22 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
+#
+Pod::Spec.new do |s|
+ s.name = 'just_audio'
+ s.version = '0.0.1'
+ s.summary = 'Flutter audio player'
+ s.description = <<-DESC
+A flutter plugin for playing audio.
+ DESC
+ s.homepage = 'https://github.com/ryanheise/just_audio'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Your Company' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'just_audio/Sources/just_audio/**/*.{h,m}'
+ s.public_header_files = 'just_audio/Sources/just_audio/include/**/*.h'
+ s.ios.dependency 'Flutter'
+ s.osx.dependency 'FlutterMacOS'
+ s.ios.deployment_target = '12.0'
+ s.osx.deployment_target = '10.14'
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
+end
diff --git a/packages/just_audio/darwin/just_audio/Package.swift b/packages/just_audio/darwin/just_audio/Package.swift
new file mode 100644
index 00000000..e711aeb8
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Package.swift
@@ -0,0 +1,25 @@
+// swift-tools-version: 5.9
+// The swift-tools-version declares the minimum version of Swift required to build this package.
+
+import PackageDescription
+
+let package = Package(
+ name: "just_audio",
+ platforms: [
+ .iOS("12.0"),
+ .macOS("10.14")
+ ],
+ products: [
+ .library(name: "just-audio", targets: ["just_audio"])
+ ],
+ dependencies: [],
+ targets: [
+ .target(
+ name: "just_audio",
+ dependencies: [],
+ cSettings: [
+ .headerSearchPath("include/just_audio")
+ ]
+ )
+ ]
+)
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m
new file mode 100644
index 00000000..f359ea67
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m
@@ -0,0 +1,1376 @@
+#import "./include/just_audio/BetterEventChannel.h"
+#import "./include/just_audio/AudioPlayer.h"
+#import "./include/just_audio/AudioSource.h"
+#import "./include/just_audio/IndexedAudioSource.h"
+#import "./include/just_audio/LoadControl.h"
+#import "./include/just_audio/UriAudioSource.h"
+#import "./include/just_audio/ConcatenatingAudioSource.h"
+#import "./include/just_audio/LoopingAudioSource.h"
+#import "./include/just_audio/ClippingAudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+#import <stdlib.h>
+#include <TargetConditionals.h>
+
+#define TREADMILL_SIZE 2
+
+// TODO: Check for and report invalid state transitions.
+// TODO: Apply Apple's guidance on seeking: https://developer.apple.com/library/archive/qa/qa1820/_index.html
+@implementation AudioPlayer {
+ NSObject<FlutterPluginRegistrar>* _registrar;
+ FlutterMethodChannel *_methodChannel;
+ BetterEventChannel *_eventChannel;
+ BetterEventChannel *_dataEventChannel;
+ NSString *_playerId;
+ AVQueuePlayer *_player;
+ AudioSource *_audioSource;
+ NSMutableArray<IndexedAudioSource *> *_indexedAudioSources;
+ NSArray<NSNumber *> *_order;
+ NSMutableArray<NSNumber *> *_orderInv;
+ int _index;
+ enum ProcessingState _processingState;
+ enum LoopMode _loopMode;
+ BOOL _shuffleModeEnabled;
+ long long _updateTime;
+ int _updatePosition;
+ int _lastPosition;
+ int _bufferedPosition;
+ // Set when the current item hasn't been played yet so we aren't sure whether sufficient audio has been buffered.
+ BOOL _bufferUnconfirmed;
+ CMTime _seekPos;
+ FlutterResult _loadResult;
+ FlutterResult _playResult;
+ id _timeObserver;
+ BOOL _automaticallyWaitsToMinimizeStalling;
+ BOOL _allowsExternalPlayback;
+ LoadControl *_loadControl;
+ BOOL _playing;
+ float _speed;
+ float _volume;
+ BOOL _justAdvanced;
+ BOOL _enqueuedAll;
+ NSDictionary<NSString *, NSObject *> *_icyMetadata;
+}
+
+- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar playerId:(NSString*)idParam loadConfiguration:(NSDictionary *)loadConfiguration {
+ self = [super init];
+ NSAssert(self, @"super init cannot be nil");
+ _registrar = registrar;
+ _playerId = idParam;
+ _methodChannel =
+ [FlutterMethodChannel methodChannelWithName:[NSMutableString stringWithFormat:@"com.ryanheise.just_audio.methods.%@", _playerId]
+ binaryMessenger:[registrar messenger]];
+ _eventChannel = [[BetterEventChannel alloc]
+ initWithName:[NSMutableString stringWithFormat:@"com.ryanheise.just_audio.events.%@", _playerId]
+ messenger:[registrar messenger]];
+ _dataEventChannel = [[BetterEventChannel alloc]
+ initWithName:[NSMutableString stringWithFormat:@"com.ryanheise.just_audio.data.%@", _playerId]
+ messenger:[registrar messenger]];
+ _index = 0;
+ _processingState = none;
+ _loopMode = loopOff;
+ _shuffleModeEnabled = NO;
+ _player = nil;
+ _audioSource = nil;
+ _indexedAudioSources = nil;
+ _order = nil;
+ _orderInv = nil;
+ _seekPos = kCMTimeInvalid;
+ _timeObserver = 0;
+ _updatePosition = 0;
+ _updateTime = 0;
+ _lastPosition = 0;
+ _bufferedPosition = 0;
+ _bufferUnconfirmed = NO;
+ _playing = NO;
+ _loadResult = nil;
+ _playResult = nil;
+ _automaticallyWaitsToMinimizeStalling = YES;
+ _allowsExternalPlayback = NO;
+ _loadControl = nil;
+ if (loadConfiguration != (id)[NSNull null]) {
+ NSDictionary *map = loadConfiguration[@"darwinLoadControl"];
+ if (map != (id)[NSNull null]) {
+ _loadControl = [[LoadControl alloc] init];
+ _loadControl.preferredForwardBufferDuration = (NSNumber *)map[@"preferredForwardBufferDuration"];
+ _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused = (BOOL)[map[@"canUseNetworkResourcesForLiveStreamingWhilePaused"] boolValue];
+ _loadControl.preferredPeakBitRate = (NSNumber *)map[@"preferredPeakBitRate"];
+ _automaticallyWaitsToMinimizeStalling = (BOOL)[map[@"automaticallyWaitsToMinimizeStalling"] boolValue];
+ }
+ }
+ if (!_loadControl) {
+ _loadControl = [[LoadControl alloc] init];
+ _loadControl.preferredForwardBufferDuration = (NSNumber *)[NSNull null];
+ _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused = NO;
+ _loadControl.preferredPeakBitRate = (NSNumber *)[NSNull null];
+ }
+ _speed = 1.0f;
+ _volume = 1.0f;
+ _justAdvanced = NO;
+ _enqueuedAll = NO;
+ _icyMetadata = @{};
+ __weak __typeof__(self) weakSelf = self;
+ [_methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
+ [weakSelf handleMethodCall:call result:result];
+ }];
+ return self;
+}
+
+- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
+ @try {
+ NSDictionary *request = (NSDictionary *)call.arguments;
+ if ([@"load" isEqualToString:call.method]) {
+ CMTime initialPosition = request[@"initialPosition"] == (id)[NSNull null] ? kCMTimeInvalid : CMTimeMake([request[@"initialPosition"] longLongValue], 1000000);
+ [self load:request[@"audioSource"] initialPosition:initialPosition initialIndex:request[@"initialIndex"] result:result];
+ } else if ([@"play" isEqualToString:call.method]) {
+ [self play:result];
+ } else if ([@"pause" isEqualToString:call.method]) {
+ [self pause];
+ result(@{});
+ } else if ([@"setVolume" isEqualToString:call.method]) {
+ [self setVolume:(float)[request[@"volume"] doubleValue]];
+ result(@{});
+ } else if ([@"setSkipSilence" isEqualToString:call.method]) {
+ /// TODO on iOS side; Seems more involved, so someone with ObjectiveC experience might look at it.
+ result(@{});
+ } else if ([@"setSpeed" isEqualToString:call.method]) {
+ [self setSpeed:(float)[request[@"speed"] doubleValue]];
+ result(@{});
+ } else if ([@"setLoopMode" isEqualToString:call.method]) {
+ [self setLoopMode:[request[@"loopMode"] intValue]];
+ result(@{});
+ } else if ([@"setShuffleMode" isEqualToString:call.method]) {
+ [self setShuffleModeEnabled:(BOOL)([request[@"shuffleMode"] intValue] == 1)];
+ result(@{});
+ } else if ([@"setShuffleOrder" isEqualToString:call.method]) {
+ [self setShuffleOrder:(NSDictionary *)request[@"audioSource"]];
+ result(@{});
+ } else if ([@"setAutomaticallyWaitsToMinimizeStalling" isEqualToString:call.method]) {
+ [self setAutomaticallyWaitsToMinimizeStalling:(BOOL)[request[@"enabled"] boolValue]];
+ result(@{});
+ } else if ([@"setCanUseNetworkResourcesForLiveStreamingWhilePaused" isEqualToString:call.method]) {
+ [self setCanUseNetworkResourcesForLiveStreamingWhilePaused:(BOOL)[request[@"enabled"] boolValue]];
+ result(@{});
+ } else if ([@"setPreferredPeakBitRate" isEqualToString:call.method]) {
+ [self setPreferredPeakBitRate:(NSNumber *)request[@"bitRate"]];
+ result(@{});
+ } else if ([@"setAllowsExternalPlayback" isEqualToString:call.method]) {
+ [self setAllowsExternalPlayback:(BOOL)([request[@"allowsExternalPlayback"] intValue] == 1)];
+ result(@{});
+ } else if ([@"seek" isEqualToString:call.method]) {
+ CMTime position = request[@"position"] == (id)[NSNull null] ? kCMTimePositiveInfinity : CMTimeMake([request[@"position"] longLongValue], 1000000);
+ [self seek:position index:request[@"index"] completionHandler:^(BOOL finished) {
+ result(@{});
+ }];
+ } else if ([@"concatenatingInsertAll" isEqualToString:call.method]) {
+ [self concatenatingInsertAll:(NSString *)request[@"id"] index:[request[@"index"] intValue] sources:(NSArray *)request[@"children"] shuffleOrder:(NSArray<NSNumber *> *)request[@"shuffleOrder"]];
+ result(@{});
+ } else if ([@"concatenatingRemoveRange" isEqualToString:call.method]) {
+ [self concatenatingRemoveRange:(NSString *)request[@"id"] start:[request[@"startIndex"] intValue] end:[request[@"endIndex"] intValue] shuffleOrder:(NSArray<NSNumber *> *)request[@"shuffleOrder"]];
+ result(@{});
+ } else if ([@"concatenatingMove" isEqualToString:call.method]) {
+ [self concatenatingMove:(NSString *)request[@"id"] currentIndex:[request[@"currentIndex"] intValue] newIndex:[request[@"newIndex"] intValue] shuffleOrder:(NSArray<NSNumber *> *)request[@"shuffleOrder"]];
+ result(@{});
+ } else if ([@"setAndroidAudioAttributes" isEqualToString:call.method]) {
+ result(@{});
+ } else {
+ result(FlutterMethodNotImplemented);
+ }
+ } @catch (NSException *exception) {
+ //NSLog(@"%@", [exception callStackSymbols]);
+ FlutterError *flutterError = [FlutterError errorWithCode:@"error" message:@"Error in handleMethodCall" details:nil];
+ result(flutterError);
+ }
+}
+
+- (AVQueuePlayer *)player {
+ return _player;
+}
+
+- (float)speed {
+ return _speed;
+}
+
+// Untested
+- (void)concatenatingInsertAll:(NSString *)catId index:(int)index sources:(NSArray *)sources shuffleOrder:(NSArray<NSNumber *> *)shuffleOrder {
+ // Find all duplicates of the identified ConcatenatingAudioSource.
+ NSMutableArray *matches = [[NSMutableArray alloc] init];
+ [_audioSource findById:catId matches:matches];
+ // Add each new source to each match.
+ for (int i = 0; i < matches.count; i++) {
+ ConcatenatingAudioSource *catSource = (ConcatenatingAudioSource *)matches[i];
+ int idx = index >= 0 ? index : catSource.count;
+ NSMutableArray<AudioSource *> *audioSources = [self decodeAudioSources:sources];
+ for (int j = 0; j < audioSources.count; j++) {
+ AudioSource *audioSource = audioSources[j];
+ [catSource insertSource:audioSource atIndex:(idx + j)];
+ }
+ [catSource setShuffleOrder:shuffleOrder];
+ }
+ // Index the new audio sources.
+ _indexedAudioSources = [[NSMutableArray alloc] init];
+ [_audioSource buildSequence:_indexedAudioSources treeIndex:0];
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ IndexedAudioSource *audioSource = _indexedAudioSources[i];
+ if (!audioSource.isAttached) {
+ audioSource.playerItem.audioSource = audioSource;
+ [self addItemObservers:audioSource.playerItem];
+ }
+ }
+ [self updateOrder];
+ if (_player.currentItem) {
+ _index = [self indexForItem:(IndexedPlayerItem *)_player.currentItem];
+ } else {
+ _index = 0;
+ }
+ [self enqueueFrom:_index];
+ // Notify each new IndexedAudioSource that it's been attached to the player.
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ if (!_indexedAudioSources[i].isAttached) {
+ [_indexedAudioSources[i] attach:_player initialPos:kCMTimeInvalid];
+ }
+ }
+ [self broadcastPlaybackEvent];
+}
+
+// Untested
+- (void)concatenatingRemoveRange:(NSString *)catId start:(int)start end:(int)end shuffleOrder:(NSArray<NSNumber *> *)shuffleOrder {
+ // Find all duplicates of the identified ConcatenatingAudioSource.
+ NSMutableArray *matches = [[NSMutableArray alloc] init];
+ [_audioSource findById:catId matches:matches];
+ // Remove range from each match.
+ for (int i = 0; i < matches.count; i++) {
+ ConcatenatingAudioSource *catSource = (ConcatenatingAudioSource *)matches[i];
+ int endIndex = end >= 0 ? end : catSource.count;
+ [catSource removeSourcesFromIndex:start toIndex:endIndex];
+ [catSource setShuffleOrder:shuffleOrder];
+ }
+ // Re-index the remaining audio sources.
+ NSArray<IndexedAudioSource *> *oldIndexedAudioSources = _indexedAudioSources;
+ _indexedAudioSources = [[NSMutableArray alloc] init];
+ [_audioSource buildSequence:_indexedAudioSources treeIndex:0];
+ for (int i = 0, j = 0; i < _indexedAudioSources.count; i++, j++) {
+ IndexedAudioSource *audioSource = _indexedAudioSources[i];
+ while (audioSource != oldIndexedAudioSources[j]) {
+ [self removeItemObservers:oldIndexedAudioSources[j].playerItem];
+ if (oldIndexedAudioSources[j].playerItem2) {
+ [self removeItemObservers:oldIndexedAudioSources[j].playerItem2];
+ }
+ if (j < _index) {
+ _index--;
+ } else if (j == _index) {
+ // The currently playing item was removed.
+ }
+ j++;
+ }
+ }
+ [self updateOrder];
+ if (_index >= _indexedAudioSources.count) _index = (int)_indexedAudioSources.count - 1;
+ if (_index < 0) _index = 0;
+ [self enqueueFrom:_index];
+ [self broadcastPlaybackEvent];
+}
+
+// Untested
+- (void)concatenatingMove:(NSString *)catId currentIndex:(int)currentIndex newIndex:(int)newIndex shuffleOrder:(NSArray<NSNumber *> *)shuffleOrder {
+ // Find all duplicates of the identified ConcatenatingAudioSource.
+ NSMutableArray *matches = [[NSMutableArray alloc] init];
+ [_audioSource findById:catId matches:matches];
+ // Move range within each match.
+ for (int i = 0; i < matches.count; i++) {
+ ConcatenatingAudioSource *catSource = (ConcatenatingAudioSource *)matches[i];
+ [catSource moveSourceFromIndex:currentIndex toIndex:newIndex];
+ [catSource setShuffleOrder:shuffleOrder];
+ }
+ // Re-index the audio sources.
+ _indexedAudioSources = [[NSMutableArray alloc] init];
+ [_audioSource buildSequence:_indexedAudioSources treeIndex:0];
+ [self updateOrder];
+ [self enqueueFrom:[self indexForItem:(IndexedPlayerItem *)_player.currentItem]];
+ [self broadcastPlaybackEvent];
+}
+
+- (void)checkForDiscontinuity {
+ if (!_playing || CMTIME_IS_VALID(_seekPos) || _processingState == completed) return;
+ int position = [self getCurrentPosition];
+ if (_processingState == buffering) {
+ if (position > _lastPosition) {
+ [self leaveBuffering:@"stall ended"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ }
+ } else {
+ long long now = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
+ long long timeSinceLastUpdate = now - _updateTime;
+ long long expectedPosition = _updatePosition + (long long)(timeSinceLastUpdate * _player.rate);
+ long long drift = position - expectedPosition;
+ //NSLog(@"position: %d, drift: %lld", position, drift);
+ // Update if we've drifted or just started observing
+ if (_updateTime == 0L) {
+ [self broadcastPlaybackEvent];
+ } else if (drift < -100) {
+ [self enterBuffering:@"stalling"];
+ //NSLog(@"Drift: %lld", drift);
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ }
+ }
+ _lastPosition = position;
+}
+
+- (void)enterBuffering:(NSString *)reason {
+ //NSLog(@"ENTER BUFFERING: %@", reason);
+ _processingState = buffering;
+}
+
+- (void)leaveBuffering:(NSString *)reason {
+ //NSLog(@"LEAVE BUFFERING: %@", reason);
+ _processingState = ready;
+}
+
+- (void)broadcastPlaybackEvent {
+ [_eventChannel sendEvent:@{
+ @"processingState": @(_processingState),
+ @"updatePosition": @((long long)1000 * _updatePosition),
+ @"updateTime": @(_updateTime),
+ @"bufferedPosition": @((long long)1000 * [self getBufferedPosition]),
+ @"icyMetadata": _icyMetadata,
+ @"duration": @([self getDurationMicroseconds]),
+ @"currentIndex": @(_index),
+ }];
+}
+
+- (int)getCurrentPosition {
+ // XXX: During load, the second case will be selected returning 0.
+ // TODO: Provide a similar case as _seekPos for _initialPos.
+ if (CMTIME_IS_VALID(_seekPos)) {
+ return (int)(1000 * CMTimeGetSeconds(_seekPos));
+ } else if (_indexedAudioSources && _indexedAudioSources.count > 0) {
+ int ms = (int)(1000 * CMTimeGetSeconds(_indexedAudioSources[_index].position));
+ if (ms < 0) ms = 0;
+ return ms;
+ } else {
+ return 0;
+ }
+}
+
+- (int)getBufferedPosition {
+ if (_processingState == none || _processingState == loading) {
+ return 0;
+ } else if (_indexedAudioSources && _indexedAudioSources.count > 0) {
+ int ms = (int)(1000 * CMTimeGetSeconds(_indexedAudioSources[_index].bufferedPosition));
+ if (ms < 0) ms = 0;
+ return ms;
+ } else {
+ return 0;
+ }
+}
+
+- (int)getDuration {
+ if (_processingState == none || _processingState == loading) {
+ return -1;
+ } else if (_indexedAudioSources && _indexedAudioSources.count > 0) {
+ int v = (int)(1000 * CMTimeGetSeconds(_indexedAudioSources[_index].duration));
+ return v;
+ } else {
+ return 0;
+ }
+}
+
+- (long long)getDurationMicroseconds {
+ int duration = [self getDuration];
+ return duration < 0 ? -1 : ((long long)1000 * duration);
+}
+
+- (void)removeItemObservers:(AVPlayerItem *)playerItem {
+ [playerItem removeObserver:self forKeyPath:@"status"];
+ [playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
+ [playerItem removeObserver:self forKeyPath:@"playbackBufferFull"];
+ [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
+ //[playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
+ [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
+ [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemFailedToPlayToEndTimeNotification object:playerItem];
+ [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemPlaybackStalledNotification object:playerItem];
+}
+
+- (void)addItemObservers:(AVPlayerItem *)playerItem {
+ // Get notified when the item is loaded or had an error loading
+ [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
+ // Get notified of the buffer state
+ [playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
+ [playerItem addObserver:self forKeyPath:@"playbackBufferFull" options:NSKeyValueObservingOptionNew context:nil];
+ [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
+ //[playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
+ // Get notified when playback has reached the end
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onComplete:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
+ // Get notified when playback stops due to a failure (currently unused)
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailToComplete:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:playerItem];
+ // Get notified when playback stalls (currently unused)
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onItemStalled:) name:AVPlayerItemPlaybackStalledNotification object:playerItem];
+
+ AVPlayerItemMetadataOutput *metadataOutput = [[AVPlayerItemMetadataOutput alloc] initWithIdentifiers:nil];
+ [metadataOutput setDelegate:self queue:dispatch_get_main_queue()];
+ // Since the delegate is stored as a weak reference,
+ // there shouldn't be a retain cycle.
+ // TODO: Check this. Shouldn't need to removeOutput
+ // later?
+ [playerItem addOutput:metadataOutput];
+}
+
+- (void)metadataOutput:(AVPlayerItemMetadataOutput *)output didOutputTimedMetadataGroups:(NSArray<AVTimedMetadataGroup *> *)groups fromPlayerItemTrack:(AVPlayerItemTrack *)track {
+ // ICY headers aren't available here. Maybe do this in the proxy.
+ BOOL hasIcyData = NO;
+ NSString *title = (NSString *)[NSNull null];
+ NSString *url = (NSString *)[NSNull null];
+ for (int i = 0; i < groups.count; i++) {
+ AVTimedMetadataGroup *group = groups[i];
+ for (int j = 0; j < group.items.count; j++) {
+ AVMetadataItem *item = group.items[j];
+ if ([@"icy/StreamTitle" isEqualToString:item.identifier]) {
+ hasIcyData = YES;
+ title = (NSString *)item.value;
+ } else if ([@"icy/StreamUrl" isEqualToString:item.identifier]) {
+ hasIcyData = YES;
+ url = (NSString *)item.value;
+ }
+ }
+ }
+ if (hasIcyData) {
+ _icyMetadata = @{
+ @"info": @{
+ @"title": title,
+ @"url": url,
+ },
+ };
+ [self broadcastPlaybackEvent];
+ }
+}
+
+- (NSMutableArray<AudioSource *> *)decodeAudioSources:(NSArray *)data {
+ NSMutableArray<AudioSource *> *array = (NSMutableArray<AudioSource *> *)[[NSMutableArray alloc] init];
+ for (int i = 0; i < [data count]; i++) {
+ AudioSource *source = [self decodeAudioSource:data[i]];
+ [array addObject:source];
+ }
+ return array;
+}
+
+- (AudioSource *)decodeAudioSource:(NSDictionary *)data {
+ NSString *type = data[@"type"];
+ if ([@"progressive" isEqualToString:type]) {
+ return [[UriAudioSource alloc] initWithId:data[@"id"] uri:data[@"uri"] loadControl:_loadControl headers:data[@"headers"] options:data[@"options"]];
+ } else if ([@"dash" isEqualToString:type]) {
+ return [[UriAudioSource alloc] initWithId:data[@"id"] uri:data[@"uri"] loadControl:_loadControl headers:data[@"headers"] options:data[@"options"]];
+ } else if ([@"hls" isEqualToString:type]) {
+ return [[UriAudioSource alloc] initWithId:data[@"id"] uri:data[@"uri"] loadControl:_loadControl headers:data[@"headers"] options:data[@"options"]];
+ } else if ([@"concatenating" isEqualToString:type]) {
+ return [[ConcatenatingAudioSource alloc] initWithId:data[@"id"]
+ audioSources:[self decodeAudioSources:data[@"children"]]
+ shuffleOrder:(NSArray<NSNumber *> *)data[@"shuffleOrder"]
+ lazyLoading:(NSNumber *)data[@"useLazyPreparation"]];
+ } else if ([@"clipping" isEqualToString:type]) {
+ return [[ClippingAudioSource alloc] initWithId:data[@"id"]
+ audioSource:(UriAudioSource *)[self decodeAudioSource:data[@"child"]]
+ start:data[@"start"]
+ end:data[@"end"]];
+ } else if ([@"looping" isEqualToString:type]) {
+ NSMutableArray *childSources = [NSMutableArray new];
+ int count = [data[@"count"] intValue];
+ for (int i = 0; i < count; i++) {
+ [childSources addObject:[self decodeAudioSource:data[@"child"]]];
+ }
+ return [[LoopingAudioSource alloc] initWithId:data[@"id"] audioSources:childSources];
+ } else {
+ return nil;
+ }
+}
+
+- (void)enqueueFrom:(int)index {
+ //NSLog(@"### enqueueFrom:%d", index);
+ _index = index;
+
+ // Update the queue while keeping the currently playing item untouched.
+
+ /* NSLog(@"before reorder: _player.items.count: ", _player.items.count); */
+ /* [self dumpQueue]; */
+
+ // First, remove all _player items except for the currently playing one (if any).
+ IndexedPlayerItem *oldItem = (IndexedPlayerItem *)_player.currentItem;
+ IndexedPlayerItem *existingItem = nil;
+ IndexedPlayerItem *newItem = _indexedAudioSources.count > 0 ? _indexedAudioSources[_index].playerItem : nil;
+ NSArray *oldPlayerItems = [NSArray arrayWithArray:_player.items];
+ // In the first pass, preserve the old and new items.
+ for (int i = 0; i < oldPlayerItems.count; i++) {
+ if (oldPlayerItems[i] == newItem) {
+ // Preserve and tag new item if it is already in the queue.
+ existingItem = oldPlayerItems[i];
+ //NSLog(@"Preserving existing item %d", [self indexForItem:existingItem]);
+ } else if (oldPlayerItems[i] == oldItem) {
+ //NSLog(@"Preserving old item %d", [self indexForItem:oldItem]);
+ // Temporarily preserve old item, just to avoid jumping to
+ // intermediate queue positions unnecessarily. We only want to jump
+ // once to _index.
+ } else {
+ //NSLog(@"Removing item %d", [self indexForItem:oldPlayerItems[i]]);
+ [_player removeItem:oldPlayerItems[i]];
+ }
+ }
+ // In the second pass, remove the old item (if different from new item).
+ if (oldItem && newItem != oldItem) {
+ //NSLog(@"removing old item %d", [self indexForItem:oldItem]);
+ [_player removeItem:oldItem];
+ }
+
+ /* NSLog(@"inter order: _player.items.count: ", _player.items.count); */
+ /* [self dumpQueue]; */
+
+ // Regenerate queue
+ _enqueuedAll = NO;
+ if (!existingItem || _loopMode != loopOne) {
+ _enqueuedAll = YES;
+ BOOL include = NO;
+ for (int i = 0; i < [_order count]; i++) {
+ int si = [_order[i] intValue];
+ if (si == _index) include = YES;
+ if (include && _indexedAudioSources[si].playerItem != existingItem) {
+ if (_indexedAudioSources[si].lazyLoading && _player.items.count >= TREADMILL_SIZE) {
+ // Enqueue up until the first lazy item that does not fit on the treadmill.
+ _enqueuedAll = NO;
+ break;
+ }
+ //NSLog(@"inserting item %d", si);
+ [_player insertItem:_indexedAudioSources[si].playerItem afterItem:nil];
+ if (_loopMode == loopOne) {
+ // We only want one item in the queue.
+ break;
+ }
+ }
+ }
+ }
+
+ // Add next loop item if we're looping
+ if (_order.count > 0) {
+ if (_loopMode == loopAll && _enqueuedAll) {
+ int si = [_order[0] intValue];
+ //NSLog(@"### add loop item:%d", si);
+ if (!_indexedAudioSources[si].playerItem2) {
+ [_indexedAudioSources[si] preparePlayerItem2];
+ [self addItemObservers:_indexedAudioSources[si].playerItem2];
+ }
+ [_player insertItem:_indexedAudioSources[si].playerItem2 afterItem:nil];
+ } else if (_loopMode == loopOne) {
+ //NSLog(@"### add loop item:%d", _index);
+ if (!_indexedAudioSources[_index].playerItem2) {
+ [_indexedAudioSources[_index] preparePlayerItem2];
+ [self addItemObservers:_indexedAudioSources[_index].playerItem2];
+ }
+ [_player insertItem:_indexedAudioSources[_index].playerItem2 afterItem:nil];
+ }
+ }
+
+ /* NSLog(@"after reorder: _player.items.count: ", _player.items.count); */
+ /* [self dumpQueue]; */
+
+ if (_processingState != loading && oldItem != newItem) {
+ // || !_player.currentItem.playbackLikelyToKeepUp;
+ if (_player.currentItem.playbackBufferEmpty) {
+ [self enterBuffering:@"enqueueFrom playbackBufferEmpty"];
+ } else {
+ [self leaveBuffering:@"enqueueFrom !playbackBufferEmpty"];
+ }
+ [self updatePosition];
+ }
+
+ [self updateEndAction];
+}
+
+- (void)updatePosition {
+ _updatePosition = [self getCurrentPosition];
+ _updateTime = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
+}
+
+- (void)load:(NSDictionary *)source initialPosition:(CMTime)initialPosition initialIndex:(NSNumber *)initialIndex result:(FlutterResult)result {
+ if (_playing) {
+ [_player pause];
+ }
+ if (_processingState == loading) {
+ [self abortExistingConnection];
+ }
+ _loadResult = result;
+ _processingState = loading;
+ _index = (initialIndex != (id)[NSNull null]) ? [initialIndex intValue] : 0;
+ // Remove previous observers
+ if (_indexedAudioSources) {
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [self removeItemObservers:_indexedAudioSources[i].playerItem];
+ if (_indexedAudioSources[i].playerItem2) {
+ [self removeItemObservers:_indexedAudioSources[i].playerItem2];
+ }
+ }
+ }
+ // Decode audio source
+ if (_audioSource && [@"clipping" isEqualToString:source[@"type"]]) {
+ // Check if we're clipping an audio source that was previously loaded.
+ UriAudioSource *child = nil;
+ if ([_audioSource isKindOfClass:[ClippingAudioSource class]]) {
+ ClippingAudioSource *clipper = (ClippingAudioSource *)_audioSource;
+ child = clipper.audioSource;
+ } else if ([_audioSource isKindOfClass:[UriAudioSource class]]) {
+ child = (UriAudioSource *)_audioSource;
+ }
+ NSString *type = source[@"child"][@"type"];
+ NSString *uri = nil;
+ if ([@"progressive" isEqualToString:type] || [@"dash" isEqualToString:type] || [@"hls" isEqualToString:type]) {
+ uri = source[@"child"][@"uri"];
+ }
+ if (child && uri && [child.uri isEqualToString:uri]) {
+ ClippingAudioSource *clipper =
+ [[ClippingAudioSource alloc] initWithId:source[@"id"]
+ audioSource:child
+ start:source[@"start"]
+ end:source[@"end"]];
+ clipper.playerItem.audioSource = clipper;
+ if (clipper.playerItem2) {
+ clipper.playerItem2.audioSource = clipper;
+ }
+ _audioSource = clipper;
+ } else {
+ _audioSource = [self decodeAudioSource:source];
+ }
+ } else {
+ _audioSource = [self decodeAudioSource:source];
+ }
+ _indexedAudioSources = [[NSMutableArray alloc] init];
+ [_audioSource buildSequence:_indexedAudioSources treeIndex:0];
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ IndexedAudioSource *source = _indexedAudioSources[i];
+ [self addItemObservers:source.playerItem];
+ source.playerItem.audioSource = source;
+ }
+ [self updatePosition];
+ [self updateOrder];
+ // Set up an empty player
+ if (!_player) {
+ _player = [[AVQueuePlayer alloc] initWithItems:@[]];
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ _player.automaticallyWaitsToMinimizeStalling = _automaticallyWaitsToMinimizeStalling;
+ // TODO: Remove these observers in dispose.
+ [_player addObserver:self
+ forKeyPath:@"timeControlStatus"
+ options:NSKeyValueObservingOptionNew
+ context:nil];
+ }
+ if (@available(macOS 10.11, iOS 6.0, *)) {
+ _player.allowsExternalPlayback = _allowsExternalPlayback;
+ }
+ [_player addObserver:self
+ forKeyPath:@"currentItem"
+ options:NSKeyValueObservingOptionNew
+ context:nil];
+ // TODO: learn about the different ways to define weakSelf.
+ //__weak __typeof__(self) weakSelf = self;
+ //typeof(self) __weak weakSelf = self;
+ __unsafe_unretained typeof(self) weakSelf = self;
+ if (@available(macOS 10.12, iOS 10.0, *)) {}
+ else {
+ _timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(200, 1000)
+ queue:nil
+ usingBlock:^(CMTime time) {
+ [weakSelf checkForDiscontinuity];
+ }
+ ];
+ }
+ }
+ // Initialise the AVQueuePlayer with items.
+ [self enqueueFrom:_index];
+ // Notify each IndexedAudioSource that it's been attached to the player.
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [_indexedAudioSources[i] attach:_player initialPos:(i == _index ? initialPosition : kCMTimeInvalid)];
+ }
+
+ if (_loadResult && (_indexedAudioSources.count == 0 || !_player.currentItem ||
+ _player.currentItem.status == AVPlayerItemStatusReadyToPlay)) {
+ _processingState = ready;
+ _loadResult(@{@"duration": @([self getDurationMicroseconds])});
+ _loadResult = nil;
+ } else {
+ // We send result after the playerItem is ready in observeValueForKeyPath.
+ }
+ if (_playing) {
+ _player.rate = _speed;
+ }
+ [_player setVolume:_volume];
+ [self broadcastPlaybackEvent];
+ /* NSLog(@"load:"); */
+ /* for (int i = 0; i < [_indexedAudioSources count]; i++) { */
+ /* NSLog(@"- %@", _indexedAudioSources[i].sourceId); */
+ /* } */
+}
+
+- (void)updateOrder {
+ _orderInv = [NSMutableArray arrayWithCapacity:[_indexedAudioSources count]];
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [_orderInv addObject:@(0)];
+ }
+ if (_shuffleModeEnabled) {
+ _order = [_audioSource getShuffleIndices];
+ } else {
+ NSMutableArray *order = [[NSMutableArray alloc] init];
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [order addObject:@(i)];
+ }
+ _order = order;
+ }
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ _orderInv[[_order[i] intValue]] = @(i);
+ }
+}
+
+- (void)onItemStalled:(NSNotification *)notification {
+ //IndexedPlayerItem *playerItem = (IndexedPlayerItem *)notification.object;
+ //NSLog(@"onItemStalled");
+}
+
+- (void)onFailToComplete:(NSNotification *)notification {
+ //IndexedPlayerItem *playerItem = (IndexedPlayerItem *)notification.object;
+ //NSLog(@"onFailToComplete");
+}
+
+- (void)onComplete:(NSNotification *)notification {
+ //NSLog(@"onComplete");
+
+ IndexedPlayerItem *endedPlayerItem = (IndexedPlayerItem *)notification.object;
+ IndexedAudioSource *endedSource = endedPlayerItem.audioSource;
+
+ if (_loopMode == loopOne) {
+ [endedSource seek:kCMTimeZero];
+ _justAdvanced = YES;
+ } else if (_loopMode == loopAll) {
+ [endedSource seek:kCMTimeZero];
+ _index = [_order[([_orderInv[_index] intValue] + 1) % _order.count] intValue];
+ [self broadcastPlaybackEvent];
+ _justAdvanced = YES;
+ } else if ([_orderInv[_index] intValue] + 1 < [_order count]) {
+ [endedSource seek:kCMTimeZero];
+ _index = [_order[([_orderInv[_index] intValue] + 1)] intValue];
+ [self updateEndAction];
+ [self broadcastPlaybackEvent];
+ _justAdvanced = YES;
+ } else {
+ // reached end of playlist
+ [self complete];
+ }
+}
+
+- (void)observeValueForKeyPath:(NSString *)keyPath
+ ofObject:(id)object
+ change:(NSDictionary<NSString *,id> *)change
+ context:(void *)context {
+
+ if ([keyPath isEqualToString:@"status"]) {
+ IndexedPlayerItem *playerItem = (IndexedPlayerItem *)object;
+ AVPlayerItemStatus status = AVPlayerItemStatusUnknown;
+ NSNumber *statusNumber = change[NSKeyValueChangeNewKey];
+ if ([statusNumber isKindOfClass:[NSNumber class]]) {
+ status = statusNumber.intValue;
+ }
+ [playerItem.audioSource onStatusChanged:status];
+ switch (status) {
+ case AVPlayerItemStatusReadyToPlay: {
+ if (playerItem != _player.currentItem) return;
+ // Detect buffering in different ways depending on whether we're playing
+ if (_playing) {
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ if (_player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) {
+ [self enterBuffering:@"ready to play: playing, waitingToPlay"];
+ } else {
+ [self leaveBuffering:@"ready to play: playing, !waitingToPlay"];
+ }
+ [self updatePosition];
+ } else {
+ // If this happens when we're playing, check whether buffer is confirmed
+ if (_bufferUnconfirmed && !_player.currentItem.playbackBufferFull) {
+ // Stay in bufering - XXX Test
+ [self enterBuffering:@"ready to play: playing, bufferUnconfirmed && !playbackBufferFull"];
+ } else {
+ if (_player.currentItem.playbackBufferEmpty) {
+ // !_player.currentItem.playbackLikelyToKeepUp;
+ [self enterBuffering:@"ready to play: playing, playbackBufferEmpty"];
+ } else {
+ [self leaveBuffering:@"ready to play: playing, !playbackBufferEmpty"];
+ }
+ [self updatePosition];
+ }
+ }
+ } else {
+ if (_player.currentItem.playbackBufferEmpty) {
+ [self enterBuffering:@"ready to play: !playing, playbackBufferEmpty"];
+ // || !_player.currentItem.playbackLikelyToKeepUp;
+ } else {
+ [self leaveBuffering:@"ready to play: !playing, !playbackBufferEmpty"];
+ }
+ [self updatePosition];
+ }
+ [self broadcastPlaybackEvent];
+ if (_loadResult) {
+ _loadResult(@{@"duration": @([self getDurationMicroseconds])});
+ _loadResult = nil;
+ }
+ break;
+ }
+ case AVPlayerItemStatusFailed: {
+ //NSLog(@"AVPlayerItemStatusFailed");
+ [self sendErrorForItem:playerItem];
+ break;
+ }
+ case AVPlayerItemStatusUnknown:
+ break;
+ }
+ } else if ([keyPath isEqualToString:@"playbackBufferEmpty"] || [keyPath isEqualToString:@"playbackBufferFull"]) {
+ // Use these values to detect buffering.
+ IndexedPlayerItem *playerItem = (IndexedPlayerItem *)object;
+ if (playerItem != _player.currentItem) return;
+ // If there's a seek in progress, these values are unreliable
+ if (CMTIME_IS_VALID(_seekPos)) return;
+ // Detect buffering in different ways depending on whether we're playing
+ if (_playing) {
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ // We handle this with timeControlStatus instead.
+ } else {
+ if (_bufferUnconfirmed && playerItem.playbackBufferFull) {
+ _bufferUnconfirmed = NO;
+ [self leaveBuffering:@"playing, _bufferUnconfirmed && playbackBufferFull"];
+ [self updatePosition];
+ //NSLog(@"Buffering confirmed! leaving buffering");
+ [self broadcastPlaybackEvent];
+ }
+ }
+ } else {
+ if (playerItem.playbackBufferEmpty) {
+ [self enterBuffering:@"!playing, playbackBufferEmpty"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ } else if (!playerItem.playbackBufferEmpty || playerItem.playbackBufferFull) {
+ _processingState = ready;
+ [self leaveBuffering:@"!playing, !playbackBufferEmpty || playbackBufferFull"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ }
+ }
+ /* } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) { */
+ } else if ([keyPath isEqualToString:@"timeControlStatus"]) {
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ AVPlayerTimeControlStatus status = AVPlayerTimeControlStatusPaused;
+ NSNumber *statusNumber = change[NSKeyValueChangeNewKey];
+ if ([statusNumber isKindOfClass:[NSNumber class]]) {
+ status = statusNumber.intValue;
+ }
+ switch (status) {
+ case AVPlayerTimeControlStatusPaused:
+ //NSLog(@"AVPlayerTimeControlStatusPaused");
+ break;
+ case AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate:
+ //NSLog(@"AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate");
+ if (_processingState != completed) {
+ [self enterBuffering:@"timeControlStatus"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ } else {
+ //NSLog(@"Ignoring wait signal because we reached the end");
+ }
+ break;
+ case AVPlayerTimeControlStatusPlaying:
+ [self leaveBuffering:@"timeControlStatus"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ break;
+ }
+ }
+ } else if ([keyPath isEqualToString:@"currentItem"] && _player.currentItem) {
+ IndexedPlayerItem *playerItem = (IndexedPlayerItem *)change[NSKeyValueChangeNewKey];
+ //IndexedPlayerItem *oldPlayerItem = (IndexedPlayerItem *)change[NSKeyValueChangeOldKey];
+ if (playerItem.status == AVPlayerItemStatusFailed) {
+ if ([_orderInv[_index] intValue] + 1 < [_order count]) {
+ // account for automatic move to next item
+ _index = [_order[[_orderInv[_index] intValue] + 1] intValue];
+ //NSLog(@"advance to next on error: index = %d", _index);
+ [self updateEndAction];
+ [self broadcastPlaybackEvent];
+ } else {
+ //NSLog(@"error on last item");
+ }
+ return;
+ } else {
+ int expectedIndex = [self indexForItem:playerItem];
+ if (_index != expectedIndex) {
+ // AVQueuePlayer will sometimes skip over error items without
+ // notifying this observer.
+ //NSLog(@"Queue change detected. Adjusting index from %d -> %d", _index, expectedIndex);
+ _index = expectedIndex;
+ [self updateEndAction];
+ [self broadcastPlaybackEvent];
+ }
+ }
+ //NSLog(@"currentItem changed. _index=%d", _index);
+ _bufferUnconfirmed = YES;
+ // If we've skipped or transitioned to a new item and we're not
+ // currently in the middle of a seek
+ /* if (CMTIME_IS_INVALID(_seekPos) && playerItem.status == AVPlayerItemStatusReadyToPlay) { */
+ /* [self updatePosition]; */
+ /* IndexedAudioSource *source = playerItem.audioSource; */
+ /* // We should already be at position zero but for */
+ /* // ClippingAudioSource it might be off by some milliseconds so we */
+ /* // consider anything <= 100 as close enough. */
+ /* if ((int)(1000 * CMTimeGetSeconds(source.position)) > 100) { */
+ /* NSLog(@"On currentItem change, seeking back to zero"); */
+ /* BOOL shouldResumePlayback = NO; */
+ /* AVPlayerActionAtItemEnd originalEndAction = _player.actionAtItemEnd; */
+ /* if (_playing && CMTimeGetSeconds(CMTimeSubtract(source.position, source.duration)) >= 0) { */
+ /* NSLog(@"Need to pause while rewinding because we're at the end"); */
+ /* shouldResumePlayback = YES; */
+ /* _player.actionAtItemEnd = AVPlayerActionAtItemEndPause; */
+ /* [_player pause]; */
+ /* } */
+ /* [self enterBuffering:@"currentItem changed, seeking"]; */
+ /* [self updatePosition]; */
+ /* [self broadcastPlaybackEvent]; */
+ /* __weak __typeof__(self) weakSelf = self; */
+ /* [source seek:kCMTimeZero completionHandler:^(BOOL finished) { */
+ /* [weakSelf leaveBuffering:@"currentItem changed, finished seek"]; */
+ /* [weakSelf updatePosition]; */
+ /* [weakSelf broadcastPlaybackEvent]; */
+ /* if (shouldResumePlayback) { */
+ /* weakSelf.player.actionAtItemEnd = originalEndAction; */
+ /* // TODO: This logic is almost duplicated in seek. See if we can reuse this code. */
+ /* weakSelf.player.rate = weakSelf.speed; */
+ /* } */
+ /* }]; */
+ /* } else { */
+ /* // Already at zero, no need to seek. */
+ /* } */
+ /* } */
+
+ if (_justAdvanced) {
+ IndexedAudioSource *audioSource = playerItem.audioSource;
+ if (_loopMode == loopOne) {
+ [audioSource flip];
+ [self enqueueFrom:_index];
+ } else if (_loopMode == loopAll) {
+ if (_index == [_order[0] intValue] && playerItem == audioSource.playerItem2) {
+ [audioSource flip];
+ [self enqueueFrom:_index];
+ } else if (!_enqueuedAll) {
+ [self enqueueFrom:_index];
+ } else {
+ [self updateEndAction];
+ }
+ } else if (!_enqueuedAll) {
+ [self enqueueFrom:_index];
+ }
+ _justAdvanced = NO;
+ }
+ } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
+ IndexedPlayerItem *playerItem = (IndexedPlayerItem *)object;
+ if (playerItem != _player.currentItem) return;
+ int pos = [self getBufferedPosition];
+ if (pos != _bufferedPosition) {
+ _bufferedPosition = pos;
+ [self broadcastPlaybackEvent];
+ }
+ }
+}
+
+- (void)sendErrorForItem:(IndexedPlayerItem *)playerItem {
+ FlutterError *flutterError = [FlutterError errorWithCode:[NSString stringWithFormat:@"%d", (int)playerItem.error.code]
+ message:playerItem.error.localizedDescription
+ details:@{@"index": @([self indexForItem:playerItem])}];
+ [self sendError:flutterError playerItem:playerItem];
+}
+
+- (void)sendError:(FlutterError *)flutterError playerItem:(IndexedPlayerItem *)playerItem {
+ //NSLog(@"sendError");
+ if (_loadResult && playerItem == _player.currentItem) {
+ _loadResult(flutterError);
+ _loadResult = nil;
+ }
+ // Broadcast all errors even if they aren't on the current item.
+ [_eventChannel sendEvent:flutterError];
+}
+
+- (void)abortExistingConnection {
+ FlutterError *flutterError = [FlutterError errorWithCode:@"abort"
+ message:@"Connection aborted"
+ details:nil];
+ [self sendError:flutterError playerItem:nil];
+}
+
+- (int)indexForItem:(IndexedPlayerItem *)playerItem {
+ for (int i = 0; i < _indexedAudioSources.count; i++) {
+ if (_indexedAudioSources[i].playerItem == playerItem || _indexedAudioSources[i].playerItem2 == playerItem) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+- (void)play {
+ [self play:nil];
+}
+
+- (void)play:(FlutterResult)result {
+ if (_playing) {
+ if (result) {
+ result(@{});
+ }
+ return;
+ }
+ if (result) {
+ if (_playResult) {
+ //NSLog(@"INTERRUPTING PLAY");
+ _playResult(@{});
+ }
+ _playResult = result;
+ }
+ _playing = YES;
+ _player.rate = _speed;
+ [self updatePosition];
+ if (@available(macOS 10.12, iOS 10.0, *)) {}
+ else {
+ if (_bufferUnconfirmed && !_player.currentItem.playbackBufferFull) {
+ [self enterBuffering:@"play, _bufferUnconfirmed && !playbackBufferFull"];
+ [self broadcastPlaybackEvent];
+ }
+ }
+}
+
+- (void)pause {
+ if (!_playing) return;
+ _playing = NO;
+ [_player pause];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ if (_playResult) {
+ //NSLog(@"PLAY FINISHED DUE TO PAUSE");
+ _playResult(@{});
+ _playResult = nil;
+ }
+}
+
+- (void)complete {
+ [self updatePosition];
+ _processingState = completed;
+ [self broadcastPlaybackEvent];
+ if (_playResult) {
+ //NSLog(@"PLAY FINISHED DUE TO COMPLETE");
+ _playResult(@{});
+ _playResult = nil;
+ }
+}
+
+- (void)setVolume:(float)volume {
+ _volume = volume;
+ if (_player) {
+ [_player setVolume:volume];
+ }
+}
+
+- (void)setSpeed:(float)speed {
+ // NOTE: We ideally should check _player.currentItem.canPlaySlowForward and
+ // canPlayFastForward, but these properties are unreliable and the official
+ // documentation is unclear and contradictory.
+ //
+ // Source #1:
+ // https://developer.apple.com/documentation/avfoundation/avplayer/1388846-rate?language=objc
+ //
+ // Rates other than 0.0 and 1.0 can be used if the associated player
+ // item returns YES for the AVPlayerItem properties canPlaySlowForward
+ // or canPlayFastForward.
+ //
+ // Source #2:
+ // https://developer.apple.com/library/archive/qa/qa1772/_index.html
+ //
+ // An AVPlayerItem whose status property equals
+ // AVPlayerItemStatusReadyToPlay can be played at rates between 1.0 and
+ // 2.0, inclusive, even if AVPlayerItem.canPlayFastForward is NO.
+ // AVPlayerItem.canPlayFastForward indicates whether the item can be
+ // played at rates greater than 2.0.
+ //
+ // But in practice, it appears that even if AVPlayerItem.canPlayFastForward
+ // is NO, rates greater than 2.0 still work sometimes.
+ //
+ // So for now, we just let the app pass in any speed and hope for the best.
+ // There is no way to reliably query whether the requested speed is
+ // supported.
+ _speed = speed;
+ if (_playing && _player) {
+ _player.rate = speed;
+ }
+ [self updatePosition];
+}
+
+- (void)setLoopMode:(int)loopMode {
+ if (loopMode == _loopMode) return;
+ _loopMode = loopMode;
+ [self enqueueFrom:_index];
+}
+
+- (void)updateEndAction {
+ // Should be called in the following situations:
+ // - when the audio source changes
+ // - when _index changes
+ // - when the loop mode changes.
+ // - when the shuffle order changes. (TODO)
+ // - when the shuffle mode changes.
+ if (!_player) return;
+ if (_audioSource && (_loopMode != loopOff || ([_order count] > 0 && [_orderInv[_index] intValue] + 1 < [_order count]))) {
+ _player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;
+ } else {
+ _player.actionAtItemEnd = AVPlayerActionAtItemEndPause; // AVPlayerActionAtItemEndNone
+ }
+}
+
+- (void)setShuffleModeEnabled:(BOOL)shuffleModeEnabled {
+ //NSLog(@"setShuffleModeEnabled: %d", shuffleModeEnabled);
+ _shuffleModeEnabled = shuffleModeEnabled;
+ if (!_audioSource) return;
+
+ [self updateOrder];
+
+ [self enqueueFrom:_index];
+}
+
+- (void)setShuffleOrder:(NSDictionary *)dict {
+ if (!_audioSource) return;
+
+ [_audioSource decodeShuffleOrder:dict];
+
+ [self updateOrder];
+
+ [self enqueueFrom:_index];
+}
+
+- (void)dumpQueue {
+ for (int i = 0; i < _player.items.count; i++) {
+ IndexedPlayerItem *playerItem = (IndexedPlayerItem *)_player.items[i];
+ int j = [self indexForItem:playerItem];
+ NSLog(@"- %d", j);
+ }
+}
+
+- (void)setAutomaticallyWaitsToMinimizeStalling:(bool)automaticallyWaitsToMinimizeStalling {
+ _automaticallyWaitsToMinimizeStalling = automaticallyWaitsToMinimizeStalling;
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ if(_player) {
+ _player.automaticallyWaitsToMinimizeStalling = automaticallyWaitsToMinimizeStalling;
+ }
+ }
+}
+
+- (void)setCanUseNetworkResourcesForLiveStreamingWhilePaused:(BOOL)enabled {
+ _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused = enabled;
+ if (!_indexedAudioSources) return;
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [_indexedAudioSources[i] applyCanUseNetworkResourcesForLiveStreamingWhilePaused];
+ }
+}
+
+- (void)setPreferredPeakBitRate:(NSNumber *)preferredPeakBitRate {
+ _loadControl.preferredPeakBitRate = preferredPeakBitRate;
+ if (!_indexedAudioSources) return;
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [_indexedAudioSources[i] applyPreferredPeakBitRate];
+ }
+}
+
+- (void)setAllowsExternalPlayback:(BOOL)allowsExternalPlayback {
+ _allowsExternalPlayback = allowsExternalPlayback;
+ if (@available(macOS 10.11, iOS 6.0, *)) {
+ if (_player) {
+ _player.allowsExternalPlayback = allowsExternalPlayback;
+ }
+ }
+}
+
+- (void)seek:(CMTime)position index:(NSNumber *)newIndex completionHandler:(void (^)(BOOL))completionHandler {
+ if (_processingState == none || _processingState == loading) {
+ if (completionHandler) {
+ completionHandler(NO);
+ }
+ return;
+ }
+ int index = _index;
+ if (newIndex != (id)[NSNull null]) {
+ index = [newIndex intValue];
+ }
+ if (index != _index) {
+ // Jump to a new item
+ /* if (_playing && index == _index + 1) { */
+ /* // Special case for jumping to the very next item */
+ /* NSLog(@"seek to next item: %d -> %d", _index, index); */
+ /* [_indexedAudioSources[_index] seek:kCMTimeZero]; */
+ /* _index = index; */
+ /* [_player advanceToNextItem]; */
+ /* [self broadcastPlaybackEvent]; */
+ /* } else */
+ {
+ // Jump to a distant item
+ //NSLog(@"seek# jump to distant item: %d -> %d", _index, index);
+ if (_playing) {
+ [_player pause];
+ }
+ [_indexedAudioSources[_index] seek:kCMTimeZero];
+ // The "currentItem" key observer will respect that a seek is already in progress
+ _seekPos = position;
+ [self updatePosition];
+ [self enqueueFrom:index];
+ IndexedAudioSource *source = _indexedAudioSources[_index];
+ if (abs((int)(1000 * CMTimeGetSeconds(CMTimeSubtract(source.position, position)))) > 100) {
+ [self enterBuffering:@"seek to index"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ [source seek:position completionHandler:^(BOOL finished) {
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ if (self->_playing) {
+ // Handled by timeControlStatus
+ } else {
+ if (self->_bufferUnconfirmed && !self->_player.currentItem.playbackBufferFull) {
+ // Stay in buffering
+ } else if (source.playerItem.status == AVPlayerItemStatusReadyToPlay) {
+ [self leaveBuffering:@"seek to index finished, (!bufferUnconfirmed || playbackBufferFull) && ready to play"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ }
+ }
+ } else {
+ if (self->_bufferUnconfirmed && !self->_player.currentItem.playbackBufferFull) {
+ // Stay in buffering
+ } else if (source.playerItem.status == AVPlayerItemStatusReadyToPlay) {
+ [self leaveBuffering:@"seek to index finished, (!bufferUnconfirmed || playbackBufferFull) && ready to play"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ }
+ }
+ if (self->_playing) {
+ self->_player.rate = self->_speed;
+ }
+ self->_seekPos = kCMTimeInvalid;
+ [self broadcastPlaybackEvent];
+ if (completionHandler) {
+ completionHandler(finished);
+ }
+ }];
+ } else {
+ _seekPos = kCMTimeInvalid;
+ if (_playing) {
+ if (@available(iOS 10.0, *)) {
+ // NOTE: Re-enable this line only after figuring out
+ // how to detect buffering when buffered audio is not
+ // immediately available.
+ //[_player playImmediatelyAtRate:_speed];
+ _player.rate = _speed;
+ } else {
+ _player.rate = _speed;
+ }
+ }
+ [self broadcastPlaybackEvent];
+ completionHandler(YES);
+ }
+ }
+ } else {
+ // Seek within an item
+ if (_playing) {
+ [_player pause];
+ }
+ _seekPos = position;
+ //NSLog(@"seek. enter buffering. pos = %d", (int)(1000*CMTimeGetSeconds(_indexedAudioSources[_index].position)));
+ // TODO: Move this into a separate method so it can also
+ // be used in skip.
+ [self enterBuffering:@"seek"];
+ [self updatePosition];
+ [self broadcastPlaybackEvent];
+ [_indexedAudioSources[_index] seek:position completionHandler:^(BOOL finished) {
+ [self updatePosition];
+ if (self->_playing) {
+ // If playing, buffering will be detected either by:
+ // 1. checkForDiscontinuity
+ // 2. timeControlStatus
+ if (@available(iOS 10.0, *)) {
+ // NOTE: Re-enable this line only after figuring out how to
+ // detect buffering when buffered audio is not immediately
+ // available.
+ //[_player playImmediatelyAtRate:_speed];
+ self->_player.rate = self->_speed;
+ } else {
+ self->_player.rate = self->_speed;
+ }
+ } else {
+ // If not playing, there is no reliable way to detect
+ // when buffering has completed, so we use
+ // !playbackBufferEmpty. Although this always seems to
+ // be full even right after a seek.
+ if (self->_player.currentItem.playbackBufferEmpty) {
+ [self enterBuffering:@"seek finished, playbackBufferEmpty"];
+ } else {
+ [self leaveBuffering:@"seek finished, !playbackBufferEmpty"];
+ }
+ [self updatePosition];
+ if (self->_processingState != buffering) {
+ [self broadcastPlaybackEvent];
+ }
+ }
+ self->_seekPos = kCMTimeInvalid;
+ [self broadcastPlaybackEvent];
+ if (completionHandler) {
+ completionHandler(finished);
+ }
+ }];
+ }
+}
+
+- (void)dispose:(BOOL)calledFromDealloc {
+ if (!_player) return;
+ if (_processingState != none) {
+ [_player pause];
+
+ [self updatePosition];
+ if (!calledFromDealloc) {
+ [self broadcastPlaybackEvent];
+ }
+ if (_playResult) {
+ //NSLog(@"PLAY FINISHED DUE TO STOP");
+ _playResult(@{});
+ _playResult = nil;
+ }
+
+ _processingState = none;
+ // If used just before destroying the current FlutterEngine, this will result in:
+ // NSInternalInconsistencyException: 'Sending a message before the FlutterEngine has been run.'
+ //[self broadcastPlaybackEvent];
+ }
+ if (_timeObserver) {
+ [_player removeTimeObserver:_timeObserver];
+ _timeObserver = 0;
+ }
+ if (_indexedAudioSources) {
+ for (int i = 0; i < [_indexedAudioSources count]; i++) {
+ [self removeItemObservers:_indexedAudioSources[i].playerItem];
+ if (_indexedAudioSources[i].playerItem2) {
+ [self removeItemObservers:_indexedAudioSources[i].playerItem2];
+ }
+ }
+ _indexedAudioSources = nil;
+ }
+ _audioSource = nil;
+ if (_player) {
+ [_player removeObserver:self forKeyPath:@"currentItem"];
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ [_player removeObserver:self forKeyPath:@"timeControlStatus"];
+ }
+ _player = nil;
+ }
+ // Untested:
+ [_eventChannel dispose];
+ [_dataEventChannel dispose];
+ [_methodChannel setMethodCallHandler:nil];
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioSource.m
new file mode 100644
index 00000000..af7df2e0
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioSource.m
@@ -0,0 +1,43 @@
+#import "./include/just_audio/AudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+
+@implementation AudioSource {
+ NSString *_sourceId;
+}
+
+- (instancetype)initWithId:(NSString *)sid {
+ self = [super init];
+ NSAssert(self, @"super init cannot be nil");
+ _sourceId = sid;
+ return self;
+}
+
+- (NSString *)sourceId {
+ return _sourceId;
+}
+
+- (BOOL)lazyLoading {
+ return NO;
+}
+
+- (void)setLazyLoading:(BOOL)lazyLoading {
+}
+
+- (int)buildSequence:(NSMutableArray *)sequence treeIndex:(int)treeIndex {
+ return 0;
+}
+
+- (void)findById:(NSString *)sourceId matches:(NSMutableArray<AudioSource *> *)matches {
+ if ([_sourceId isEqualToString:sourceId]) {
+ [matches addObject:self];
+ }
+}
+
+- (NSArray<NSNumber *> *)getShuffleIndices {
+ return @[];
+}
+
+- (void)decodeShuffleOrder:(NSDictionary *)dict {
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/BetterEventChannel.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/BetterEventChannel.m
new file mode 100644
index 00000000..ad52bb2d
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/BetterEventChannel.m
@@ -0,0 +1,37 @@
+#import "./include/just_audio/BetterEventChannel.h"
+
+@implementation BetterEventChannel {
+ FlutterEventChannel *_eventChannel;
+ FlutterEventSink _eventSink;
+}
+
+- (instancetype)initWithName:(NSString*)name messenger:(NSObject<FlutterBinaryMessenger> *)messenger {
+ self = [super init];
+ NSAssert(self, @"super init cannot be nil");
+ _eventChannel =
+ [FlutterEventChannel eventChannelWithName:name binaryMessenger:messenger];
+ [_eventChannel setStreamHandler:self];
+ _eventSink = nil;
+ return self;
+}
+
+- (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink {
+ _eventSink = eventSink;
+ return nil;
+}
+
+- (FlutterError*)onCancelWithArguments:(id)arguments {
+ _eventSink = nil;
+ return nil;
+}
+
+- (void)sendEvent:(id)event {
+ if (!_eventSink) return;
+ _eventSink(event);
+}
+
+- (void)dispose {
+ [_eventChannel setStreamHandler:nil];
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/ClippingAudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/ClippingAudioSource.m
new file mode 100644
index 00000000..e65fb016
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/ClippingAudioSource.m
@@ -0,0 +1,121 @@
+#import "./include/just_audio/AudioSource.h"
+#import "./include/just_audio/ClippingAudioSource.h"
+#import "./include/just_audio/IndexedPlayerItem.h"
+#import "./include/just_audio/UriAudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+
+@implementation ClippingAudioSource {
+ UriAudioSource *_audioSource;
+ CMTime _start;
+ CMTime _end;
+}
+
+- (instancetype)initWithId:(NSString *)sid audioSource:(UriAudioSource *)audioSource start:(NSNumber *)start end:(NSNumber *)end {
+ self = [super initWithId:sid];
+ NSAssert(self, @"super init cannot be nil");
+ _audioSource = audioSource;
+ _start = start == (id)[NSNull null] ? kCMTimeZero : CMTimeMake([start longLongValue], 1000000);
+ _end = end == (id)[NSNull null] ? kCMTimeInvalid : CMTimeMake([end longLongValue], 1000000);
+ return self;
+}
+
+- (UriAudioSource *)audioSource {
+ return _audioSource;
+}
+
+- (BOOL)lazyLoading {
+ return _audioSource.lazyLoading;
+}
+
+- (void)setLazyLoading:(BOOL)lazyLoading {
+ _audioSource.lazyLoading = lazyLoading;
+}
+
+- (void)findById:(NSString *)sourceId matches:(NSMutableArray<AudioSource *> *)matches {
+ [super findById:sourceId matches:matches];
+ [_audioSource findById:sourceId matches:matches];
+}
+
+- (void)attach:(AVQueuePlayer *)player initialPos:(CMTime)initialPos {
+ // Force super.attach to correct for the initial position.
+ if (CMTIME_IS_INVALID(initialPos)) {
+ initialPos = kCMTimeZero;
+ }
+ // Prepare clip to start/end at the right timestamps.
+ _audioSource.playerItem.forwardPlaybackEndTime = _end;
+ [super attach:player initialPos:initialPos];
+}
+
+- (IndexedPlayerItem *)playerItem {
+ return _audioSource.playerItem;
+}
+
+- (IndexedPlayerItem *)playerItem2 {
+ return _audioSource.playerItem2;
+}
+
+- (NSArray<NSNumber *> *)getShuffleIndices {
+ return @[@(0)];
+}
+
+- (void)play:(AVQueuePlayer *)player {
+}
+
+- (void)pause:(AVQueuePlayer *)player {
+}
+
+- (void)stop:(AVQueuePlayer *)player {
+}
+
+- (void)seek:(CMTime)position completionHandler:(void (^)(BOOL))completionHandler {
+ if (!completionHandler || (self.playerItem.status == AVPlayerItemStatusReadyToPlay)) {
+ CMTime absPosition = CMTimeAdd(_start, position);
+ [_audioSource.playerItem seekToTime:absPosition toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:completionHandler];
+ } else {
+ [super seek:position completionHandler:completionHandler];
+ }
+}
+
+- (void)flip {
+ [_audioSource flip];
+}
+
+- (void)preparePlayerItem2 {
+ if (self.playerItem2) return;
+ [_audioSource preparePlayerItem2];
+ IndexedPlayerItem *item = _audioSource.playerItem2;
+ // Prepare loop clip to start/end at the right timestamps.
+ item.forwardPlaybackEndTime = _end;
+ [item seekToTime:_start toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:nil];
+}
+
+- (CMTime)duration {
+ return CMTimeSubtract(CMTIME_IS_INVALID(_end) ? self.playerItem.duration : _end, _start);
+}
+
+- (void)setDuration:(CMTime)duration {
+}
+
+- (CMTime)position {
+ return CMTimeSubtract(self.playerItem.currentTime, _start);
+}
+
+- (CMTime)bufferedPosition {
+ CMTime pos = CMTimeSubtract(_audioSource.bufferedPosition, _start);
+ CMTime dur = [self duration];
+ return CMTimeCompare(pos, dur) >= 0 ? dur : pos;
+}
+
+- (void)applyPreferredForwardBufferDuration {
+ [_audioSource applyPreferredForwardBufferDuration];
+}
+
+- (void)applyCanUseNetworkResourcesForLiveStreamingWhilePaused {
+ [_audioSource applyCanUseNetworkResourcesForLiveStreamingWhilePaused];
+}
+
+- (void)applyPreferredPeakBitRate {
+ [_audioSource applyPreferredPeakBitRate];
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/ConcatenatingAudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/ConcatenatingAudioSource.m
new file mode 100644
index 00000000..fa8956fb
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/ConcatenatingAudioSource.m
@@ -0,0 +1,103 @@
+#import "./include/just_audio/AudioSource.h"
+#import "./include/just_audio/ConcatenatingAudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+#import <stdlib.h>
+
+@implementation ConcatenatingAudioSource {
+ NSMutableArray<AudioSource *> *_audioSources;
+ NSArray<NSNumber *> *_shuffleOrder;
+}
+
+- (instancetype)initWithId:(NSString *)sid audioSources:(NSMutableArray<AudioSource *> *)audioSources shuffleOrder:(NSArray<NSNumber *> *)shuffleOrder lazyLoading:(NSNumber *)lazyLoading {
+ self = [super initWithId:sid];
+ NSAssert(self, @"super init cannot be nil");
+ _audioSources = audioSources;
+ _shuffleOrder = shuffleOrder;
+ self.lazyLoading = [lazyLoading boolValue];
+ return self;
+}
+
+- (int)count {
+ return (int)_audioSources.count;
+}
+
+- (BOOL)lazyLoading {
+ return [_audioSources count] > 0 ? _audioSources[0].lazyLoading : NO;
+}
+
+- (void)setLazyLoading:(BOOL)lazyLoading {
+ for (int i = 0; i < [_audioSources count]; i++) {
+ _audioSources[i].lazyLoading = lazyLoading;
+ }
+}
+
+- (void)insertSource:(AudioSource *)audioSource atIndex:(int)index {
+ [_audioSources insertObject:audioSource atIndex:index];
+}
+
+- (void)removeSourcesFromIndex:(int)start toIndex:(int)end {
+ if (end == -1) end = (int)_audioSources.count;
+ for (int i = start; i < end; i++) {
+ [_audioSources removeObjectAtIndex:start];
+ }
+}
+
+- (void)moveSourceFromIndex:(int)currentIndex toIndex:(int)newIndex {
+ AudioSource *source = _audioSources[currentIndex];
+ [_audioSources removeObjectAtIndex:currentIndex];
+ [_audioSources insertObject:source atIndex:newIndex];
+}
+
+- (int)buildSequence:(NSMutableArray *)sequence treeIndex:(int)treeIndex {
+ for (int i = 0; i < [_audioSources count]; i++) {
+ treeIndex = [_audioSources[i] buildSequence:sequence treeIndex:treeIndex];
+ }
+ return treeIndex;
+}
+
+- (void)findById:(NSString *)sourceId matches:(NSMutableArray<AudioSource *> *)matches {
+ [super findById:sourceId matches:matches];
+ for (int i = 0; i < [_audioSources count]; i++) {
+ [_audioSources[i] findById:sourceId matches:matches];
+ }
+}
+
+- (NSArray<NSNumber *> *)getShuffleIndices {
+ NSMutableArray<NSNumber *> *order = [NSMutableArray new];
+ int offset = (int)[order count];
+ NSMutableArray<NSArray<NSNumber *> *> *childOrders = [NSMutableArray new]; // array of array of ints
+ for (int i = 0; i < [_audioSources count]; i++) {
+ AudioSource *audioSource = _audioSources[i];
+ NSArray<NSNumber *> *childShuffleIndices = [audioSource getShuffleIndices];
+ NSMutableArray<NSNumber *> *offsetChildShuffleOrder = [NSMutableArray new];
+ for (int j = 0; j < [childShuffleIndices count]; j++) {
+ [offsetChildShuffleOrder addObject:@([childShuffleIndices[j] integerValue] + offset)];
+ }
+ [childOrders addObject:offsetChildShuffleOrder];
+ offset += [childShuffleIndices count];
+ }
+ for (int i = 0; i < [_audioSources count]; i++) {
+ [order addObjectsFromArray:childOrders[[_shuffleOrder[i] integerValue]]];
+ }
+ return order;
+}
+
+- (void)setShuffleOrder:(NSArray<NSNumber *> *)shuffleOrder {
+ _shuffleOrder = shuffleOrder;
+}
+
+- (void)decodeShuffleOrder:(NSDictionary *)dict {
+ _shuffleOrder = (NSArray<NSNumber *> *)dict[@"shuffleOrder"];
+ NSArray *dictChildren = (NSArray *)dict[@"children"];
+ if (_audioSources.count != dictChildren.count) {
+ NSLog(@"decodeShuffleOrder Concatenating children don't match");
+ return;
+ }
+ for (int i = 0; i < [_audioSources count]; i++) {
+ AudioSource *child = _audioSources[i];
+ NSDictionary *dictChild = (NSDictionary *)dictChildren[i];
+ [child decodeShuffleOrder:dictChild];
+ }
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedAudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedAudioSource.m
new file mode 100644
index 00000000..45ffb674
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedAudioSource.m
@@ -0,0 +1,116 @@
+#import "./include/just_audio/IndexedAudioSource.h"
+#import "./include/just_audio/IndexedPlayerItem.h"
+#import <AVFoundation/AVFoundation.h>
+
+@implementation IndexedAudioSource {
+ BOOL _isAttached;
+ BOOL _lazyLoading;
+ CMTime _queuedSeekPos;
+ void (^_queuedSeekCompletionHandler)(BOOL);
+}
+
+- (instancetype)initWithId:(NSString *)sid {
+ self = [super initWithId:sid];
+ NSAssert(self, @"super init cannot be nil");
+ _isAttached = NO;
+ _lazyLoading = NO;
+ _queuedSeekPos = kCMTimeInvalid;
+ _queuedSeekCompletionHandler = nil;
+ return self;
+}
+
+- (void)onStatusChanged:(AVPlayerItemStatus)status {
+ if (status == AVPlayerItemStatusReadyToPlay) {
+ // This handles a pending seek during a load.
+ // TODO: Test seeking during a seek.
+ if (_queuedSeekCompletionHandler) {
+ [self seek:_queuedSeekPos completionHandler:_queuedSeekCompletionHandler];
+ _queuedSeekPos = kCMTimeInvalid;
+ _queuedSeekCompletionHandler = nil;
+ }
+ }
+}
+
+- (IndexedPlayerItem *)playerItem {
+ return nil;
+}
+
+- (IndexedPlayerItem *)playerItem2 {
+ return nil;
+}
+
+- (BOOL)isAttached {
+ return _isAttached;
+}
+
+- (BOOL)lazyLoading {
+ return _lazyLoading;
+}
+
+- (void)setLazyLoading:(BOOL)lazyLoading {
+ _lazyLoading = lazyLoading;
+}
+
+- (int)buildSequence:(NSMutableArray *)sequence treeIndex:(int)treeIndex {
+ [sequence addObject:self];
+ return treeIndex + 1;
+}
+
+- (void)attach:(AVQueuePlayer *)player initialPos:(CMTime)initialPos {
+ _isAttached = YES;
+ if (CMTIME_IS_VALID(initialPos)) {
+ [self seek:initialPos];
+ }
+}
+
+- (void)play:(AVQueuePlayer *)player {
+}
+
+- (void)pause:(AVQueuePlayer *)player {
+}
+
+- (void)stop:(AVQueuePlayer *)player {
+}
+
+- (void)seek:(CMTime)position {
+ [self seek:position completionHandler:nil];
+}
+
+- (void)seek:(CMTime)position completionHandler:(void (^)(BOOL))completionHandler {
+ if (completionHandler && (self.playerItem.status != AVPlayerItemStatusReadyToPlay)) {
+ _queuedSeekPos = position;
+ _queuedSeekCompletionHandler = completionHandler;
+ }
+}
+
+- (void)flip {
+}
+
+- (void)preparePlayerItem2 {
+}
+
+- (CMTime)duration {
+ return kCMTimeInvalid;
+}
+
+- (void)setDuration:(CMTime)duration {
+}
+
+- (CMTime)position {
+ return kCMTimeInvalid;
+}
+
+- (CMTime)bufferedPosition {
+ return kCMTimeInvalid;
+}
+
+- (void)applyPreferredForwardBufferDuration {
+}
+
+- (void)applyCanUseNetworkResourcesForLiveStreamingWhilePaused {
+}
+
+- (void)applyPreferredPeakBitRate {
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedPlayerItem.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedPlayerItem.m
new file mode 100644
index 00000000..dd4eb86e
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/IndexedPlayerItem.m
@@ -0,0 +1,6 @@
+#import "./include/just_audio/IndexedPlayerItem.h"
+#import "./include/just_audio/IndexedAudioSource.h"
+
+@implementation IndexedPlayerItem
+@synthesize audioSource;
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/JustAudioPlugin.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/JustAudioPlugin.m
new file mode 100644
index 00000000..7aac9169
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/JustAudioPlugin.m
@@ -0,0 +1,64 @@
+#import "./include/just_audio/JustAudioPlugin.h"
+#import "./include/just_audio/AudioPlayer.h"
+#import <AVFoundation/AVFoundation.h>
+#include <TargetConditionals.h>
+
+@implementation JustAudioPlugin {
+ NSObject<FlutterPluginRegistrar>* _registrar;
+ NSMutableDictionary<NSString *, AudioPlayer *> *_players;
+}
+
++ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
+ FlutterMethodChannel* channel = [FlutterMethodChannel
+ methodChannelWithName:@"com.ryanheise.just_audio.methods"
+ binaryMessenger:[registrar messenger]];
+ JustAudioPlugin* instance = [[JustAudioPlugin alloc] initWithRegistrar:registrar];
+ [registrar addMethodCallDelegate:instance channel:channel];
+}
+
+- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
+ self = [super init];
+ NSAssert(self, @"super init cannot be nil");
+ _registrar = registrar;
+ _players = [[NSMutableDictionary alloc] init];
+ return self;
+}
+
+- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
+ if ([@"init" isEqualToString:call.method]) {
+ NSDictionary *request = (NSDictionary *)call.arguments;
+ NSString *playerId = (NSString *)request[@"id"];
+ NSDictionary *loadConfiguration = (NSDictionary *)request[@"audioLoadConfiguration"];
+ if ([_players objectForKey:playerId] != nil) {
+ FlutterError *flutterError = [FlutterError errorWithCode:@"error" message:@"Platform player already exists" details:nil];
+ result(flutterError);
+ } else {
+ AudioPlayer* player = [[AudioPlayer alloc] initWithRegistrar:_registrar playerId:playerId loadConfiguration:loadConfiguration];
+ [_players setValue:player forKey:playerId];
+ result(nil);
+ }
+ } else if ([@"disposePlayer" isEqualToString:call.method]) {
+ NSDictionary *request = (NSDictionary *)call.arguments;
+ NSString *playerId = request[@"id"];
+ [_players[playerId] dispose:NO];
+ [_players setValue:nil forKey:playerId];
+ result(@{});
+ } else if ([@"disposeAllPlayers" isEqualToString:call.method]) {
+ for (NSString *playerId in _players) {
+ [_players[playerId] dispose:NO];
+ }
+ [_players removeAllObjects];
+ result(@{});
+ } else {
+ result(FlutterMethodNotImplemented);
+ }
+}
+
+- (void)dealloc {
+ for (NSString *playerId in _players) {
+ [_players[playerId] dispose:YES];
+ }
+ [_players removeAllObjects];
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/LoadControl.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/LoadControl.m
new file mode 100644
index 00000000..d27f6ef6
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/LoadControl.m
@@ -0,0 +1,7 @@
+#import "./include/just_audio/LoadControl.h"
+
+@implementation LoadControl
+@synthesize preferredForwardBufferDuration;
+@synthesize canUseNetworkResourcesForLiveStreamingWhilePaused;
+@synthesize preferredPeakBitRate;
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/LoopingAudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/LoopingAudioSource.m
new file mode 100644
index 00000000..a8a231bd
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/LoopingAudioSource.m
@@ -0,0 +1,63 @@
+#import "./include/just_audio/AudioSource.h"
+#import "./include/just_audio/LoopingAudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+
+@implementation LoopingAudioSource {
+ // An array of duplicates
+ NSArray<AudioSource *> *_audioSources; // <AudioSource *>
+}
+
+- (instancetype)initWithId:(NSString *)sid audioSources:(NSArray<AudioSource *> *)audioSources {
+ self = [super initWithId:sid];
+ NSAssert(self, @"super init cannot be nil");
+ _audioSources = audioSources;
+ return self;
+}
+
+- (BOOL)lazyLoading {
+ return [_audioSources count] > 0 ? _audioSources[0].lazyLoading : NO;
+}
+
+- (void)setLazyLoading:(BOOL)lazyLoading {
+ for (int i = 0; i < [_audioSources count]; i++) {
+ _audioSources[i].lazyLoading = lazyLoading;
+ }
+}
+
+- (int)buildSequence:(NSMutableArray *)sequence treeIndex:(int)treeIndex {
+ for (int i = 0; i < [_audioSources count]; i++) {
+ treeIndex = [_audioSources[i] buildSequence:sequence treeIndex:treeIndex];
+ }
+ return treeIndex;
+}
+
+- (void)findById:(NSString *)sourceId matches:(NSMutableArray<AudioSource *> *)matches {
+ [super findById:sourceId matches:matches];
+ for (int i = 0; i < [_audioSources count]; i++) {
+ [_audioSources[i] findById:sourceId matches:matches];
+ }
+}
+
+- (NSArray<NSNumber *> *)getShuffleIndices {
+ NSMutableArray<NSNumber *> *order = [NSMutableArray new];
+ int offset = (int)[order count];
+ for (int i = 0; i < [_audioSources count]; i++) {
+ AudioSource *audioSource = _audioSources[i];
+ NSArray<NSNumber *> *childShuffleOrder = [audioSource getShuffleIndices];
+ for (int j = 0; j < [childShuffleOrder count]; j++) {
+ [order addObject:@([childShuffleOrder[j] integerValue] + offset)];
+ }
+ offset += [childShuffleOrder count];
+ }
+ return order;
+}
+
+- (void)decodeShuffleOrder:(NSDictionary *)dict {
+ NSDictionary *dictChild = (NSDictionary *)dict[@"child"];
+ for (int i = 0; i < [_audioSources count]; i++) {
+ AudioSource *child = _audioSources[i];
+ [child decodeShuffleOrder:dictChild];
+ }
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/UriAudioSource.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/UriAudioSource.m
new file mode 100644
index 00000000..6a1ba9e9
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/UriAudioSource.m
@@ -0,0 +1,214 @@
+#import "./include/just_audio/UriAudioSource.h"
+#import "./include/just_audio/IndexedAudioSource.h"
+#import "./include/just_audio/IndexedPlayerItem.h"
+#import "./include/just_audio/LoadControl.h"
+#import <AVFoundation/AVFoundation.h>
+
+@implementation UriAudioSource {
+ NSString *_uri;
+ IndexedPlayerItem *_playerItem;
+ IndexedPlayerItem *_playerItem2;
+ /* CMTime _duration; */
+ LoadControl *_loadControl;
+ NSMutableDictionary *_headers;
+ NSDictionary *_options;
+}
+
+- (instancetype)initWithId:(NSString *)sid uri:(NSString *)uri loadControl:(LoadControl *)loadControl headers:(NSDictionary *)headers options:(NSDictionary *)options {
+ self = [super initWithId:sid];
+ NSAssert(self, @"super init cannot be nil");
+ _uri = uri;
+ _loadControl = loadControl;
+ _headers = headers != (id)[NSNull null] ? [headers mutableCopy] : nil;
+ _options = options;
+ _playerItem = [self createPlayerItem:uri];
+ _playerItem2 = nil;
+ return self;
+}
+
+- (NSString *)uri {
+ return _uri;
+}
+
+- (IndexedPlayerItem *)createPlayerItem:(NSString *)uri {
+ IndexedPlayerItem *item;
+ NSMutableDictionary *assetOptions = [[NSMutableDictionary alloc] init];
+
+ if (_options != (id)[NSNull null]) {
+ NSDictionary *darwinOptions = _options[@"darwinAssetOptions"];
+ if (darwinOptions != (id)[NSNull null]) {
+ assetOptions[AVURLAssetPreferPreciseDurationAndTimingKey] = darwinOptions[@"preferPreciseDurationAndTiming"];
+ }
+ }
+
+ if ([uri hasPrefix:@"file://"]) {
+ NSURL *fileURL = [NSURL fileURLWithPath:[[uri stringByRemovingPercentEncoding] substringFromIndex:7]];
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:assetOptions];
+ item = [[IndexedPlayerItem alloc] initWithAsset:asset];
+ } else {
+ if (_headers) {
+ // Use user-agent key if it is the only header and the API is supported.
+ if ([_headers count] == 1) {
+ if (@available(macOS 13.0, iOS 16.0, *)) {
+ NSString *userAgent = _headers[@"User-Agent"];
+ if (userAgent) {
+ [_headers removeObjectForKey:@"User-Agent"];
+ } else {
+ userAgent = _headers[@"user-agent"];
+ if (userAgent) {
+ [_headers removeObjectForKey:@"user-agent"];
+ }
+ }
+ if (userAgent) {
+ assetOptions[AVURLAssetHTTPUserAgentKey] = userAgent;
+ }
+ }
+ }
+ if ([_headers count] > 0) {
+ assetOptions[@"AVURLAssetHTTPHeaderFieldsKey"] = _headers;
+ }
+ }
+
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:uri] options:assetOptions];
+ item = [[IndexedPlayerItem alloc] initWithAsset:asset];
+ }
+ if (@available(macOS 10.13, iOS 11.0, *)) {
+ // This does the best at reducing distortion on voice with speeds below 1.0
+ item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmTimeDomain;
+ }
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ if (_loadControl.preferredForwardBufferDuration != (id)[NSNull null]) {
+ item.preferredForwardBufferDuration = (double)([_loadControl.preferredForwardBufferDuration longLongValue]/1000) / 1000.0;
+ }
+ }
+ if (@available(iOS 9.0, macOS 10.11, *)) {
+ item.canUseNetworkResourcesForLiveStreamingWhilePaused = _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused;
+ }
+ if (@available(iOS 8.0, macOS 10.10, *)) {
+ if (_loadControl.preferredPeakBitRate != (id)[NSNull null]) {
+ item.preferredPeakBitRate = [_loadControl.preferredPeakBitRate doubleValue];
+ }
+ }
+
+ return item;
+}
+
+// Not used. XXX: Remove?
+- (void)applyPreferredForwardBufferDuration {
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ if (_loadControl.preferredForwardBufferDuration != (id)[NSNull null]) {
+ double value = (double)([_loadControl.preferredForwardBufferDuration longLongValue]/1000) / 1000.0;
+ _playerItem.preferredForwardBufferDuration = value;
+ if (_playerItem2) {
+ _playerItem2.preferredForwardBufferDuration = value;
+ }
+ }
+ }
+}
+
+- (void)applyCanUseNetworkResourcesForLiveStreamingWhilePaused {
+ if (@available(iOS 9.0, macOS 10.11, *)) {
+ _playerItem.canUseNetworkResourcesForLiveStreamingWhilePaused = _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused;
+ if (_playerItem2) {
+ _playerItem2.canUseNetworkResourcesForLiveStreamingWhilePaused = _loadControl.canUseNetworkResourcesForLiveStreamingWhilePaused;
+ }
+ }
+}
+
+- (void)applyPreferredPeakBitRate {
+ if (@available(iOS 8.0, macOS 10.10, *)) {
+ if (_loadControl.preferredPeakBitRate != (id)[NSNull null]) {
+ double value = [_loadControl.preferredPeakBitRate doubleValue];
+ _playerItem.preferredPeakBitRate = value;
+ if (_playerItem2) {
+ _playerItem2.preferredPeakBitRate = value;
+ }
+ }
+ }
+}
+
+- (IndexedPlayerItem *)playerItem {
+ return _playerItem;
+}
+
+- (IndexedPlayerItem *)playerItem2 {
+ return _playerItem2;
+}
+
+- (NSArray<NSNumber *> *)getShuffleIndices {
+ return @[@(0)];
+}
+
+- (void)play:(AVQueuePlayer *)player {
+}
+
+- (void)pause:(AVQueuePlayer *)player {
+}
+
+- (void)stop:(AVQueuePlayer *)player {
+}
+
+- (void)seek:(CMTime)position completionHandler:(void (^)(BOOL))completionHandler {
+ if (!completionHandler || (_playerItem.status == AVPlayerItemStatusReadyToPlay)) {
+ NSValue *seekableRange = _playerItem.seekableTimeRanges.lastObject;
+ if (seekableRange) {
+ CMTimeRange range = [seekableRange CMTimeRangeValue];
+ position = CMTimeAdd(position, range.start);
+ }
+ [_playerItem seekToTime:position toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:completionHandler];
+ } else {
+ [super seek:position completionHandler:completionHandler];
+ }
+}
+
+- (void)flip {
+ IndexedPlayerItem *temp = _playerItem;
+ _playerItem = _playerItem2;
+ _playerItem2 = temp;
+}
+
+- (void)preparePlayerItem2 {
+ if (!_playerItem2) {
+ _playerItem2 = [self createPlayerItem:_uri];
+ _playerItem2.audioSource = _playerItem.audioSource;
+ }
+}
+
+- (CMTime)duration {
+ NSValue *seekableRange = _playerItem.seekableTimeRanges.lastObject;
+ if (seekableRange) {
+ CMTimeRange seekableDuration = [seekableRange CMTimeRangeValue];
+ return seekableDuration.duration;
+ }
+ else {
+ return _playerItem.duration;
+ }
+ return kCMTimeInvalid;
+}
+
+- (void)setDuration:(CMTime)duration {
+}
+
+- (CMTime)position {
+ NSValue *seekableRange = _playerItem.seekableTimeRanges.lastObject;
+ if (seekableRange) {
+ CMTimeRange range = [seekableRange CMTimeRangeValue];
+ return CMTimeSubtract(_playerItem.currentTime, range.start);
+ } else {
+ return _playerItem.currentTime;
+ }
+
+}
+
+- (CMTime)bufferedPosition {
+ NSValue *last = _playerItem.loadedTimeRanges.lastObject;
+ if (last) {
+ CMTimeRange timeRange = [last CMTimeRangeValue];
+ return CMTimeAdd(timeRange.start, timeRange.duration);
+ } else {
+ return _playerItem.currentTime;
+ }
+ return kCMTimeInvalid;
+}
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioPlayer.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioPlayer.h
new file mode 100644
index 00000000..ae402b4b
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioPlayer.h
@@ -0,0 +1,30 @@
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface AudioPlayer : NSObject<AVPlayerItemMetadataOutputPushDelegate>
+
+@property (readonly, nonatomic) AVQueuePlayer *player;
+@property (readonly, nonatomic) float speed;
+
+- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar playerId:(NSString*)idParam loadConfiguration:(NSDictionary *)loadConfiguration;
+- (void)dispose:(BOOL)calledFromDealloc;
+
+@end
+
+enum ProcessingState {
+ none,
+ loading,
+ buffering,
+ ready,
+ completed
+};
+
+enum LoopMode {
+ loopOff,
+ loopOne,
+ loopAll
+};
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioSource.h
new file mode 100644
index 00000000..b07371bd
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/AudioSource.h
@@ -0,0 +1,19 @@
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface AudioSource : NSObject
+
+@property (readonly, nonatomic) NSString* sourceId;
+@property (readwrite, nonatomic) BOOL lazyLoading;
+
+- (instancetype)initWithId:(NSString *)sid;
+- (int)buildSequence:(NSMutableArray *)sequence treeIndex:(int)treeIndex;
+- (void)findById:(NSString *)sourceId matches:(NSMutableArray<AudioSource *> *)matches;
+- (NSArray<NSNumber *> *)getShuffleIndices;
+- (void)decodeShuffleOrder:(NSDictionary *)dict;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/BetterEventChannel.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/BetterEventChannel.h
new file mode 100644
index 00000000..999395d0
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/BetterEventChannel.h
@@ -0,0 +1,14 @@
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface BetterEventChannel : NSObject<FlutterStreamHandler>
+
+- (instancetype)initWithName:(NSString*)name messenger:(NSObject<FlutterBinaryMessenger> *)messenger;
+- (void)sendEvent:(id)event;
+- (void)dispose;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ClippingAudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ClippingAudioSource.h
new file mode 100644
index 00000000..cccb4985
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ClippingAudioSource.h
@@ -0,0 +1,16 @@
+#import "AudioSource.h"
+#import "UriAudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface ClippingAudioSource : IndexedAudioSource
+
+@property (readonly, nonatomic) UriAudioSource* audioSource;
+
+- (instancetype)initWithId:(NSString *)sid audioSource:(UriAudioSource *)audioSource start:(NSNumber *)start end:(NSNumber *)end;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ConcatenatingAudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ConcatenatingAudioSource.h
new file mode 100644
index 00000000..07c5bc1a
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/ConcatenatingAudioSource.h
@@ -0,0 +1,19 @@
+#import "AudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface ConcatenatingAudioSource : AudioSource
+
+@property (readonly, nonatomic) int count;
+
+- (instancetype)initWithId:(NSString *)sid audioSources:(NSMutableArray<AudioSource *> *)audioSources shuffleOrder:(NSArray<NSNumber *> *)shuffleOrder lazyLoading:(NSNumber *)lazyLoading;
+- (void)insertSource:(AudioSource *)audioSource atIndex:(int)index;
+- (void)removeSourcesFromIndex:(int)start toIndex:(int)end;
+- (void)moveSourceFromIndex:(int)currentIndex toIndex:(int)newIndex;
+- (void)setShuffleOrder:(NSArray<NSNumber *> *)shuffleOrder;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedAudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedAudioSource.h
new file mode 100644
index 00000000..5e560f1c
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedAudioSource.h
@@ -0,0 +1,32 @@
+#import "AudioSource.h"
+#import "IndexedPlayerItem.h"
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface IndexedAudioSource : AudioSource
+
+@property (readonly, nonatomic) IndexedPlayerItem *playerItem;
+@property (readonly, nonatomic) IndexedPlayerItem *playerItem2;
+@property (readwrite, nonatomic) CMTime duration;
+@property (readonly, nonatomic) CMTime position;
+@property (readonly, nonatomic) CMTime bufferedPosition;
+@property (readonly, nonatomic) BOOL isAttached;
+
+- (void)onStatusChanged:(AVPlayerItemStatus)status;
+- (void)attach:(AVQueuePlayer *)player initialPos:(CMTime)initialPos;
+- (void)play:(AVQueuePlayer *)player;
+- (void)pause:(AVQueuePlayer *)player;
+- (void)stop:(AVQueuePlayer *)player;
+- (void)seek:(CMTime)position;
+- (void)seek:(CMTime)position completionHandler:(void (^)(BOOL))completionHandler;
+- (void)preparePlayerItem2;
+- (void)flip;
+- (void)applyPreferredForwardBufferDuration;
+- (void)applyCanUseNetworkResourcesForLiveStreamingWhilePaused;
+- (void)applyPreferredPeakBitRate;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedPlayerItem.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedPlayerItem.h
new file mode 100644
index 00000000..8a86a94d
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/IndexedPlayerItem.h
@@ -0,0 +1,9 @@
+#import <AVFoundation/AVFoundation.h>
+
+@class IndexedAudioSource;
+
+@interface IndexedPlayerItem : AVPlayerItem
+
+@property (readwrite, nonatomic, weak) IndexedAudioSource *audioSource;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/JustAudioPlugin.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/JustAudioPlugin.h
new file mode 100644
index 00000000..bdb94e74
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/JustAudioPlugin.h
@@ -0,0 +1,9 @@
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface JustAudioPlugin : NSObject<FlutterPlugin>
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoadControl.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoadControl.h
new file mode 100644
index 00000000..a115fdae
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoadControl.h
@@ -0,0 +1,9 @@
+#import <Foundation/Foundation.h>
+
+@interface LoadControl : NSObject
+
+@property (readwrite, nonatomic) NSNumber *preferredForwardBufferDuration;
+@property (readwrite, nonatomic) BOOL canUseNetworkResourcesForLiveStreamingWhilePaused;
+@property (readwrite, nonatomic) NSNumber *preferredPeakBitRate;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoopingAudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoopingAudioSource.h
new file mode 100644
index 00000000..ce6e4b16
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/LoopingAudioSource.h
@@ -0,0 +1,13 @@
+#import "AudioSource.h"
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface LoopingAudioSource : AudioSource
+
+- (instancetype)initWithId:(NSString *)sid audioSources:(NSArray<AudioSource *> *)audioSources;
+
+@end
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/UriAudioSource.h b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/UriAudioSource.h
new file mode 100644
index 00000000..ddf38043
--- /dev/null
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/include/just_audio/UriAudioSource.h
@@ -0,0 +1,16 @@
+#import "IndexedAudioSource.h"
+#import "LoadControl.h"
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface UriAudioSource : IndexedAudioSource
+
+@property (readonly, nonatomic) NSString *uri;
+
+- (instancetype)initWithId:(NSString *)sid uri:(NSString *)uri loadControl:(LoadControl *)loadControl headers:(NSDictionary *)headers options:(NSDictionary *)options;
+
+@end
diff --git a/packages/just_audio/lib/just_audio.dart b/packages/just_audio/lib/just_audio.dart
new file mode 100644
index 00000000..84688a2b
--- /dev/null
+++ b/packages/just_audio/lib/just_audio.dart
@@ -0,0 +1,4081 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
+import 'package:audio_session/audio_session.dart';
+import 'package:crypto/crypto.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:just_audio_platform_interface/just_audio_platform_interface.dart';
+import 'package:meta/meta.dart' show experimental;
+import 'package:path/path.dart' as p;
+import 'package:path_provider/path_provider.dart';
+import 'package:rxdart/rxdart.dart';
+import 'package:uuid/uuid.dart';
+
+const _uuid = Uuid();
+
+JustAudioPlatform? _pluginPlatformCache;
+
+JustAudioPlatform get _pluginPlatform {
+ var pluginPlatform = JustAudioPlatform.instance;
+ // If this is a new FlutterEngine or if we've just hot restarted an existing
+ // FlutterEngine...
+ if (_pluginPlatformCache == null) {
+ // Dispose of all existing players within this FlutterEngine. This helps to
+ // shut down existing players on a hot restart. TODO: Remove this hack once
+ // https://github.com/flutter/flutter/issues/10437 is implemented.
+ try {
+ pluginPlatform.disposeAllPlayers(DisposeAllPlayersRequest());
+ } catch (e) {
+ // Silently ignore if a platform doesn't support this method.
+ }
+ _pluginPlatformCache = pluginPlatform;
+ }
+ return pluginPlatform;
+}
+
+/// An object to manage playing audio from a URL, a locale file or an asset.
+///
+/// ```
+/// final player = AudioPlayer();
+/// await player.setUrl('https://foo.com/bar.mp3');
+/// player.play();
+/// await player.pause();
+/// await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 20));
+/// await player.play();
+/// await player.setUrl('https://foo.com/baz.mp3');
+/// await player.seek(Duration(minutes: 5));
+/// player.play();
+/// await player.pause();
+/// await player.dispose();
+/// ```
+///
+/// You must call [dispose] to release the resources used by this player,
+/// including any temporary files created to cache assets.
+class AudioPlayer {
+ /// The user agent to set on all HTTP requests.
+ final String? _userAgent;
+
+ /// Whether to use the proxy server to send request headers.
+ final bool _useProxyForRequestHeaders;
+
+ final AudioLoadConfiguration? _audioLoadConfiguration;
+
+ final bool _androidOffloadSchedulingEnabled;
+
+ /// This is `true` when the audio player needs to engage the native platform
+ /// side of the plugin to decode or play audio, and is `false` when the native
+ /// resources are not needed (i.e. after initial instantiation and after [stop]).
+ bool _active = false;
+
+ /// This is set to [_nativePlatform] when [_active] is `true` and
+ /// [_idlePlatform] otherwise.
+ late Future<AudioPlayerPlatform> _platform;
+
+ /// Reflects the current platform immediately after it is set.
+ AudioPlayerPlatform? _platformValue;
+
+ /// The interface to the native portion of the plugin. This will be disposed
+ /// and set to `null` when not in use.
+ Future<AudioPlayerPlatform>? _nativePlatform;
+
+ /// A pure Dart implementation of the platform interface for use when the
+ /// native platform is not needed.
+ _IdleAudioPlayer? _idlePlatform;
+
+ /// The subscription to the event channel of the current platform
+ /// implementation. When switching between active and inactive modes, this is
+ /// used to cancel the subscription to the previous platform's events and
+ /// subscribe to the new platform's events.
+ StreamSubscription<PlaybackEventMessage>? _playbackEventSubscription;
+
+ /// The subscription to the data event channel of the current platform
+ /// implementation. When switching between active and inactive modes, this is
+ /// used to cancel the subscription to the previous platform's events and
+ /// subscribe to the new platform's events.
+ StreamSubscription<PlayerDataMessage>? _playerDataSubscription;
+
+ StreamSubscription<AndroidAudioAttributes>?
+ _androidAudioAttributesSubscription;
+ StreamSubscription<void>? _becomingNoisyEventSubscription;
+ StreamSubscription<AudioInterruptionEvent>? _interruptionEventSubscription;
+
+ final String _id;
+ final _proxy = _ProxyHttpServer();
+ AudioSource? _audioSource;
+ final Map<String, AudioSource> _audioSources = {};
+ bool _disposed = false;
+ _InitialSeekValues? _initialSeekValues;
+ final AudioPipeline _audioPipeline;
+
+ PlaybackEvent _playbackEvent = PlaybackEvent();
+ final _playbackEventSubject = BehaviorSubject<PlaybackEvent>(sync: true);
+ Future<Duration?>? _durationFuture;
+ final _durationSubject = BehaviorSubject<Duration?>();
+ final _processingStateSubject = BehaviorSubject<ProcessingState>();
+ final _playingSubject = BehaviorSubject.seeded(false);
+ final _volumeSubject = BehaviorSubject.seeded(1.0);
+ final _speedSubject = BehaviorSubject.seeded(1.0);
+ final _pitchSubject = BehaviorSubject.seeded(1.0);
+ final _skipSilenceEnabledSubject = BehaviorSubject.seeded(false);
+ final _bufferedPositionSubject = BehaviorSubject<Duration>();
+ final _icyMetadataSubject = BehaviorSubject<IcyMetadata?>();
+ final _playerStateSubject = BehaviorSubject<PlayerState>();
+ final _sequenceSubject = BehaviorSubject<List<IndexedAudioSource>?>();
+ final _shuffleIndicesSubject = BehaviorSubject<List<int>?>();
+ final _shuffleIndicesInv = <int>[];
+ final _currentIndexSubject = BehaviorSubject<int?>(sync: true);
+ final _sequenceStateSubject = BehaviorSubject<SequenceState?>();
+ final _loopModeSubject = BehaviorSubject.seeded(LoopMode.off);
+ final _shuffleModeEnabledSubject = BehaviorSubject.seeded(false);
+ final _androidAudioSessionIdSubject = BehaviorSubject<int?>();
+ final _positionDiscontinuitySubject =
+ PublishSubject<PositionDiscontinuity>(sync: true);
+ var _seeking = false;
+ // ignore: close_sinks
+ BehaviorSubject<Duration>? _positionSubject;
+ bool _automaticallyWaitsToMinimizeStalling = true;
+ bool _canUseNetworkResourcesForLiveStreamingWhilePaused = false;
+ double _preferredPeakBitRate = 0;
+ bool _allowsExternalPlayback = false;
+ bool _playInterrupted = false;
+ bool _platformLoading = false;
+ AndroidAudioAttributes? _androidAudioAttributes;
+ WebCrossOrigin? _webCrossOrigin;
+ String _webSinkId = '';
+ final bool _androidApplyAudioAttributes;
+ final bool _handleAudioSessionActivation;
+
+ /// Counts how many times [_setPlatformActive] is called.
+ int _activationCount = 0;
+
+ /// Creates an [AudioPlayer].
+ ///
+ /// Apps requesting remote URLs should set the [userAgent] parameter which
+ /// will be set as the `user-agent` header on all requests (except on web
+ /// where the browser's user agent will be used) to identify the client. If
+ /// unspecified, a platform-specific default will be supplied.
+ ///
+ /// Request headers including `user-agent` are sent by default via a local
+ /// HTTP proxy which requires non-HTTPS support to be enabled (see the README
+ /// page for setup instructions). Alternatively, you can set
+ /// [useProxyForRequestHeaders] to `false` to allow supported platforms to
+ /// send the request headers directly without use of the proxy. On iOS/macOS,
+ /// this will use the `AVURLAssetHTTPUserAgentKey` on iOS 16 and above, and
+ /// macOS 13 and above, if `user-agent` is the only header used. Otherwise,
+ /// the `AVURLAssetHTTPHeaderFieldsKey` key will be used. On Android, this
+ /// will use ExoPlayer's `setUserAgent` and `setDefaultRequestProperties`.
+ /// For Linux/Windows federated platform implementations, refer to the
+ /// documentation for that implementation's support.
+ ///
+ /// The player will automatically pause/duck and resume/unduck when audio
+ /// interruptions occur (e.g. a phone call) or when headphones are unplugged.
+ /// If you wish to handle audio interruptions manually, set
+ /// [handleInterruptions] to `false` and interface directly with the audio
+ /// session via the [audio_session](https://pub.dev/packages/audio_session)
+ /// package. If you do not wish just_audio to automatically activate the audio
+ /// session when playing audio, set [handleAudioSessionActivation] to `false`.
+ /// If you do not want just_audio to respect the global
+ /// [AndroidAudioAttributes] configured by audio_session, set
+ /// [androidApplyAudioAttributes] to `false`.
+ ///
+ /// The default audio loading and buffering behaviour can be configured via
+ /// the [audioLoadConfiguration] parameter.
+ AudioPlayer({
+ String? userAgent,
+ bool handleInterruptions = true,
+ bool androidApplyAudioAttributes = true,
+ bool handleAudioSessionActivation = true,
+ AudioLoadConfiguration? audioLoadConfiguration,
+ AudioPipeline? audioPipeline,
+ bool androidOffloadSchedulingEnabled = false,
+ bool useProxyForRequestHeaders = true,
+ }) : _id = _uuid.v4(),
+ _userAgent = userAgent,
+ _androidApplyAudioAttributes =
+ androidApplyAudioAttributes && _isAndroid(),
+ _handleAudioSessionActivation = handleAudioSessionActivation,
+ _audioLoadConfiguration = audioLoadConfiguration,
+ _audioPipeline = audioPipeline ?? AudioPipeline(),
+ _androidOffloadSchedulingEnabled = androidOffloadSchedulingEnabled,
+ _useProxyForRequestHeaders = useProxyForRequestHeaders {
+ _audioPipeline._setup(this);
+ if (_audioLoadConfiguration?.darwinLoadControl != null) {
+ _automaticallyWaitsToMinimizeStalling = _audioLoadConfiguration!
+ .darwinLoadControl!.automaticallyWaitsToMinimizeStalling;
+ }
+ _playbackEventSubject.add(_playbackEvent);
+ _processingStateSubject.addStream(playbackEventStream
+ .map((event) => event.processingState)
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _bufferedPositionSubject.addStream(playbackEventStream
+ .map((event) => event.bufferedPosition)
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _icyMetadataSubject.addStream(playbackEventStream
+ .map((event) => event.icyMetadata)
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ playbackEventStream.pairwise().listen((pair) {
+ final prev = pair.first;
+ final curr = pair.last;
+ // Detect auto-advance
+ if (_seeking) return;
+ if (prev.currentIndex == null || curr.currentIndex == null) return;
+ if (curr.currentIndex != prev.currentIndex) {
+ // If we've changed item without seeking, it must be an autoAdvance.
+ _positionDiscontinuitySubject.add(PositionDiscontinuity(
+ PositionDiscontinuityReason.autoAdvance, prev, curr));
+ } else {
+ // If the item is the same, try to determine whether we have looped
+ // back.
+ final prevPos = _getPositionFor(prev);
+ final currPos = _getPositionFor(curr);
+ if (loopMode != LoopMode.one) return;
+ if (currPos >= prevPos) return;
+ if (currPos >= const Duration(milliseconds: 300)) return;
+ final duration = this.duration;
+ if (duration != null && prevPos < duration * 0.6) return;
+ if (duration == null &&
+ currPos - prevPos < const Duration(seconds: 1)) {
+ return;
+ }
+ _positionDiscontinuitySubject.add(PositionDiscontinuity(
+ PositionDiscontinuityReason.autoAdvance, prev, curr));
+ }
+ }, onError: (Object e, StackTrace st) {});
+ _currentIndexSubject.addStream(playbackEventStream
+ .map((event) => event.currentIndex)
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _androidAudioSessionIdSubject.addStream(playbackEventStream
+ .map((event) => event.androidAudioSessionId)
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _sequenceStateSubject.addStream(Rx.combineLatest5<List<IndexedAudioSource>?,
+ List<int>?, int?, bool, LoopMode, SequenceState?>(
+ sequenceStream,
+ shuffleIndicesStream,
+ currentIndexStream,
+ shuffleModeEnabledStream,
+ loopModeStream,
+ (sequence, shuffleIndices, currentIndex, shuffleModeEnabled, loopMode) {
+ if (sequence == null) return null;
+ if (shuffleIndices == null) return null;
+ currentIndex ??= 0;
+ currentIndex = max(min(sequence.length - 1, max(0, currentIndex)), 0);
+ return SequenceState(
+ sequence,
+ currentIndex,
+ shuffleIndices,
+ shuffleModeEnabled,
+ loopMode,
+ );
+ },
+ ).distinct().handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _playerStateSubject.addStream(
+ Rx.combineLatest2<bool, PlaybackEvent, PlayerState>(
+ playingStream,
+ playbackEventStream,
+ (playing, event) => PlayerState(playing, event.processingState))
+ .distinct()
+ .handleError((Object err, StackTrace stackTrace) {/* noop */}));
+ _shuffleModeEnabledSubject.add(false);
+ _loopModeSubject.add(LoopMode.off);
+ _setPlatformActive(false, force: true)
+ ?.catchError((dynamic e) async => null);
+ _sequenceSubject.add(null);
+ // Respond to changes to AndroidAudioAttributes configuration.
+ if (androidApplyAudioAttributes && _isAndroid()) {
+ AudioSession.instance.then((audioSession) {
+ _androidAudioAttributesSubscription = audioSession.configurationStream
+ .map((conf) => conf.androidAudioAttributes)
+ .where((attributes) => attributes != null)
+ .cast<AndroidAudioAttributes>()
+ .distinct()
+ .listen(setAndroidAudioAttributes);
+ });
+ }
+ if (handleInterruptions) {
+ AudioSession.instance.then((session) {
+ _becomingNoisyEventSubscription =
+ session.becomingNoisyEventStream.listen((_) {
+ pause();
+ });
+ _interruptionEventSubscription =
+ session.interruptionEventStream.listen((event) {
+ if (event.begin) {
+ switch (event.type) {
+ case AudioInterruptionType.duck:
+ assert(_isAndroid());
+ if (session.androidAudioAttributes!.usage ==
+ AndroidAudioUsage.game) {
+ setVolume(volume / 2);
+ }
+ _playInterrupted = false;
+ break;
+ case AudioInterruptionType.pause:
+ case AudioInterruptionType.unknown:
+ if (playing) {
+ pause();
+ // Although pause is async and sets _playInterrupted = false,
+ // this is done in the sync portion.
+ _playInterrupted = true;
+ }
+ break;
+ }
+ } else {
+ switch (event.type) {
+ case AudioInterruptionType.duck:
+ assert(_isAndroid());
+ setVolume(min(1.0, volume * 2));
+ _playInterrupted = false;
+ break;
+ case AudioInterruptionType.pause:
+ if (_playInterrupted) play();
+ _playInterrupted = false;
+ break;
+ case AudioInterruptionType.unknown:
+ _playInterrupted = false;
+ break;
+ }
+ }
+ });
+ });
+ }
+ _removeOldAssetCacheDir();
+ }
+
+ /// Old versions of just_audio used an asset caching system that created a
+ /// separate cache file per asset per player instance, and was highly
+ /// dependent on the app calling [dispose] to clean up afterwards. If the app
+ /// is upgrading from an old version of just_audio, this will delete the old
+ /// cache directory.
+ Future<void> _removeOldAssetCacheDir() async {
+ if (kIsWeb) return;
+ try {
+ final oldAssetCacheDir = Directory(p.join(
+ (await getTemporaryDirectory()).path, 'just_audio_asset_cache'));
+ if (oldAssetCacheDir.existsSync()) {
+ try {
+ oldAssetCacheDir.deleteSync(recursive: true);
+ } catch (e) {
+ // ignore: avoid_print
+ print("Failed to delete old asset cache dir: $e");
+ }
+ }
+ } catch (e) {
+ // There is no temporary directory for this platform.
+ }
+ }
+
+ /// The previously set [AudioSource], if any.
+ AudioSource? get audioSource => _audioSource;
+
+ /// The latest [PlaybackEvent].
+ PlaybackEvent get playbackEvent => _playbackEvent;
+
+ /// A stream of [PlaybackEvent]s.
+ Stream<PlaybackEvent> get playbackEventStream => _playbackEventSubject.stream;
+
+ /// The duration of the current audio or `null` if unknown.
+ Duration? get duration => _playbackEvent.duration;
+
+ /// The duration of the current audio or `null` if unknown.
+ Future<Duration?>? get durationFuture => _durationFuture;
+
+ /// The duration of the current audio.
+ Stream<Duration?> get durationStream => _durationSubject.stream;
+
+ /// The current [ProcessingState].
+ ProcessingState get processingState => _playbackEvent.processingState;
+
+ /// A stream of [ProcessingState]s.
+ Stream<ProcessingState> get processingStateStream =>
+ _processingStateSubject.stream;
+
+ /// Whether the player is playing.
+ bool get playing => _playingSubject.nvalue!;
+
+ /// A stream of changing [playing] states.
+ Stream<bool> get playingStream => _playingSubject.stream;
+
+ /// The current volume of the player.
+ double get volume => _volumeSubject.nvalue!;
+
+ /// A stream of [volume] changes.
+ Stream<double> get volumeStream => _volumeSubject.stream;
+
+ /// The current speed of the player.
+ double get speed => _speedSubject.nvalue!;
+
+ /// A stream of current speed values.
+ Stream<double> get speedStream => _speedSubject.stream;
+
+ /// The current pitch factor of the player.
+ double get pitch => _pitchSubject.nvalue!;
+
+ /// A stream of current pitch factor values.
+ Stream<double> get pitchStream => _pitchSubject.stream;
+
+ /// The current skipSilenceEnabled factor of the player.
+ bool get skipSilenceEnabled => _skipSilenceEnabledSubject.nvalue!;
+
+ /// A stream of current skipSilenceEnabled factor values.
+ Stream<bool> get skipSilenceEnabledStream =>
+ _skipSilenceEnabledSubject.stream;
+
+ /// The position up to which buffered audio is available.
+ Duration get bufferedPosition =>
+ _bufferedPositionSubject.nvalue ?? Duration.zero;
+
+ /// A stream of buffered positions.
+ Stream<Duration> get bufferedPositionStream =>
+ _bufferedPositionSubject.stream;
+
+ /// The latest ICY metadata received through the audio source, or `null` if no
+ /// metadata is available.
+ IcyMetadata? get icyMetadata => _playbackEvent.icyMetadata;
+
+ /// A stream of ICY metadata received through the audio source.
+ Stream<IcyMetadata?> get icyMetadataStream => _icyMetadataSubject.stream;
+
+ /// The current player state containing only the processing and playing
+ /// states.
+ PlayerState get playerState =>
+ _playerStateSubject.nvalue ?? PlayerState(false, ProcessingState.idle);
+
+ /// A stream of [PlayerState]s.
+ Stream<PlayerState> get playerStateStream => _playerStateSubject.stream;
+
+ /// The current sequence of indexed audio sources, or `null` if no audio
+ /// source is set.
+ List<IndexedAudioSource>? get sequence => _sequenceSubject.nvalue;
+
+ /// A stream broadcasting the current sequence of indexed audio sources.
+ Stream<List<IndexedAudioSource>?> get sequenceStream =>
+ _sequenceSubject.stream;
+
+ /// The current shuffled sequence of indexed audio sources, or `null` if no
+ /// audio source is set.
+ List<int>? get shuffleIndices => _shuffleIndicesSubject.nvalue;
+
+ /// A stream broadcasting the current shuffled sequence of indexed audio
+ /// sources.
+ Stream<List<int>?> get shuffleIndicesStream => _shuffleIndicesSubject.stream;
+
+ //List<IndexedAudioSource> get _effectiveSequence =>
+ // shuffleModeEnabled ? shuffleIndices : sequence;
+
+ /// The index of the current item, or `null` if either no audio source is set,
+ /// or the current audio source has an empty sequence.
+ int? get currentIndex => _currentIndexSubject.nvalue;
+
+ /// A stream broadcasting the current item.
+ Stream<int?> get currentIndexStream => _currentIndexSubject.stream;
+
+ /// The current [SequenceState], or `null` if either [sequence]] or
+ /// [currentIndex] is `null`.
+ SequenceState? get sequenceState => _sequenceStateSubject.nvalue;
+
+ /// A stream broadcasting the current [SequenceState].
+ Stream<SequenceState?> get sequenceStateStream =>
+ _sequenceStateSubject.stream;
+
+ /// Whether there is another item after the current index.
+ bool get hasNext => nextIndex != null;
+
+ /// Whether there is another item before the current index.
+ bool get hasPrevious => previousIndex != null;
+
+ /// Returns [shuffleIndices] if [shuffleModeEnabled] is `true`, otherwise
+ /// returns the unshuffled indices. When no current audio source is set, this
+ /// returns `null`.
+ List<int>? get effectiveIndices {
+ if (shuffleIndices == null || sequence == null) return null;
+ return shuffleModeEnabled
+ ? shuffleIndices
+ : List.generate(sequence!.length, (i) => i);
+ }
+
+ List<int>? get _effectiveIndicesInv {
+ if (shuffleIndices == null || sequence == null) return null;
+ return shuffleModeEnabled
+ ? _shuffleIndicesInv
+ : List.generate(sequence!.length, (i) => i);
+ }
+
+ /// The index of the next item to be played, or `null` if there is no next
+ /// item.
+ int? get nextIndex => _getRelativeIndex(1);
+
+ /// The index of the previous item in play order, or `null` if there is no
+ /// previous item.
+ int? get previousIndex => _getRelativeIndex(-1);
+
+ int? _getRelativeIndex(int offset) {
+ if (_audioSource == null || currentIndex == null) return null;
+ if (loopMode == LoopMode.one) return currentIndex;
+ final effectiveIndices = this.effectiveIndices;
+ if (effectiveIndices == null || effectiveIndices.isEmpty) return null;
+ final effectiveIndicesInv = _effectiveIndicesInv!;
+ if (currentIndex! >= effectiveIndicesInv.length) return null;
+ final invPos = effectiveIndicesInv[currentIndex!];
+ var newInvPos = invPos + offset;
+ if (newInvPos >= effectiveIndices.length || newInvPos < 0) {
+ if (loopMode == LoopMode.all) {
+ newInvPos %= effectiveIndices.length;
+ } else {
+ return null;
+ }
+ }
+ final result = effectiveIndices[newInvPos];
+ return result;
+ }
+
+ /// The current loop mode.
+ LoopMode get loopMode => _loopModeSubject.nvalue!;
+
+ /// A stream of [LoopMode]s.
+ Stream<LoopMode> get loopModeStream => _loopModeSubject.stream;
+
+ /// Whether shuffle mode is currently enabled.
+ bool get shuffleModeEnabled => _shuffleModeEnabledSubject.nvalue!;
+
+ /// A stream of the shuffle mode status.
+ Stream<bool> get shuffleModeEnabledStream =>
+ _shuffleModeEnabledSubject.stream;
+
+ /// The current Android AudioSession ID or `null` if not set.
+ int? get androidAudioSessionId => _playbackEvent.androidAudioSessionId;
+
+ /// Broadcasts the current Android AudioSession ID or `null` if not set.
+ Stream<int?> get androidAudioSessionIdStream =>
+ _androidAudioSessionIdSubject.stream;
+
+ /// A stream broadcasting every position discontinuity.
+ Stream<PositionDiscontinuity> get positionDiscontinuityStream =>
+ _positionDiscontinuitySubject.stream;
+
+ /// Whether the player should automatically delay playback in order to
+ /// minimize stalling. (iOS 10.0 or later only)
+ bool get automaticallyWaitsToMinimizeStalling =>
+ _automaticallyWaitsToMinimizeStalling;
+
+ /// Whether the player can use the network for live streaming while paused on
+ /// iOS/macOS.
+ bool get canUseNetworkResourcesForLiveStreamingWhilePaused =>
+ _canUseNetworkResourcesForLiveStreamingWhilePaused;
+
+ /// The preferred peak bit rate (in bits per second) of bandwidth usage on iOS/macOS.
+ double get preferredPeakBitRate => _preferredPeakBitRate;
+
+ /// Whether the player allows external playback on iOS/macOS, defaults to
+ /// false.
+ bool get allowsExternalPlayback => _allowsExternalPlayback;
+
+ /// The `crossorigin` attribute set the `<audio>` element backing this player
+ /// instance on web.
+ WebCrossOrigin? get webCrossOrigin => _webCrossOrigin;
+
+ /// The current sink ID of the `<audio>` element backing this instance on web.
+ String get webSinkId => _webSinkId;
+
+ /// The current position of the player.
+ Duration get position => _getPositionFor(_playbackEvent);
+
+ Duration _getPositionFor(PlaybackEvent playbackEvent) {
+ if (playing && processingState == ProcessingState.ready) {
+ final result = playbackEvent.updatePosition +
+ (DateTime.now().difference(playbackEvent.updateTime)) * speed;
+ return playbackEvent.duration == null || result <= playbackEvent.duration!
+ ? result
+ : playbackEvent.duration!;
+ } else {
+ return playbackEvent.updatePosition;
+ }
+ }
+
+ /// A stream tracking the current position of this player, suitable for
+ /// animating a seek bar. To ensure a smooth animation, this stream emits
+ /// values more frequently on short items where the seek bar moves more
+ /// quickly, and less frequenly on long items where the seek bar moves more
+ /// slowly. The interval between each update will be no quicker than once
+ /// every 16ms and no slower than once every 200ms.
+ ///
+ /// See [createPositionStream] for more control over the stream parameters.
+ Stream<Duration> get positionStream {
+ if (_positionSubject == null) {
+ _positionSubject = BehaviorSubject<Duration>();
+ if (!_disposed) {
+ _positionSubject!.addStream(createPositionStream(
+ steps: 800,
+ minPeriod: const Duration(milliseconds: 16),
+ maxPeriod: const Duration(milliseconds: 200)));
+ }
+ }
+ return _positionSubject!.stream;
+ }
+
+ /// Creates a new stream periodically tracking the current position of this
+ /// player. The stream will aim to emit [steps] position updates from the
+ /// beginning to the end of the current audio source, at intervals of
+ /// [duration] / [steps]. This interval will be clipped between [minPeriod]
+ /// and [maxPeriod]. This stream will not emit values while audio playback is
+ /// paused or stalled.
+ ///
+ /// Note: each time this method is called, a new stream is created. If you
+ /// intend to use this stream multiple times, you should hold a reference to
+ /// the returned stream and close it once you are done.
+ Stream<Duration> createPositionStream({
+ int steps = 800,
+ Duration minPeriod = const Duration(milliseconds: 200),
+ Duration maxPeriod = const Duration(milliseconds: 200),
+ }) {
+ assert(minPeriod <= maxPeriod);
+ assert(minPeriod > Duration.zero);
+ final controller = StreamController<Duration>.broadcast();
+ if (_disposed) return controller.stream;
+
+ Duration duration() => this.duration ?? Duration.zero;
+ Duration step() {
+ var s = duration() ~/ steps;
+ if (s < minPeriod) s = minPeriod;
+ if (s > maxPeriod) s = maxPeriod;
+ return s;
+ }
+
+ Timer? currentTimer;
+ StreamSubscription<Duration?>? durationSubscription;
+ StreamSubscription<PlaybackEvent>? playbackEventSubscription;
+ void yieldPosition(Timer timer) {
+ if (controller.isClosed || _durationSubject.isClosed) {
+ timer.cancel();
+ durationSubscription?.cancel();
+ playbackEventSubscription?.cancel();
+ if (!controller.isClosed) {
+ // This will in turn close _positionSubject.
+ controller.close();
+ }
+ return;
+ }
+ if (playing) {
+ controller.add(position);
+ }
+ }
+
+ durationSubscription = durationStream.listen((duration) {
+ currentTimer?.cancel();
+ currentTimer = Timer.periodic(step(), yieldPosition);
+ }, onError: (Object e, StackTrace stackTrace) {});
+ playbackEventSubscription = playbackEventStream.listen((event) {
+ controller.add(position);
+ }, onError: (Object e, StackTrace stackTrace) {});
+ return controller.stream.distinct();
+ }
+
+ /// Convenience method to set the audio source to a URL with optional headers,
+ /// preloaded by default, with an initial position of zero by default.
+ /// If headers are set, just_audio will create a cleartext local HTTP proxy on
+ /// your device to forward HTTP requests with headers included.
+ ///
+ /// This is equivalent to:
+ ///
+ /// ```
+ /// setAudioSource(AudioSource.uri(Uri.parse(url), headers: headers, tag: tag),
+ /// initialPosition: Duration.zero, preload: true);
+ /// ```
+ ///
+ /// See [setAudioSource] for a detailed explanation of the options.
+ Future<Duration?> setUrl(
+ String url, {
+ Map<String, String>? headers,
+ Duration? initialPosition,
+ bool preload = true,
+ dynamic tag,
+ }) =>
+ setAudioSource(
+ AudioSource.uri(Uri.parse(url), headers: headers, tag: tag),
+ initialPosition: initialPosition,
+ preload: preload);
+
+ /// Convenience method to set the audio source to a file, preloaded by
+ /// default, with an initial position of zero by default.
+ ///
+ /// This is equivalent to:
+ ///
+ /// ```
+ /// setAudioSource(AudioSource.uri(Uri.file(filePath), tag: tag),
+ /// initialPosition: Duration.zero, preload: true);
+ /// ```
+ ///
+ /// See [setAudioSource] for a detailed explanation of the options.
+ Future<Duration?> setFilePath(
+ String filePath, {
+ Duration? initialPosition,
+ bool preload = true,
+ dynamic tag,
+ }) =>
+ setAudioSource(AudioSource.file(filePath, tag: tag),
+ initialPosition: initialPosition, preload: preload);
+
+ /// Convenience method to set the audio source to an asset, preloaded by
+ /// default, with an initial position of zero by default.
+ ///
+ /// For assets within the same package, this is equivalent to:
+ ///
+ /// ```
+ /// setAudioSource(AudioSource.uri(Uri.parse('asset:///$assetPath'), tag: tag),
+ /// initialPosition: Duration.zero, preload: true);
+ /// ```
+ ///
+ /// If the asset is to be loaded from a different package, the [package]
+ /// parameter must be given to specify the package name.
+ ///
+ /// See [setAudioSource] for a detailed explanation of the options.
+ Future<Duration?> setAsset(
+ String assetPath, {
+ String? package,
+ bool preload = true,
+ Duration? initialPosition,
+ dynamic tag,
+ }) =>
+ setAudioSource(
+ AudioSource.asset(assetPath, package: package, tag: tag),
+ initialPosition: initialPosition,
+ preload: preload,
+ );
+
+ /// Sets the source from which this audio player should fetch audio.
+ ///
+ /// By default, this method will immediately start loading audio and return
+ /// its duration as soon as it is known, or `null` if that information is
+ /// unavailable. Set [preload] to `false` if you would prefer to delay loading
+ /// until some later point, either via an explicit call to [load] or via a
+ /// call to [play] which implicitly loads the audio. If [preload] is `false`,
+ /// a `null` duration will be returned. Note that the [preload] option will
+ /// automatically be assumed as `true` if `playing` is currently `true`.
+ ///
+ /// Optionally specify [initialPosition] and [initialIndex] to seek to an
+ /// initial position within a particular item (defaulting to position zero of
+ /// the first item).
+ ///
+ /// When [preload] is `true`, this method may throw:
+ ///
+ /// * [Exception] if no audio source has been previously set.
+ /// * [PlayerException] if the audio source was unable to be loaded.
+ /// * [PlayerInterruptedException] if another audio source was loaded before
+ /// this call completed or the player was stopped or disposed of before the
+ /// call completed.
+ Future<Duration?> setAudioSource(
+ AudioSource source, {
+ bool preload = true,
+ int? initialIndex,
+ Duration? initialPosition,
+ }) async {
+ if (_disposed) return null;
+ _audioSource = null;
+ _initialSeekValues =
+ _InitialSeekValues(position: initialPosition, index: initialIndex);
+ _playbackEventSubject.add(_playbackEvent = PlaybackEvent(
+ currentIndex: initialIndex ?? 0,
+ updatePosition: initialPosition ?? Duration.zero));
+ _audioSource = source;
+ _broadcastSequence();
+ Duration? duration;
+ if (playing) preload = true;
+ if (preload) {
+ duration = await load();
+ } else {
+ await _setPlatformActive(false)?.catchError((dynamic e) async => null);
+ }
+ return duration;
+ }
+
+ /// Starts loading the current audio source and returns the audio duration as
+ /// soon as it is known, or `null` if unavailable.
+ ///
+ /// This method throws:
+ ///
+ /// * [Exception] if no audio source has been previously set.
+ /// * [PlayerException] if the audio source was unable to be loaded.
+ /// * [PlayerInterruptedException] if another call to [load] happened before
+ /// this call completed or the player was stopped or disposed of before the
+ /// call could complete.
+ Future<Duration?> load() async {
+ if (_disposed) return null;
+ if (_audioSource == null) {
+ throw Exception('Must set AudioSource before loading');
+ }
+ if (_active) {
+ final initialSeekValues = _initialSeekValues;
+ _initialSeekValues = null;
+ return await _load(await _platform, _audioSource!,
+ initialSeekValues: initialSeekValues);
+ } else {
+ // This will implicitly load the current audio source.
+ return await _setPlatformActive(true);
+ }
+ }
+
+ void _broadcastSequence() {
+ // TODO: update currentIndex first if it's out of range as a result of
+ // removing items from the playlist.
+ _sequenceSubject.add(_audioSource?.sequence);
+ _updateShuffleIndices();
+ }
+
+ void _updateShuffleIndices() {
+ _shuffleIndicesSubject.add(_audioSource?.shuffleIndices);
+ final shuffleIndicesLength = shuffleIndices?.length ?? 0;
+ if (_shuffleIndicesInv.length > shuffleIndicesLength) {
+ _shuffleIndicesInv.removeRange(
+ shuffleIndicesLength, _shuffleIndicesInv.length);
+ } else if (_shuffleIndicesInv.length < shuffleIndicesLength) {
+ _shuffleIndicesInv.addAll(
+ List.filled(shuffleIndicesLength - _shuffleIndicesInv.length, 0));
+ }
+ for (var i = 0; i < shuffleIndicesLength; i++) {
+ _shuffleIndicesInv[shuffleIndices![i]] = i;
+ }
+ }
+
+ void _registerAudioSource(AudioSource source) {
+ _audioSources[source._id] = source;
+ }
+
+ Future<Duration?> _load(AudioPlayerPlatform platform, AudioSource source,
+ {_InitialSeekValues? initialSeekValues}) async {
+ final activationNumber = _activationCount;
+ void checkInterruption() {
+ if (_activationCount != activationNumber) {
+ // the platform has changed since we started loading, so abort.
+ throw PlatformException(code: 'abort', message: 'Loading interrupted');
+ }
+ }
+
+ try {
+ await source._setup(this);
+ checkInterruption();
+ source._shuffle(initialIndex: initialSeekValues?.index ?? 0);
+ _broadcastSequence();
+ _durationFuture = platform
+ .load(LoadRequest(
+ audioSourceMessage: source._toMessage(),
+ initialPosition: initialSeekValues?.position,
+ initialIndex: initialSeekValues?.index,
+ ))
+ .then((response) => response.duration);
+ final duration = await _durationFuture;
+ checkInterruption();
+ _durationSubject.add(duration);
+ if (platform != _platformValue) {
+ // the platform has changed since we started loading, so abort.
+ throw PlatformException(code: 'abort', message: 'Loading interrupted');
+ }
+ // Wait for loading state to pass.
+ await processingStateStream
+ .firstWhere((state) => state != ProcessingState.loading);
+ checkInterruption();
+ return duration;
+ } on PlatformException catch (e) {
+ try {
+ throw PlayerException(int.parse(e.code), e.message,
+ (e.details as Map<dynamic, dynamic>?)?.cast<String, dynamic>());
+ } on FormatException catch (_) {
+ if (e.code == 'abort') {
+ throw PlayerInterruptedException(e.message);
+ } else {
+ throw PlayerException(9999999, e.message);
+ }
+ }
+ }
+ }
+
+ /// Clips the current [AudioSource] to the given [start] and [end]
+ /// timestamps. If [start] is null, it will be reset to the start of the
+ /// original [AudioSource]. If [end] is null, it will be reset to the end of
+ /// the original [AudioSource]. This method cannot be called from the
+ /// [ProcessingState.idle] state.
+ Future<Duration?> setClip(
+ {Duration? start, Duration? end, dynamic tag}) async {
+ if (_disposed) return null;
+ _setPlatformActive(true)?.catchError((dynamic e) async => null);
+ final duration = await _load(
+ await _platform,
+ start == null && end == null
+ ? _audioSource!
+ : ClippingAudioSource(
+ child: _audioSource as UriAudioSource,
+ start: start,
+ end: end,
+ tag: tag,
+ ));
+ return duration;
+ }
+
+ /// Tells the player to play audio at the current [speed] and [volume] as soon
+ /// as an audio source is loaded and ready to play. If an audio source has
+ /// been set but not preloaded, this method will also initiate the loading.
+ /// The [Future] returned by this method completes when the playback completes
+ /// or is paused or stopped. If the player is already playing, this method
+ /// completes immediately.
+ ///
+ /// This method causes [playing] to become true, and it will remain true
+ /// until [pause] or [stop] is called. This means that if playback completes,
+ /// and then you [seek] to an earlier position in the audio, playback will
+ /// continue playing from that position. If you instead wish to [pause] or
+ /// [stop] playback on completion, you can call either method as soon as
+ /// [processingState] becomes [ProcessingState.completed] by listening to
+ /// [processingStateStream].
+ ///
+ /// This method activates the audio session before playback, and will do
+ /// nothing if activation of the audio session fails for any reason.
+ Future<void> play() async {
+ if (_disposed) return;
+ if (playing) return;
+ _playInterrupted = false;
+ // Broadcast to clients immediately, but revert to false if we fail to
+ // activate the audio session. This allows setAudioSource to be aware of a
+ // prior play request.
+ _playbackEvent = _playbackEvent.copyWith(
+ updatePosition: position,
+ updateTime: DateTime.now(),
+ );
+ _playingSubject.add(true);
+ _playbackEventSubject.add(_playbackEvent);
+ final playCompleter = Completer<dynamic>();
+ final audioSession = await AudioSession.instance;
+ if (!_handleAudioSessionActivation || await audioSession.setActive(true)) {
+ if (!playing) return;
+ // TODO: rewrite this to more cleanly handle simultaneous load/play
+ // requests which each may result in platform play requests.
+ final requireActive = _audioSource != null;
+ if (requireActive) {
+ if (_active) {
+ // If the native platform is already active, send it a play request.
+ // NOTE: If a load() request happens simultaneously, this may result
+ // in two play requests being sent. The platform implementation should
+ // ignore the second play request since it is already playing.
+ _sendPlayRequest(await _platform, playCompleter);
+ } else {
+ // If the native platform wasn't already active, activating it will
+ // implicitly restore the playing state and send a play request.
+ _setPlatformActive(true, playCompleter: playCompleter)
+ ?.catchError((dynamic e) async => null);
+ }
+ }
+ } else {
+ // Revert if we fail to activate the audio session.
+ _playingSubject.add(false);
+ }
+ await playCompleter.future;
+ }
+
+ /// Pauses the currently playing media. This method does nothing if
+ /// ![playing].
+ Future<void> pause() async {
+ if (_disposed) return;
+ if (!playing) return;
+ //_setPlatformActive(true);
+ _playInterrupted = false;
+ // Update local state immediately so that queries aren't surprised.
+ _playbackEvent = _playbackEvent.copyWith(
+ updatePosition: position,
+ updateTime: DateTime.now(),
+ );
+ _playingSubject.add(false);
+ _playbackEventSubject.add(_playbackEvent);
+ // TODO: perhaps modify platform side to ensure new state is broadcast
+ // before this method returns.
+ await (await _platform).pause(PauseRequest());
+ }
+
+ Future<void> _sendPlayRequest(
+ AudioPlayerPlatform platform, Completer<void>? playCompleter) async {
+ try {
+ if (!playing) return; // defensive
+ await platform.play(PlayRequest());
+ playCompleter?.complete();
+ } catch (e, stackTrace) {
+ playCompleter?.completeError(e, stackTrace);
+ }
+ }
+
+ /// Stops playing audio and releases decoders and other native platform
+ /// resources needed to play audio. The current audio source state will be
+ /// retained and playback can be resumed at a later point in time.
+ ///
+ /// Use [stop] if the app is done playing audio for now but may need still
+ /// want to resume playback later. Use [dispose] when the app is completely
+ /// finished playing audio. Use [pause] instead if you would like to keep the
+ /// decoders alive so that the app can quickly resume audio playback.
+ Future<void> stop() async {
+ if (_disposed) return;
+ final future =
+ _setPlatformActive(false)?.catchError((dynamic e) async => null);
+
+ _playInterrupted = false;
+ // Update local state immediately so that queries aren't surprised.
+ _playingSubject.add(false);
+ await future;
+ }
+
+ /// Sets the volume of this player, where 1.0 is normal volume.
+ Future<void> setVolume(final double volume) async {
+ if (_disposed) return;
+ _volumeSubject.add(volume);
+ await (await _platform).setVolume(SetVolumeRequest(volume: volume));
+ }
+
+ /// Sets whether silence should be skipped in audio playback. (Currently
+ /// Android only).
+ Future<void> setSkipSilenceEnabled(bool enabled) async {
+ if (_disposed) return;
+ final previouslyEnabled = skipSilenceEnabled;
+ if (enabled == previouslyEnabled) return;
+ _skipSilenceEnabledSubject.add(enabled);
+ try {
+ await (await _platform)
+ .setSkipSilence(SetSkipSilenceRequest(enabled: enabled));
+ } catch (e) {
+ _skipSilenceEnabledSubject.add(previouslyEnabled);
+ rethrow;
+ }
+ }
+
+ /// Sets the playback speed to use when [playing] is `true`, where 1.0 is
+ /// normal speed. Note that values in excess of 1.0 may result in stalls if
+ /// the playback speed is faster than the player is able to downloaded the
+ /// audio.
+ Future<void> setSpeed(final double speed) async {
+ if (_disposed) return;
+ _playbackEvent = _playbackEvent.copyWith(
+ updatePosition: position,
+ updateTime: DateTime.now(),
+ );
+ _playbackEventSubject.add(_playbackEvent);
+ _speedSubject.add(speed);
+ await (await _platform).setSpeed(SetSpeedRequest(speed: speed));
+ }
+
+ /// Sets the factor by which pitch will be shifted.
+ Future<void> setPitch(final double pitch) async {
+ if (_disposed) return;
+ _playbackEvent = _playbackEvent.copyWith(
+ updatePosition: position,
+ updateTime: DateTime.now(),
+ );
+ _playbackEventSubject.add(_playbackEvent);
+ _pitchSubject.add(pitch);
+ await (await _platform).setPitch(SetPitchRequest(pitch: pitch));
+ }
+
+ /// Sets the [LoopMode]. Looping will be gapless on Android, iOS and macOS. On
+ /// web, there will be a slight gap at the loop point.
+ Future<void> setLoopMode(LoopMode mode) async {
+ if (_disposed) return;
+ _loopModeSubject.add(mode);
+ await (await _platform).setLoopMode(
+ SetLoopModeRequest(loopMode: LoopModeMessage.values[mode.index]));
+ }
+
+ /// Sets whether shuffle mode is enabled.
+ Future<void> setShuffleModeEnabled(bool enabled) async {
+ if (_disposed) return;
+ _shuffleModeEnabledSubject.add(enabled);
+ await (await _platform).setShuffleMode(SetShuffleModeRequest(
+ shuffleMode:
+ enabled ? ShuffleModeMessage.all : ShuffleModeMessage.none));
+ }
+
+ /// Recursively shuffles the children of the currently loaded [AudioSource].
+ /// Each [ConcatenatingAudioSource] will be shuffled according to its
+ /// configured [ShuffleOrder].
+ Future<void> shuffle() async {
+ if (_disposed) return;
+ if (_audioSource == null) return;
+ _audioSource!._shuffle(initialIndex: currentIndex);
+ _updateShuffleIndices();
+ await (await _platform).setShuffleOrder(
+ SetShuffleOrderRequest(audioSourceMessage: _audioSource!._toMessage()));
+ }
+
+ /// Sets automaticallyWaitsToMinimizeStalling for AVPlayer in iOS 10.0 or later, defaults to true.
+ /// Has no effect on Android clients
+ Future<void> setAutomaticallyWaitsToMinimizeStalling(
+ final bool automaticallyWaitsToMinimizeStalling) async {
+ if (_disposed) return;
+ _automaticallyWaitsToMinimizeStalling =
+ automaticallyWaitsToMinimizeStalling;
+ await (await _platform).setAutomaticallyWaitsToMinimizeStalling(
+ SetAutomaticallyWaitsToMinimizeStallingRequest(
+ enabled: automaticallyWaitsToMinimizeStalling));
+ }
+
+ /// Sets canUseNetworkResourcesForLiveStreamingWhilePaused on iOS/macOS,
+ /// defaults to false.
+ Future<void> setCanUseNetworkResourcesForLiveStreamingWhilePaused(
+ final bool canUseNetworkResourcesForLiveStreamingWhilePaused) async {
+ if (_disposed) return;
+ _canUseNetworkResourcesForLiveStreamingWhilePaused =
+ canUseNetworkResourcesForLiveStreamingWhilePaused;
+ await (await _platform)
+ .setCanUseNetworkResourcesForLiveStreamingWhilePaused(
+ SetCanUseNetworkResourcesForLiveStreamingWhilePausedRequest(
+ enabled: canUseNetworkResourcesForLiveStreamingWhilePaused));
+ }
+
+ /// Sets preferredPeakBitRate on iOS/macOS, defaults to true.
+ Future<void> setPreferredPeakBitRate(
+ final double preferredPeakBitRate) async {
+ if (_disposed) return;
+ _preferredPeakBitRate = preferredPeakBitRate;
+ await (await _platform).setPreferredPeakBitRate(
+ SetPreferredPeakBitRateRequest(bitRate: preferredPeakBitRate));
+ }
+
+ /// Sets allowsExternalPlayback on iOS/macOS, defaults to false.
+ Future<void> setAllowsExternalPlayback(
+ final bool allowsExternalPlayback) async {
+ if (_disposed) return;
+ _allowsExternalPlayback = allowsExternalPlayback;
+ await (await _platform).setAllowsExternalPlayback(
+ SetAllowsExternalPlaybackRequest(
+ allowsExternalPlayback: allowsExternalPlayback));
+ }
+
+ /// Seeks to a particular [position]. If a composition of multiple
+ /// [AudioSource]s has been loaded, you may also specify [index] to seek to a
+ /// particular item within that sequence. This method has no effect unless
+ /// an audio source has been loaded.
+ ///
+ /// A `null` [position] seeks to the head of a live stream.
+ Future<void> seek(final Duration? position, {int? index}) async {
+ if (_disposed) return;
+ _initialSeekValues = null;
+ switch (processingState) {
+ case ProcessingState.loading:
+ return;
+ default:
+ try {
+ _seeking = true;
+ final prevPlaybackEvent = _playbackEvent;
+ _playbackEvent = prevPlaybackEvent.copyWith(
+ updatePosition: position,
+ updateTime: DateTime.now(),
+ );
+ _playbackEventSubject.add(_playbackEvent);
+ _positionDiscontinuitySubject.add(PositionDiscontinuity(
+ PositionDiscontinuityReason.seek,
+ prevPlaybackEvent,
+ _playbackEvent));
+ await (await _platform)
+ .seek(SeekRequest(position: position, index: index));
+ } finally {
+ _seeking = false;
+ }
+ }
+ }
+
+ /// Seek to the next item, or does nothing if there is no next item.
+ Future<void> seekToNext() async {
+ if (hasNext) {
+ await seek(Duration.zero, index: nextIndex);
+ }
+ }
+
+ /// Seek to the previous item, or does nothing if there is no previous item.
+ Future<void> seekToPrevious() async {
+ if (hasPrevious) {
+ await seek(Duration.zero, index: previousIndex);
+ }
+ }
+
+ /// Set the Android audio attributes for this player. Has no effect on other
+ /// platforms. This will cause a new Android AudioSession ID to be generated.
+ Future<void> setAndroidAudioAttributes(
+ AndroidAudioAttributes audioAttributes) async {
+ if (_disposed) return;
+ if (!_isAndroid() && !_isUnitTest()) return;
+ if (audioAttributes == _androidAudioAttributes) return;
+ _androidAudioAttributes = audioAttributes;
+ await _internalSetAndroidAudioAttributes(await _platform, audioAttributes);
+ }
+
+ Future<void> _internalSetAndroidAudioAttributes(AudioPlayerPlatform platform,
+ AndroidAudioAttributes audioAttributes) async {
+ if (!_isAndroid() && !_isUnitTest()) return;
+ await platform.setAndroidAudioAttributes(SetAndroidAudioAttributesRequest(
+ contentType: audioAttributes.contentType.index,
+ flags: audioAttributes.flags.value,
+ usage: audioAttributes.usage.value));
+ }
+
+ /// Set the `crossorigin` attribute on the `<audio>` element backing this
+ /// player instance on web (see
+ /// [HTMLMediaElement crossorigin](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/crossOrigin) ).
+ ///
+ /// If [webCrossOrigin] is null (the initial state), the URL will be fetched
+ /// without CORS. If it is `useCredentials`, a CORS request will be made
+ /// exchanging credentials (via cookies/certificates/HTTP authentication)
+ /// regardless of the origin. If it is 'anonymous', a CORS request will be
+ /// made, but credentials are exchanged only if the URL is fetched from the
+ /// same origin.
+ Future<void> setWebCrossOrigin(WebCrossOrigin? webCrossOrigin) async {
+ if (_disposed) return;
+ if (!kIsWeb && !_isUnitTest()) return;
+
+ await (await _platform).setWebCrossOrigin(
+ SetWebCrossOriginRequest(
+ crossOrigin: webCrossOrigin == null
+ ? null
+ : WebCrossOriginMessage.values[webCrossOrigin.index]),
+ );
+ _webCrossOrigin = webCrossOrigin;
+ }
+
+ /// Sets a specific device output id on Web.
+ Future<void> setWebSinkId(String webSinkId) async {
+ if (_disposed) return;
+ if (!kIsWeb && !_isUnitTest()) return;
+
+ await (await _platform)
+ .setWebSinkId(SetWebSinkIdRequest(sinkId: webSinkId));
+ _webSinkId = webSinkId;
+ }
+
+ /// Release all resources associated with this player. You must invoke this
+ /// after you are done with the player.
+ Future<void> dispose() async {
+ if (_disposed) return;
+ _disposed = true;
+ if (_nativePlatform != null) {
+ await _disposePlatform(await _nativePlatform!);
+ _nativePlatform = null;
+ }
+ if (_idlePlatform != null) {
+ await _disposePlatform(_idlePlatform!);
+ _idlePlatform = null;
+ }
+ _audioSource = null;
+ for (var s in _audioSources.values) {
+ s._dispose();
+ }
+ _audioSources.clear();
+ _proxy.stop();
+ await _durationSubject.close();
+ await _loopModeSubject.close();
+ await _shuffleModeEnabledSubject.close();
+ await _playingSubject.close();
+ await _volumeSubject.close();
+ await _speedSubject.close();
+ await _pitchSubject.close();
+ await _sequenceSubject.close();
+ await _shuffleIndicesSubject.close();
+ await _androidAudioAttributesSubscription?.cancel();
+ await _becomingNoisyEventSubscription?.cancel();
+ await _interruptionEventSubscription?.cancel();
+ }
+
+ /// Switch to using the native platform when [active] is `true` and using the
+ /// idle platform when [active] is `false`. If an audio source has been set,
+ /// the returned future completes with its duration if known, or `null`
+ /// otherwise.
+ ///
+ /// The platform will not switch if [active] == [_active] unless [force] is
+ /// `true`.
+ Future<Duration?>? _setPlatformActive(bool active,
+ {Completer<void>? playCompleter, bool force = false}) {
+ if (_disposed) return null;
+ if (!force && (active == _active)) return _durationFuture;
+ _platformLoading = active;
+
+ // Warning! Tricky async code lies ahead.
+ // (This should definitely be made less tricky)
+ // This method itself is not asynchronous, and guarantees that _platform
+ // will be set in this cycle to a Future. The platform returned by that
+ // future takes time to initialise and so we need to handle the case where
+ // that initialisation was interrupted by another call to
+ // _setPlatformActive.
+
+ // Store the current activation sequence number. activationNumber should
+ // equal _activationCount for the duration of this call, unless it is
+ // interrupted by another simultaneous call.
+ final activationNumber = ++_activationCount;
+
+ /// Tells whether we've been interrupted.
+ bool wasInterrupted() => _activationCount != activationNumber;
+
+ final durationCompleter = Completer<Duration?>();
+
+ // Checks if we were interrupted and aborts the current activation. If we
+ // are interrupted, there are two cases:
+ // 1. If we were activating the native platform, abort with an exception.
+ // 2. If we were activating the idle dummy, abort silently.
+ //
+ // We should call this after each awaited call since those are opportunities
+ // for other coroutines to run and interrupt this one.
+ bool checkInterruption() {
+ // No interruption.
+ if (!wasInterrupted()) return false;
+ // An interruption that we can ignore
+ if (!active) return true;
+ // An interruption that should throw
+ final e =
+ PlatformException(code: 'abort', message: 'Loading interrupted');
+ durationCompleter.completeError(e);
+ throw e;
+ }
+
+ // This method updates _active and _platform before yielding to the next
+ // task in the event loop.
+ _active = active;
+ final position = this.position;
+ final currentIndex = this.currentIndex;
+ final audioSource = _audioSource;
+
+ void subscribeToEvents(AudioPlayerPlatform platform) {
+ _playerDataSubscription =
+ platform.playerDataMessageStream.listen((message) {
+ if (message.playing != null && message.playing != playing) {
+ _playingSubject.add(message.playing!);
+ }
+ if (message.volume != null) {
+ _volumeSubject.add(message.volume!);
+ }
+ if (message.speed != null) {
+ _speedSubject.add(message.speed!);
+ }
+ if (message.pitch != null) {
+ _pitchSubject.add(message.pitch!);
+ }
+ if (message.loopMode != null) {
+ _loopModeSubject.add(LoopMode.values[message.loopMode!.index]);
+ }
+ if (message.shuffleMode != null) {
+ _shuffleModeEnabledSubject
+ .add(message.shuffleMode != ShuffleModeMessage.none);
+ }
+ });
+ _playbackEventSubscription =
+ platform.playbackEventMessageStream.listen((message) {
+ var duration = message.duration;
+ var index = message.currentIndex ?? currentIndex;
+ if (index != null && sequence != null && index < sequence!.length) {
+ if (duration == null) {
+ duration = sequence![index].duration;
+ } else {
+ sequence![index].duration = duration;
+ }
+ }
+ if (_platformLoading &&
+ message.processingState != ProcessingStateMessage.idle) {
+ _platformLoading = false;
+ }
+ final playbackEvent = PlaybackEvent(
+ // The platform may emit an idle state while it's starting up which we
+ // override here.
+ processingState: _platformLoading
+ ? ProcessingState.loading
+ : ProcessingState.values[message.processingState.index],
+ updateTime: message.updateTime,
+ updatePosition: message.updatePosition,
+ bufferedPosition: message.bufferedPosition,
+ duration: duration,
+ icyMetadata: message.icyMetadata == null
+ ? null
+ : IcyMetadata._fromMessage(message.icyMetadata!),
+ currentIndex: index,
+ androidAudioSessionId: message.androidAudioSessionId,
+ );
+ _durationFuture = Future.value(playbackEvent.duration);
+ if (playbackEvent == _playbackEvent) {
+ return;
+ }
+ if (playbackEvent.duration != _playbackEvent.duration) {
+ _durationSubject.add(playbackEvent.duration);
+ }
+ final oldPlaybackEvent = _playbackEvent;
+ _playbackEventSubject.add(_playbackEvent = playbackEvent);
+ if (_playbackEvent.processingState !=
+ oldPlaybackEvent.processingState &&
+ _playbackEvent.processingState == ProcessingState.idle) {
+ _setPlatformActive(false)?.catchError((dynamic e) async => null);
+ }
+ }, onError: _playbackEventSubject.addError);
+ }
+
+ Future<AudioPlayerPlatform> setPlatform() async {
+ _playbackEventSubscription?.cancel();
+ _playerDataSubscription?.cancel();
+ if (!force) {
+ final oldPlatform = _platformValue!;
+ if (oldPlatform is! _IdleAudioPlayer) {
+ await _disposePlatform(oldPlatform);
+ }
+ }
+ if (_disposed) return _platform;
+ // During initialisation, we must only use this platform reference in case
+ // _platform is updated again during initialisation.
+ final platform = active
+ ? await (_nativePlatform = _pluginPlatform.init(InitRequest(
+ id: _id,
+ audioLoadConfiguration: _audioLoadConfiguration?._toMessage(),
+ androidAudioEffects: (_isAndroid() || _isUnitTest())
+ ? _audioPipeline.androidAudioEffects
+ .map((audioEffect) => audioEffect._toMessage())
+ .toList()
+ : [],
+ darwinAudioEffects: (_isDarwin() || _isUnitTest())
+ ? _audioPipeline.darwinAudioEffects
+ .map((audioEffect) => audioEffect._toMessage())
+ .toList()
+ : [],
+ androidOffloadSchedulingEnabled: _androidOffloadSchedulingEnabled,
+ )))
+ : (_idlePlatform =
+ _IdleAudioPlayer(id: _id, sequenceStream: sequenceStream));
+ if (checkInterruption()) return platform;
+
+ _platformValue = platform;
+
+ if (active) {
+ if (audioSource != null) {
+ _playbackEventSubject.add(_playbackEvent = _playbackEvent.copyWith(
+ updatePosition: position,
+ processingState: ProcessingState.loading,
+ ));
+ }
+
+ final automaticallyWaitsToMinimizeStalling =
+ this.automaticallyWaitsToMinimizeStalling;
+ final playing = this.playing;
+ // To avoid a glitch in ExoPlayer, ensure that any requested audio
+ // attributes are set before loading the audio source.
+ if (_isAndroid() || _isUnitTest()) {
+ if (_androidApplyAudioAttributes) {
+ final audioSession = await AudioSession.instance;
+ if (checkInterruption()) return platform;
+ _androidAudioAttributes ??=
+ audioSession.configuration?.androidAudioAttributes;
+ }
+ if (_androidAudioAttributes != null) {
+ await _internalSetAndroidAudioAttributes(
+ platform, _androidAudioAttributes!);
+ if (checkInterruption()) return platform;
+ }
+ }
+ if (!automaticallyWaitsToMinimizeStalling) {
+ // Only set if different from default.
+ await platform.setAutomaticallyWaitsToMinimizeStalling(
+ SetAutomaticallyWaitsToMinimizeStallingRequest(
+ enabled: automaticallyWaitsToMinimizeStalling));
+ if (checkInterruption()) return platform;
+ }
+ await platform.setVolume(SetVolumeRequest(volume: volume));
+ if (checkInterruption()) return platform;
+ await platform.setSpeed(SetSpeedRequest(speed: speed));
+ if (checkInterruption()) return platform;
+ try {
+ await platform.setPitch(SetPitchRequest(pitch: pitch));
+ } catch (e) {
+ // setPitch not supported on this platform.
+ }
+ if (checkInterruption()) return platform;
+ try {
+ await platform.setSkipSilence(
+ SetSkipSilenceRequest(enabled: skipSilenceEnabled));
+ } catch (e) {
+ // setSkipSilence not supported on this platform.
+ }
+ if (checkInterruption()) return platform;
+ await platform.setLoopMode(SetLoopModeRequest(
+ loopMode: LoopModeMessage.values[loopMode.index]));
+ if (checkInterruption()) return platform;
+ await platform.setShuffleMode(SetShuffleModeRequest(
+ shuffleMode: shuffleModeEnabled
+ ? ShuffleModeMessage.all
+ : ShuffleModeMessage.none));
+ if (checkInterruption()) return platform;
+ if (kIsWeb) {
+ if (_webCrossOrigin != null) {
+ await platform.setWebCrossOrigin(SetWebCrossOriginRequest(
+ crossOrigin: WebCrossOriginMessage.values[_webCrossOrigin!.index],
+ ));
+ }
+ if (_webSinkId != '') {
+ await platform.setWebSinkId(SetWebSinkIdRequest(
+ sinkId: _webSinkId,
+ ));
+ }
+ }
+ for (var audioEffect in _audioPipeline._audioEffects) {
+ await audioEffect._activate(platform);
+ if (checkInterruption()) return platform;
+ }
+ if (playing) {
+ _sendPlayRequest(platform, playCompleter);
+ }
+ }
+
+ subscribeToEvents(platform);
+
+ if (audioSource != null) {
+ try {
+ final initialSeekValues = _initialSeekValues ??
+ _InitialSeekValues(position: position, index: currentIndex);
+ _initialSeekValues = null;
+ final duration = await _load(platform, _audioSource!,
+ initialSeekValues: initialSeekValues);
+ if (checkInterruption()) return platform;
+ durationCompleter.complete(duration);
+ } catch (e, stackTrace) {
+ await _setPlatformActive(false)
+ ?.catchError((dynamic e) async => null);
+ durationCompleter.completeError(e, stackTrace);
+ }
+ } else {
+ durationCompleter.complete(null);
+ }
+
+ return platform;
+ }
+
+ _platform = setPlatform();
+ return durationCompleter.future;
+ }
+
+ /// Dispose of the given platform.
+ Future<void> _disposePlatform(AudioPlayerPlatform platform) async {
+ if (platform is _IdleAudioPlayer) {
+ await platform.dispose(DisposeRequest());
+ } else {
+ _nativePlatform = null;
+ try {
+ await _pluginPlatform.disposePlayer(DisposePlayerRequest(id: _id));
+ } catch (e) {
+ // Fallback if disposePlayer hasn't been implemented.
+ await platform.dispose(DisposeRequest());
+ }
+ }
+ }
+
+ /// Clears the plugin's internal asset cache directory. Call this when the
+ /// app's assets have changed to force assets to be re-fetched from the asset
+ /// bundle.
+ static Future<void> clearAssetCache() async {
+ if (kIsWeb) return;
+ await for (var file in (await _getCacheDir()).list()) {
+ await file.delete(recursive: true);
+ }
+ }
+}
+
+/// Captures the details of any error accessing, loading or playing an audio
+/// source, including an invalid or inaccessible URL, or an audio encoding that
+/// could not be understood.
+class PlayerException implements Exception {
+ /// On iOS and macOS, maps to `NSError.code`. On Android, maps to
+ /// `ExoPlaybackException.type`. On Web, maps to `MediaError.code`.
+ final int code;
+
+ /// On iOS and macOS, maps to `NSError.localizedDescription`. On Android,
+ /// maps to `ExoPlaybackException.getMessage()`. On Web, a generic message
+ /// is provided.
+ final String? message;
+
+ /// On Android/iOS/macOS, contains details of the error. For errors associated
+ /// with a particular audio source, the `"index"` key maps to the index of the
+ /// audio source in the sequence.
+ final Map<String, dynamic> details;
+
+ PlayerException(this.code, this.message, [Map<String, dynamic>? details])
+ : details = details ?? <String, dynamic>{};
+
+ @override
+ String toString() => "($code) $message";
+}
+
+/// An error that occurs when one operation on the player has been interrupted
+/// (e.g. by another simultaneous operation).
+class PlayerInterruptedException implements Exception {
+ final String? message;
+
+ PlayerInterruptedException(this.message);
+
+ @override
+ String toString() => "$message";
+}
+
+/// Encapsulates the playback state and current position of the player.
+class PlaybackEvent {
+ /// The current processing state.
+ final ProcessingState processingState;
+
+ /// When the last time a position discontinuity happened, as measured in time
+ /// since the epoch.
+ final DateTime updateTime;
+
+ /// The position at [updateTime].
+ final Duration updatePosition;
+
+ /// The buffer position.
+ final Duration bufferedPosition;
+
+ /// The media duration, or `null` if unknown.
+ final Duration? duration;
+
+ /// The latest ICY metadata received through the audio stream if available.
+ final IcyMetadata? icyMetadata;
+
+ /// The index of the currently playing item, or `null` if no item is selected.
+ final int? currentIndex;
+
+ /// The current Android AudioSession ID if set.
+ final int? androidAudioSessionId;
+
+ PlaybackEvent({
+ this.processingState = ProcessingState.idle,
+ DateTime? updateTime,
+ this.updatePosition = Duration.zero,
+ this.bufferedPosition = Duration.zero,
+ this.duration,
+ this.icyMetadata,
+ this.currentIndex,
+ this.androidAudioSessionId,
+ }) : updateTime = updateTime ?? DateTime.now();
+
+ /// Returns a copy of this event with given properties replaced.
+ PlaybackEvent copyWith({
+ ProcessingState? processingState,
+ DateTime? updateTime,
+ Duration? updatePosition,
+ Duration? bufferedPosition,
+ Duration? duration,
+ IcyMetadata? icyMetadata,
+ int? currentIndex,
+ int? androidAudioSessionId,
+ }) =>
+ PlaybackEvent(
+ processingState: processingState ?? this.processingState,
+ updateTime: updateTime ?? this.updateTime,
+ updatePosition: updatePosition ?? this.updatePosition,
+ bufferedPosition: bufferedPosition ?? this.bufferedPosition,
+ duration: duration ?? this.duration,
+ icyMetadata: icyMetadata ?? this.icyMetadata,
+ currentIndex: currentIndex ?? this.currentIndex,
+ androidAudioSessionId:
+ androidAudioSessionId ?? this.androidAudioSessionId,
+ );
+
+ @override
+ int get hashCode => Object.hash(
+ processingState,
+ updateTime,
+ updatePosition,
+ bufferedPosition,
+ duration,
+ icyMetadata,
+ currentIndex,
+ androidAudioSessionId,
+ );
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is PlaybackEvent &&
+ processingState == other.processingState &&
+ updateTime == other.updateTime &&
+ updatePosition == other.updatePosition &&
+ bufferedPosition == other.bufferedPosition &&
+ duration == other.duration &&
+ icyMetadata == other.icyMetadata &&
+ currentIndex == other.currentIndex &&
+ androidAudioSessionId == other.androidAudioSessionId;
+
+ @override
+ String toString() =>
+ "{processingState=$processingState, updateTime=$updateTime, updatePosition=$updatePosition, bufferedPosition=$bufferedPosition, duration=$duration, currentIndex=$currentIndex}";
+}
+
+/// Enumerates the different processing states of a player.
+enum ProcessingState {
+ /// The player has not loaded an [AudioSource].
+ idle,
+
+ /// The player is loading an [AudioSource].
+ loading,
+
+ /// The player is buffering audio and unable to play.
+ buffering,
+
+ /// The player is has enough audio buffered and is able to play.
+ ready,
+
+ /// The player has reached the end of the audio.
+ completed,
+}
+
+/// Encapsulates the playing and processing states. These two states vary
+/// orthogonally, and so if [processingState] is [ProcessingState.buffering],
+/// you can check [playing] to determine whether the buffering occurred while
+/// the player was playing or while the player was paused.
+class PlayerState {
+ /// Whether the player will play when [processingState] is
+ /// [ProcessingState.ready].
+ final bool playing;
+
+ /// The current processing state of the player.
+ final ProcessingState processingState;
+
+ PlayerState(this.playing, this.processingState);
+
+ @override
+ String toString() => 'playing=$playing,processingState=$processingState';
+
+ @override
+ int get hashCode => Object.hash(playing, processingState);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is PlayerState &&
+ other.playing == playing &&
+ other.processingState == processingState;
+}
+
+class IcyInfo {
+ final String? title;
+ final String? url;
+
+ static IcyInfo _fromMessage(IcyInfoMessage message) => IcyInfo(
+ title: message.title,
+ url: message.url,
+ );
+
+ IcyInfo({required this.title, required this.url});
+
+ @override
+ String toString() => 'title=$title,url=$url';
+
+ @override
+ int get hashCode => Object.hash(title, url);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is IcyInfo &&
+ other.title == title &&
+ other.url == url;
+}
+
+class IcyHeaders {
+ final int? bitrate;
+ final String? genre;
+ final String? name;
+ final int? metadataInterval;
+ final String? url;
+ final bool? isPublic;
+
+ static IcyHeaders _fromMessage(IcyHeadersMessage message) => IcyHeaders(
+ bitrate: message.bitrate,
+ genre: message.genre,
+ name: message.name,
+ metadataInterval: message.metadataInterval,
+ url: message.url,
+ isPublic: message.isPublic,
+ );
+
+ IcyHeaders({
+ required this.bitrate,
+ required this.genre,
+ required this.name,
+ required this.metadataInterval,
+ required this.url,
+ required this.isPublic,
+ });
+
+ @override
+ String toString() =>
+ 'bitrate=$bitrate,genre=$genre,name=$name,metadataInterval=$metadataInterval,url=$url,isPublic=$isPublic';
+
+ @override
+ int get hashCode => toString().hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is IcyHeaders &&
+ other.bitrate == bitrate &&
+ other.genre == genre &&
+ other.name == name &&
+ other.metadataInterval == metadataInterval &&
+ other.url == url &&
+ other.isPublic == isPublic;
+}
+
+class IcyMetadata {
+ final IcyInfo? info;
+ final IcyHeaders? headers;
+
+ static IcyMetadata _fromMessage(IcyMetadataMessage message) => IcyMetadata(
+ info: message.info == null ? null : IcyInfo._fromMessage(message.info!),
+ headers: message.headers == null
+ ? null
+ : IcyHeaders._fromMessage(message.headers!),
+ );
+
+ IcyMetadata({required this.info, required this.headers});
+
+ @override
+ int get hashCode => Object.hash(info, headers);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is IcyMetadata &&
+ other.info == info &&
+ other.headers == headers;
+}
+
+/// Encapsulates the [sequence] and [currentIndex] state and ensures
+/// consistency such that [currentIndex] is within the range of
+/// `sequence.length`. If `sequence.length` is 0, then [currentIndex] is also
+/// 0.
+class SequenceState {
+ /// The sequence of the current [AudioSource].
+ final List<IndexedAudioSource> sequence;
+
+ /// The index of the current source in the sequence.
+ final int currentIndex;
+
+ /// The current shuffle order
+ final List<int> shuffleIndices;
+
+ /// Whether shuffle mode is enabled.
+ final bool shuffleModeEnabled;
+
+ /// The current loop mode.
+ final LoopMode loopMode;
+
+ SequenceState(this.sequence, this.currentIndex, this.shuffleIndices,
+ this.shuffleModeEnabled, this.loopMode);
+
+ /// The current source in the sequence.
+ IndexedAudioSource? get currentSource =>
+ sequence.isEmpty ? null : sequence[currentIndex];
+
+ /// The effective sequence. This is equivalent to [sequence]. If
+ /// [shuffleModeEnabled] is true, this is modulated by [shuffleIndices].
+ List<IndexedAudioSource> get effectiveSequence => shuffleModeEnabled
+ ? shuffleIndices.map((i) => sequence[i]).toList()
+ : sequence;
+}
+
+/// Configuration options to use when loading audio from a source.
+class AudioLoadConfiguration {
+ /// Bufferring and loading options for iOS/macOS.
+ final DarwinLoadControl? darwinLoadControl;
+
+ /// Buffering and loading options for Android.
+ final AndroidLoadControl? androidLoadControl;
+
+ /// Speed control for live streams on Android.
+ final AndroidLivePlaybackSpeedControl? androidLivePlaybackSpeedControl;
+
+ const AudioLoadConfiguration({
+ this.darwinLoadControl,
+ this.androidLoadControl,
+ this.androidLivePlaybackSpeedControl,
+ });
+
+ AudioLoadConfigurationMessage _toMessage() => AudioLoadConfigurationMessage(
+ darwinLoadControl: darwinLoadControl?._toMessage(),
+ androidLoadControl: androidLoadControl?._toMessage(),
+ androidLivePlaybackSpeedControl:
+ androidLivePlaybackSpeedControl?._toMessage(),
+ );
+}
+
+/// Buffering and loading options for iOS/macOS.
+class DarwinLoadControl {
+ /// (iOS/macOS) Whether the player will wait for sufficient data to be
+ /// buffered before starting playback to avoid the likelihood of stalling.
+ final bool automaticallyWaitsToMinimizeStalling;
+
+ /// (iOS/macOS) The duration of audio that should be buffered ahead of the
+ /// current position. If not set or `null`, the system will try to set an
+ /// appropriate buffer duration.
+ final Duration? preferredForwardBufferDuration;
+
+ /// (iOS/macOS) Whether the player can continue downloading while paused to
+ /// keep the state up to date with the live stream.
+ final bool canUseNetworkResourcesForLiveStreamingWhilePaused;
+
+ /// (iOS/macOS) If specified, limits the download bandwidth in bits per
+ /// second.
+ final double? preferredPeakBitRate;
+
+ const DarwinLoadControl({
+ this.automaticallyWaitsToMinimizeStalling = true,
+ this.preferredForwardBufferDuration,
+ this.canUseNetworkResourcesForLiveStreamingWhilePaused = false,
+ this.preferredPeakBitRate,
+ });
+
+ DarwinLoadControlMessage _toMessage() => DarwinLoadControlMessage(
+ automaticallyWaitsToMinimizeStalling:
+ automaticallyWaitsToMinimizeStalling,
+ preferredForwardBufferDuration: preferredForwardBufferDuration,
+ canUseNetworkResourcesForLiveStreamingWhilePaused:
+ canUseNetworkResourcesForLiveStreamingWhilePaused,
+ preferredPeakBitRate: preferredPeakBitRate,
+ );
+}
+
+/// Buffering and loading options for Android.
+class AndroidLoadControl {
+ /// (Android) The minimum duration of audio that should be buffered ahead of
+ /// the current position.
+ final Duration minBufferDuration;
+
+ /// (Android) The maximum duration of audio that should be buffered ahead of
+ /// the current position.
+ final Duration maxBufferDuration;
+
+ /// (Android) The duration of audio that must be buffered before starting
+ /// playback after a user action.
+ final Duration bufferForPlaybackDuration;
+
+ /// (Android) The duration of audio that must be buffered before starting
+ /// playback after a buffer depletion.
+ final Duration bufferForPlaybackAfterRebufferDuration;
+
+ /// (Android) The target buffer size in bytes.
+ final int? targetBufferBytes;
+
+ /// (Android) Whether to prioritize buffer time constraints over buffer size
+ /// constraints.
+ final bool prioritizeTimeOverSizeThresholds;
+
+ /// (Android) The back buffer duration.
+ final Duration backBufferDuration;
+
+ const AndroidLoadControl({
+ this.minBufferDuration = const Duration(seconds: 50),
+ this.maxBufferDuration = const Duration(seconds: 50),
+ this.bufferForPlaybackDuration = const Duration(milliseconds: 2500),
+ this.bufferForPlaybackAfterRebufferDuration = const Duration(seconds: 5),
+ this.targetBufferBytes,
+ this.prioritizeTimeOverSizeThresholds = false,
+ this.backBufferDuration = Duration.zero,
+ });
+
+ AndroidLoadControlMessage _toMessage() => AndroidLoadControlMessage(
+ minBufferDuration: minBufferDuration,
+ maxBufferDuration: maxBufferDuration,
+ bufferForPlaybackDuration: bufferForPlaybackDuration,
+ bufferForPlaybackAfterRebufferDuration:
+ bufferForPlaybackAfterRebufferDuration,
+ targetBufferBytes: targetBufferBytes,
+ prioritizeTimeOverSizeThresholds: prioritizeTimeOverSizeThresholds,
+ backBufferDuration: backBufferDuration,
+ );
+}
+
+/// Speed control for live streams on Android.
+class AndroidLivePlaybackSpeedControl {
+ /// (Android) The minimum playback speed to use when adjusting playback speed
+ /// to approach the target live offset, if none is defined by the media.
+ final double fallbackMinPlaybackSpeed;
+
+ /// (Android) The maximum playback speed to use when adjusting playback speed
+ /// to approach the target live offset, if none is defined by the media.
+ final double fallbackMaxPlaybackSpeed;
+
+ /// (Android) The minimum interval between playback speed changes on a live
+ /// stream.
+ final Duration minUpdateInterval;
+
+ /// (Android) The proportional control factor used to adjust playback speed on
+ /// a live stream. The adjusted speed is calculated as: `1.0 +
+ /// proportionalControlFactor * (currentLiveOffsetSec - targetLiveOffsetSec)`.
+ final double proportionalControlFactor;
+
+ /// (Android) The maximum difference between the current live offset and the
+ /// target live offset within which the speed 1.0 is used.
+ final Duration maxLiveOffsetErrorForUnitSpeed;
+
+ /// (Android) The increment applied to the target live offset whenever the
+ /// player rebuffers.
+ final Duration targetLiveOffsetIncrementOnRebuffer;
+
+ /// (Android) The factor for smoothing the minimum possible live offset
+ /// achievable during playback.
+ final double minPossibleLiveOffsetSmoothingFactor;
+
+ const AndroidLivePlaybackSpeedControl({
+ this.fallbackMinPlaybackSpeed = 0.97,
+ this.fallbackMaxPlaybackSpeed = 1.03,
+ this.minUpdateInterval = const Duration(seconds: 1),
+ this.proportionalControlFactor = 1.0,
+ this.maxLiveOffsetErrorForUnitSpeed = const Duration(milliseconds: 20),
+ this.targetLiveOffsetIncrementOnRebuffer =
+ const Duration(milliseconds: 500),
+ this.minPossibleLiveOffsetSmoothingFactor = 0.999,
+ });
+
+ AndroidLivePlaybackSpeedControlMessage _toMessage() =>
+ AndroidLivePlaybackSpeedControlMessage(
+ fallbackMinPlaybackSpeed: fallbackMinPlaybackSpeed,
+ fallbackMaxPlaybackSpeed: fallbackMaxPlaybackSpeed,
+ minUpdateInterval: minUpdateInterval,
+ proportionalControlFactor: proportionalControlFactor,
+ maxLiveOffsetErrorForUnitSpeed: maxLiveOffsetErrorForUnitSpeed,
+ targetLiveOffsetIncrementOnRebuffer:
+ targetLiveOffsetIncrementOnRebuffer,
+ minPossibleLiveOffsetSmoothingFactor:
+ minPossibleLiveOffsetSmoothingFactor,
+ );
+}
+
+class ProgressiveAudioSourceOptions {
+ final AndroidExtractorOptions? androidExtractorOptions;
+ final DarwinAssetOptions? darwinAssetOptions;
+
+ const ProgressiveAudioSourceOptions({
+ this.androidExtractorOptions,
+ this.darwinAssetOptions,
+ });
+
+ ProgressiveAudioSourceOptionsMessage _toMessage() =>
+ ProgressiveAudioSourceOptionsMessage(
+ androidExtractorOptions: androidExtractorOptions?._toMessage(),
+ darwinAssetOptions: darwinAssetOptions?._toMessage(),
+ );
+}
+
+class DarwinAssetOptions {
+ final bool preferPreciseDurationAndTiming;
+
+ const DarwinAssetOptions({this.preferPreciseDurationAndTiming = false});
+
+ DarwinAssetOptionsMessage _toMessage() => DarwinAssetOptionsMessage(
+ preferPreciseDurationAndTiming: preferPreciseDurationAndTiming,
+ );
+}
+
+class AndroidExtractorOptions {
+ static const flagMp3EnableIndexSeeking = 1 << 2;
+ static const flagMp3DisableId3Metadata = 1 << 3;
+
+ final bool constantBitrateSeekingEnabled;
+ final bool constantBitrateSeekingAlwaysEnabled;
+ final int mp3Flags;
+
+ const AndroidExtractorOptions({
+ this.constantBitrateSeekingEnabled = true,
+ this.constantBitrateSeekingAlwaysEnabled = false,
+ this.mp3Flags = 0,
+ });
+
+ AndroidExtractorOptionsMessage _toMessage() => AndroidExtractorOptionsMessage(
+ constantBitrateSeekingEnabled: constantBitrateSeekingEnabled,
+ constantBitrateSeekingAlwaysEnabled:
+ constantBitrateSeekingAlwaysEnabled,
+ mp3Flags: mp3Flags,
+ );
+}
+
+/// A local proxy HTTP server for making remote GET requests with headers.
+class _ProxyHttpServer {
+ late HttpServer _server;
+ bool _running = false;
+
+ /// Maps request keys to [_ProxyHandler]s.
+ final Map<String, _ProxyHandler> _handlerMap = {};
+
+ /// The port this server is bound to on localhost. This is set only after
+ /// [start] has completed.
+ int get port => _server.port;
+
+ /// Register a [UriAudioSource] to be served through this proxy. This may be
+ /// called only after [start] has completed.
+ Uri addUriAudioSource(UriAudioSource source) {
+ final uri = source.uri;
+ final headers = <String, String>{};
+ if (source.headers != null) {
+ headers.addAll(source.headers!.cast<String, String>());
+ }
+ final path = _requestKey(uri);
+ _handlerMap[path] = _proxyHandlerForUri(
+ uri,
+ headers: headers,
+ userAgent: source._player?._userAgent,
+ );
+ return uri.replace(
+ scheme: 'http',
+ host: InternetAddress.loopbackIPv4.address,
+ port: port,
+ );
+ }
+
+ /// Register a [StreamAudioSource] to be served through this proxy. This may
+ /// be called only after [start] has completed.
+ Uri addStreamAudioSource(StreamAudioSource source) {
+ final uri = _sourceUri(source);
+ final path = _requestKey(uri);
+ _handlerMap[path] = _proxyHandlerForSource(source);
+ return uri;
+ }
+
+ Uri _sourceUri(StreamAudioSource source) => Uri.http(
+ '${InternetAddress.loopbackIPv4.address}:$port', '/id/${source._id}');
+
+ /// A unique key for each request that can be processed by this proxy,
+ /// made up of the URL path and query string. It is not possible to
+ /// simultaneously track requests that have the same URL path and query
+ /// but differ in other respects such as the port or headers.
+ String _requestKey(Uri uri) => '${uri.path}?${uri.query}';
+
+ /// Start the server if it is not already running.
+ Future<dynamic> ensureRunning() async {
+ if (_running) return;
+ return await start();
+ }
+
+ /// Starts the server.
+ Future<dynamic> start() async {
+ _running = true;
+ _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ _server.listen((request) async {
+ if (request.method == 'GET') {
+ final uriPath = _requestKey(request.uri);
+ final handler = _handlerMap[uriPath]!;
+ handler(this, request);
+ }
+ }, onDone: () {
+ _running = false;
+ }, onError: (Object e, StackTrace st) {
+ _running = false;
+ });
+ }
+
+ /// Stops the server
+ Future<dynamic> stop() async {
+ if (!_running) return;
+ _running = false;
+ return await _server.close();
+ }
+}
+
+/// Encapsulates the start and end of an HTTP range request.
+class _HttpRangeRequest {
+ /// The starting byte position of the range request.
+ final int start;
+
+ /// The last byte position of the range request, or `null` if requesting
+ /// until the end of the media.
+ final int? end;
+
+ /// The end byte position (exclusive), defaulting to `null`.
+ int? get endEx => end == null ? null : end! + 1;
+
+ _HttpRangeRequest(this.start, this.end);
+
+ /// Format a range header for this request.
+ String get header =>
+ 'bytes=$start-${end != null ? (end! - 1).toString() : ""}';
+
+ /// Creates an [_HttpRangeRequest] from [header].
+ static _HttpRangeRequest? parse(List<String>? header) {
+ if (header == null || header.isEmpty) return null;
+ final match = RegExp(r'^bytes=(\d+)(-(\d+)?)?').firstMatch(header.first);
+ if (match == null) return null;
+ int? intGroup(int i) => match[i] != null ? int.parse(match[i]!) : null;
+ return _HttpRangeRequest(intGroup(1)!, intGroup(3));
+ }
+}
+
+/// Encapsulates the range information in an HTTP range response.
+class _HttpRangeResponse {
+ /// The starting byte position of the range.
+ final int start;
+
+ /// The last byte position of the range.
+ final int end;
+
+ /// The total number of bytes in the entire media.
+ final int? fullLength;
+
+ _HttpRangeResponse(this.start, this.end, this.fullLength);
+
+ /// The end byte position (exclusive).
+ int? get endEx => end + 1;
+
+ /// The number of bytes requested.
+ int? get length => endEx == null ? null : endEx! - start;
+
+ /// The content-range header value to use in HTTP responses.
+ String get header => 'bytes $start-$end/${fullLength?.toString() ?? "*"}';
+}
+
+/// Specifies a source of audio to be played. Audio sources are composable
+/// using the subclasses of this class. The same [AudioSource] instance should
+/// not be used simultaneously by more than one [AudioPlayer].
+abstract class AudioSource {
+ final String _id;
+ AudioPlayer? _player;
+
+ /// Creates an [AudioSource] from a [Uri] with optional headers by
+ /// attempting to guess the type of stream. On iOS, this uses Apple's SDK to
+ /// automatically detect the stream type. On Android, the type of stream will
+ /// be guessed from the extension.
+ ///
+ /// If you are loading DASH or HLS streams that do not have standard "mpd" or
+ /// "m3u8" extensions in their URIs, this method will fail to detect the
+ /// stream type on Android. If you know in advance what type of audio stream
+ /// it is, you should instantiate [DashAudioSource] or [HlsAudioSource]
+ /// directly.
+ ///
+ /// If headers are set, just_audio will create a cleartext local HTTP proxy on
+ /// your device to forward HTTP requests with headers included.
+ ///
+ /// The [tag] is for associating your app's own data with each audio source,
+ /// e.g. title, cover art, a primary key for your DB. Such data can be
+ /// conveniently retrieved from the tag while rendering the UI.
+ ///
+ /// When using just_audio_background, [tag] must be a MediaItem, a class
+ /// provided by that package. If you wish to have more control over the tag
+ /// for background audio purposes, consider using the plugin audio_service
+ /// instead of just_audio_background.
+ static UriAudioSource uri(Uri uri,
+ {Map<String, String>? headers, dynamic tag}) {
+ bool hasExtension(Uri uri, String extension) =>
+ uri.path.toLowerCase().endsWith('.$extension') ||
+ uri.fragment.toLowerCase().endsWith('.$extension');
+ if (hasExtension(uri, 'mpd')) {
+ return DashAudioSource(uri, headers: headers, tag: tag);
+ } else if (hasExtension(uri, 'm3u8')) {
+ return HlsAudioSource(uri, headers: headers, tag: tag);
+ } else {
+ return ProgressiveAudioSource(uri, headers: headers, tag: tag);
+ }
+ }
+
+ /// Convenience method to create an audio source for a file.
+ ///
+ /// This is equivalent to:
+ ///
+ /// ```
+ /// AudioSource.uri(Uri.file(filePath), tag: tag);
+ /// ```
+ static UriAudioSource file(String filePath, {dynamic tag}) {
+ return AudioSource.uri(Uri.file(filePath), tag: tag);
+ }
+
+ /// Convenience method to create an audio source for an asset.
+ ///
+ /// For assets within the same package, this is equivalent to:
+ ///
+ /// ```
+ /// AudioSource.uri(Uri.parse('asset:///$assetPath'), tag: tag);
+ /// ```
+ ///
+ /// If the asset is to be loaded from a different package, the [package]
+ /// parameter must be given to specify the package name.
+ static UriAudioSource asset(String assetPath,
+ {String? package, dynamic tag}) {
+ final keyName =
+ package == null ? assetPath : 'packages/$package/$assetPath';
+ return AudioSource.uri(Uri.parse('asset:///$keyName'), tag: tag);
+ }
+
+ AudioSource() : _id = _uuid.v4();
+
+ @mustCallSuper
+ Future<void> _setup(AudioPlayer player) async {
+ _player = player;
+ player._registerAudioSource(this);
+ }
+
+ String? get _userAgent => _player?._userAgent;
+
+ void _shuffle({int? initialIndex});
+
+ @mustCallSuper
+ void _dispose() {
+ // Without this we might make _player "late".
+ _player = null;
+ }
+
+ AudioSourceMessage _toMessage();
+
+ List<IndexedAudioSource> get sequence;
+
+ List<int> get shuffleIndices;
+
+ @override
+ int get hashCode => _id.hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is AudioSource &&
+ other._id == _id;
+}
+
+/// An [AudioSource] that can appear in a sequence.
+abstract class IndexedAudioSource extends AudioSource {
+ final dynamic tag;
+ Duration? duration;
+
+ IndexedAudioSource({this.tag, this.duration});
+
+ @override
+ void _shuffle({int? initialIndex}) {}
+
+ @override
+ List<IndexedAudioSource> get sequence => [this];
+
+ @override
+ List<int> get shuffleIndices => [0];
+}
+
+/// An abstract class representing audio sources that are loaded from a URI.
+abstract class UriAudioSource extends IndexedAudioSource {
+ final Uri uri;
+ final Map<String, String>? headers;
+ Uri? _overrideUri;
+
+ UriAudioSource(this.uri, {this.headers, dynamic tag, Duration? duration})
+ : super(tag: tag, duration: duration);
+
+ /// If [uri] points to an asset, this gives us [_overrideUri] which is the URI
+ /// of the copied asset on the filesystem, otherwise it gives us the original
+ /// [uri].
+ Uri get _effectiveUri => _overrideUri ?? uri;
+
+ Map<String, String>? get _mergedHeaders =>
+ headers == null && _userAgent == null
+ ? null
+ : {
+ if (headers != null)
+ for (var key in headers!.keys) key: headers![key]!,
+ if (_userAgent != null) 'User-Agent': _userAgent!,
+ };
+
+ @override
+ Future<void> _setup(AudioPlayer player) async {
+ await super._setup(player);
+ if (uri.scheme == 'asset') {
+ _overrideUri = await _loadAsset(uri.pathSegments.join('/'));
+ } else if (uri.scheme != 'file' &&
+ !kIsWeb &&
+ player._useProxyForRequestHeaders &&
+ (headers != null || player._userAgent != null)) {
+ await player._proxy.ensureRunning();
+ _overrideUri = player._proxy.addUriAudioSource(this);
+ }
+ }
+
+ Future<Uri> _loadAsset(String assetPath) async {
+ if (kIsWeb) {
+ // Mapping from extensions to content types for the web player. If an
+ // extension is missing, please submit a pull request.
+ const mimeTypes = {
+ '.aac': 'audio/aac',
+ '.mp3': 'audio/mpeg',
+ '.ogg': 'audio/ogg',
+ '.opus': 'audio/opus',
+ '.wav': 'audio/wav',
+ '.weba': 'audio/webm',
+ '.mp4': 'audio/mp4',
+ '.m4a': 'audio/mp4',
+ '.aif': 'audio/x-aiff',
+ '.aifc': 'audio/x-aiff',
+ '.aiff': 'audio/x-aiff',
+ '.m3u': 'audio/x-mpegurl',
+ };
+ // Default to 'audio/mpeg'
+ final mimeType =
+ mimeTypes[p.extension(assetPath).toLowerCase()] ?? 'audio/mpeg';
+ return _encodeDataUrl(
+ base64
+ .encode((await rootBundle.load(assetPath)).buffer.asUint8List()),
+ mimeType);
+ } else {
+ // For non-web platforms, extract the asset into a cache file and pass
+ // that to the player.
+ final file = await _getCacheFile(assetPath);
+ // Not technically inter-isolate-safe, although low risk. Could consider
+ // locking the file or creating a separate lock file.
+ if (!file.existsSync()) {
+ file.createSync(recursive: true);
+ await file.writeAsBytes(
+ (await rootBundle.load(assetPath)).buffer.asUint8List());
+ }
+ return Uri.file(file.path);
+ }
+ }
+
+ /// Get file for caching asset media with proper extension
+ Future<File> _getCacheFile(final String assetPath) async => File(p.joinAll([
+ (await _getCacheDir()).path,
+ 'assets',
+ ...Uri.parse(assetPath).pathSegments,
+ ]));
+}
+
+/// An [AudioSource] representing a regular media file such as an MP3 or M4A
+/// file. The following URI schemes are supported:
+///
+/// * file: loads from a local file (provided you give your app permission to
+/// access that file).
+/// * asset: loads from a Flutter asset (not supported on Web).
+/// * http(s): loads from an HTTP(S) resource.
+///
+/// On platforms except for the web, the supplied [headers] will be passed with
+/// the HTTP(S) request.
+///
+/// If headers are set, just_audio will create a cleartext local HTTP proxy on
+/// your device to forward HTTP requests with headers included.
+class ProgressiveAudioSource extends UriAudioSource {
+ final ProgressiveAudioSourceOptions? options;
+
+ ProgressiveAudioSource(
+ super.uri, {
+ super.headers,
+ super.tag,
+ super.duration,
+ this.options,
+ });
+
+ @override
+ AudioSourceMessage _toMessage() => ProgressiveAudioSourceMessage(
+ id: _id,
+ uri: _effectiveUri.toString(),
+ headers: _mergedHeaders,
+ tag: tag,
+ options: options?._toMessage(),
+ );
+}
+
+/// An [AudioSource] representing a DASH stream. The following URI schemes are
+/// supported:
+///
+/// * file: loads from a local file (provided you give your app permission to
+/// access that file).
+/// * asset: loads from a Flutter asset (not supported on Web).
+/// * http(s): loads from an HTTP(S) resource.
+///
+/// On platforms except for the web, the supplied [headers] will be passed with
+/// the HTTP(S) request. Currently headers are not recursively applied to items
+/// the HTTP(S) request. Currently headers are not applied recursively.
+///
+/// If headers are set, just_audio will create a cleartext local HTTP proxy on
+/// your device to forward HTTP requests with headers included.
+class DashAudioSource extends UriAudioSource {
+ DashAudioSource(Uri uri,
+ {Map<String, String>? headers, dynamic tag, Duration? duration})
+ : super(uri, headers: headers, tag: tag, duration: duration);
+
+ @override
+ AudioSourceMessage _toMessage() => DashAudioSourceMessage(
+ id: _id,
+ uri: _effectiveUri.toString(),
+ headers: _mergedHeaders,
+ tag: tag,
+ );
+}
+
+/// An [AudioSource] representing an HLS stream. The following URI schemes are
+/// supported:
+///
+/// * file: loads from a local file (provided you give your app permission to
+/// access that file).
+/// * asset: loads from a Flutter asset (not supported on Web).
+/// * http(s): loads from an HTTP(S) resource.
+///
+/// On platforms except for the web, the supplied [headers] will be passed with
+/// the HTTP(S) request. Currently headers are not applied recursively.
+///
+/// If headers are set, just_audio will create a cleartext local HTTP proxy on
+/// your device to forward HTTP requests with headers included.
+class HlsAudioSource extends UriAudioSource {
+ HlsAudioSource(Uri uri,
+ {Map<String, String>? headers, dynamic tag, Duration? duration})
+ : super(uri, headers: headers, tag: tag, duration: duration);
+
+ @override
+ AudioSourceMessage _toMessage() => HlsAudioSourceMessage(
+ id: _id,
+ uri: _effectiveUri.toString(),
+ headers: _mergedHeaders,
+ tag: tag,
+ );
+}
+
+/// An [AudioSource] for a period of silence.
+///
+/// NOTE: This is currently supported on Android only.
+class SilenceAudioSource extends IndexedAudioSource {
+ @override
+ Duration get duration => super.duration!;
+
+ @override
+ set duration(covariant Duration duration) => super.duration = duration;
+
+ SilenceAudioSource({
+ dynamic tag,
+ required Duration duration,
+ }) : super(tag: tag, duration: duration);
+
+ @override
+ AudioSourceMessage _toMessage() =>
+ SilenceAudioSourceMessage(id: _id, duration: duration);
+}
+
+/// An [AudioSource] representing a concatenation of multiple audio sources to
+/// be played in succession. This can be used to create playlists. Playback
+/// between items will be gapless on Android, iOS and macOS, while there will
+/// be a slight gap on Web.
+///
+/// (Untested) Audio sources can be dynamically added, removed and reordered
+/// while the audio is playing.
+class ConcatenatingAudioSource extends AudioSource {
+ final List<AudioSource> children;
+ final bool useLazyPreparation;
+ final ShuffleOrder _shuffleOrder;
+
+ /// Creates a [ConcatenatingAudioSorce] with the specified [children]. If
+ /// [useLazyPreparation] is `true`, children will be loaded/buffered as late
+ /// as possible before needed for playback (currently supported on Android,
+ /// iOS, MacOS). When [AudioPlayer.shuffleModeEnabled] is `true`,
+ /// [shuffleOrder] will be used to determine the playback order (defaulting to
+ /// [DefaultShuffleOrder]).
+ ConcatenatingAudioSource({
+ required this.children,
+ this.useLazyPreparation = true,
+ ShuffleOrder? shuffleOrder,
+ }) : _shuffleOrder = shuffleOrder ?? DefaultShuffleOrder()
+ ..insert(0, children.length);
+
+ @override
+ Future<void> _setup(AudioPlayer player) async {
+ await super._setup(player);
+ for (var source in children) {
+ await source._setup(player);
+ }
+ }
+
+ @override
+ void _shuffle({int? initialIndex}) {
+ int? localInitialIndex;
+ // si = index in [sequence]
+ // ci = index in [children] array.
+ for (var ci = 0, si = 0; ci < children.length; ci++) {
+ final child = children[ci];
+ final childLength = child.sequence.length;
+ final initialIndexWithinThisChild = initialIndex != null &&
+ initialIndex >= si &&
+ initialIndex < si + childLength;
+ if (initialIndexWithinThisChild) {
+ localInitialIndex = ci;
+ }
+ final childInitialIndex =
+ initialIndexWithinThisChild ? (initialIndex - si) : null;
+ child._shuffle(initialIndex: childInitialIndex);
+ si += childLength;
+ }
+ _shuffleOrder.shuffle(initialIndex: localInitialIndex);
+ }
+
+ /// (Untested) Appends an [AudioSource].
+ Future<void> add(AudioSource audioSource) async {
+ final index = children.length;
+ children.add(audioSource);
+ _shuffleOrder.insert(index, 1);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await audioSource._setup(_player!);
+ await (await _player!._platform).concatenatingInsertAll(
+ ConcatenatingInsertAllRequest(
+ id: _id,
+ index: index,
+ children: [audioSource._toMessage()],
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Inserts an [AudioSource] at [index].
+ Future<void> insert(int index, AudioSource audioSource) async {
+ children.insert(index, audioSource);
+ _shuffleOrder.insert(index, 1);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await audioSource._setup(_player!);
+ await (await _player!._platform).concatenatingInsertAll(
+ ConcatenatingInsertAllRequest(
+ id: _id,
+ index: index,
+ children: [audioSource._toMessage()],
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Appends multiple [AudioSource]s.
+ Future<void> addAll(List<AudioSource> children) async {
+ final index = this.children.length;
+ this.children.addAll(children);
+ _shuffleOrder.insert(index, children.length);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ for (var child in children) {
+ await child._setup(_player!);
+ }
+ await (await _player!._platform).concatenatingInsertAll(
+ ConcatenatingInsertAllRequest(
+ id: _id,
+ index: index,
+ children: children.map((child) => child._toMessage()).toList(),
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Insert multiple [AudioSource]s at [index].
+ Future<void> insertAll(int index, List<AudioSource> children) async {
+ this.children.insertAll(index, children);
+ _shuffleOrder.insert(index, children.length);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ for (var child in children) {
+ await child._setup(_player!);
+ }
+ await (await _player!._platform).concatenatingInsertAll(
+ ConcatenatingInsertAllRequest(
+ id: _id,
+ index: index,
+ children: children.map((child) => child._toMessage()).toList(),
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Dynamically remove an [AudioSource] at [index] after this
+ /// [ConcatenatingAudioSource] has already been loaded.
+ Future<void> removeAt(int index) async {
+ children.removeAt(index);
+ _shuffleOrder.removeRange(index, index + 1);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await (await _player!._platform).concatenatingRemoveRange(
+ ConcatenatingRemoveRangeRequest(
+ id: _id,
+ startIndex: index,
+ endIndex: index + 1,
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Removes a range of [AudioSource]s from index [start] inclusive
+ /// to [end] exclusive.
+ Future<void> removeRange(int start, int end) async {
+ children.removeRange(start, end);
+ _shuffleOrder.removeRange(start, end);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await (await _player!._platform).concatenatingRemoveRange(
+ ConcatenatingRemoveRangeRequest(
+ id: _id,
+ startIndex: start,
+ endIndex: end,
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Moves an [AudioSource] from [currentIndex] to [newIndex].
+ Future<void> move(int currentIndex, int newIndex) async {
+ children.insert(newIndex, children.removeAt(currentIndex));
+ _shuffleOrder.removeRange(currentIndex, currentIndex + 1);
+ _shuffleOrder.insert(newIndex, 1);
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await (await _player!._platform).concatenatingMove(
+ ConcatenatingMoveRequest(
+ id: _id,
+ currentIndex: currentIndex,
+ newIndex: newIndex,
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// (Untested) Removes all [AudioSource]s.
+ Future<void> clear() async {
+ final end = children.length;
+ children.clear();
+ _shuffleOrder.clear();
+ if (_player != null) {
+ _player!._broadcastSequence();
+ await (await _player!._platform).concatenatingRemoveRange(
+ ConcatenatingRemoveRangeRequest(
+ id: _id,
+ startIndex: 0,
+ endIndex: end,
+ shuffleOrder: List.of(_shuffleOrder.indices)));
+ }
+ }
+
+ /// The number of [AudioSource]s.
+ int get length => children.length;
+
+ AudioSource operator [](int index) => children[index];
+
+ @override
+ List<IndexedAudioSource> get sequence =>
+ children.expand((s) => s.sequence).toList();
+
+ @override
+ List<int> get shuffleIndices {
+ var offset = 0;
+ final childIndicesList = <List<int>>[];
+ for (var child in children) {
+ final childIndices = child.shuffleIndices.map((i) => i + offset).toList();
+ childIndicesList.add(childIndices);
+ offset += childIndices.length;
+ }
+ final indices = <int>[];
+ for (var index in _shuffleOrder.indices) {
+ indices.addAll(childIndicesList[index]);
+ }
+ return indices;
+ }
+
+ @override
+ AudioSourceMessage _toMessage() => ConcatenatingAudioSourceMessage(
+ id: _id,
+ children: children.map((child) => child._toMessage()).toList(),
+ useLazyPreparation: useLazyPreparation,
+ shuffleOrder: _shuffleOrder.indices);
+}
+
+/// An [AudioSource] that clips the audio of a [UriAudioSource] between a
+/// certain start and end time.
+class ClippingAudioSource extends IndexedAudioSource {
+ final UriAudioSource child;
+ final Duration? start;
+ final Duration? end;
+
+ /// Creates an audio source that clips [child] to the range [start]..[end],
+ /// where [start] and [end] default to the beginning and end of the original
+ /// [child] source.
+ ClippingAudioSource({
+ required this.child,
+ this.start,
+ this.end,
+ dynamic tag,
+ Duration? duration,
+ }) : super(tag: tag, duration: duration);
+
+ @override
+ Future<void> _setup(AudioPlayer player) async {
+ await super._setup(player);
+ await child._setup(player);
+ }
+
+ @override
+ AudioSourceMessage _toMessage() => ClippingAudioSourceMessage(
+ id: _id,
+ child: child._toMessage() as UriAudioSourceMessage,
+ start: start,
+ end: end,
+ tag: tag);
+}
+
+// An [AudioSource] that loops a nested [AudioSource] a finite number of times.
+// NOTE: this can be inefficient when using a large loop count. If you wish to
+// loop an infinite number of times, use [AudioPlayer.setLoopMode].
+class LoopingAudioSource extends AudioSource {
+ AudioSource child;
+ final int count;
+
+ LoopingAudioSource({
+ required this.child,
+ required this.count,
+ }) : super();
+
+ @override
+ Future<void> _setup(AudioPlayer player) async {
+ await super._setup(player);
+ await child._setup(player);
+ }
+
+ @override
+ void _shuffle({int? initialIndex}) {}
+
+ @override
+ List<IndexedAudioSource> get sequence =>
+ List.generate(count, (i) => child).expand((s) => s.sequence).toList();
+
+ @override
+ List<int> get shuffleIndices => List.generate(count, (i) => i);
+
+ @override
+ AudioSourceMessage _toMessage() => LoopingAudioSourceMessage(
+ id: _id, child: child._toMessage(), count: count);
+}
+
+Uri _encodeDataUrl(String base64Data, String mimeType) =>
+ Uri.parse('data:$mimeType;base64,$base64Data');
+
+/// An [AudioSource] that provides audio dynamically. Subclasses must override
+/// [request] to provide the encoded audio data. This API is experimental.
+@experimental
+abstract class StreamAudioSource extends IndexedAudioSource {
+ Uri? _uri;
+ StreamAudioSource({dynamic tag}) : super(tag: tag);
+
+ @override
+ Future<void> _setup(AudioPlayer player) async {
+ await super._setup(player);
+ if (kIsWeb) {
+ final response = await request();
+ _uri = _encodeDataUrl(await base64.encoder.bind(response.stream).join(),
+ response.contentType);
+ } else {
+ await player._proxy.ensureRunning();
+ _uri = player._proxy.addStreamAudioSource(this);
+ }
+ }
+
+ /// Used by the player to request a byte range of encoded audio data in small
+ /// chunks, from byte position [start] inclusive (or from the beginning of the
+ /// audio data if not specified) to [end] exclusive (or the end of the audio
+ /// data if not specified). If the returned future completes with an error,
+ /// a 500 response will be sent back to the player.
+ Future<StreamAudioResponse> request([int? start, int? end]);
+
+ @override
+ AudioSourceMessage _toMessage() => ProgressiveAudioSourceMessage(
+ id: _id, uri: _uri.toString(), headers: null, tag: tag);
+}
+
+/// The response for a [StreamAudioSource]. This API is experimental.
+@experimental
+class StreamAudioResponse {
+ /// Indicates to the client whether or not range requests are supported for
+ /// the requested media. If `true`, the client may make further requests
+ /// specifying the `start` and possibly also the `end` parameters of the range
+ /// request, otherwise these will both be null.
+ final bool rangeRequestsSupported;
+
+ /// When responding to a range request, this holds the byte length of the
+ /// entire media, otherwise it holds `null`.
+ final int? sourceLength;
+
+ /// The number of bytes returned in this response, or `null` if unknown. Note:
+ /// this may be different from the length of the entire media for a range
+ /// request.
+ final int? contentLength;
+
+ /// The starting byte position of the response data if responding to a range
+ /// request.
+ final int? offset;
+
+ /// The MIME type of the audio.
+ final String contentType;
+
+ /// The audio content returned by this response.
+ final Stream<List<int>> stream;
+
+ StreamAudioResponse({
+ this.rangeRequestsSupported = true,
+ required this.sourceLength,
+ required this.contentLength,
+ required this.offset,
+ required this.stream,
+ required this.contentType,
+ });
+}
+
+/// This is an experimental audio source that caches the audio while it is being
+/// downloaded and played. It is not supported on platforms that do not provide
+/// access to the file system (e.g. web).
+@experimental
+class LockCachingAudioSource extends StreamAudioSource {
+ Future<HttpClientResponse>? _response;
+ final Uri uri;
+ final Map<String, String>? headers;
+ final Future<File> cacheFile;
+ int _progress = 0;
+ final _requests = <_StreamingByteRangeRequest>[];
+ final _downloadProgressSubject = BehaviorSubject<double>();
+ bool _downloading = false;
+
+ /// Creates a [LockCachingAudioSource] to that provides [uri] to the player
+ /// while simultaneously caching it to [cacheFile]. If no cache file is
+ /// supplied, just_audio will allocate a cache file internally.
+ ///
+ /// If headers are set, just_audio will create a cleartext local HTTP proxy on
+ /// your device to forward HTTP requests with headers included.
+ LockCachingAudioSource(
+ this.uri, {
+ this.headers,
+ File? cacheFile,
+ dynamic tag,
+ }) : cacheFile =
+ cacheFile != null ? Future.value(cacheFile) : _getCacheFile(uri),
+ super(tag: tag) {
+ _init();
+ }
+
+ Future<void> _init() async {
+ final cacheFile = await this.cacheFile;
+ _downloadProgressSubject.add((await cacheFile.exists()) ? 1.0 : 0.0);
+ }
+
+ /// Returns a [UriAudioSource] resolving directly to the cache file if it
+ /// exists, otherwise returns `this`. This can be
+ Future<IndexedAudioSource> resolve() async {
+ final file = await cacheFile;
+ return await file.exists() ? AudioSource.uri(Uri.file(file.path)) : this;
+ }
+
+ /// Emits the current download progress as a double value from 0.0 (nothing
+ /// downloaded) to 1.0 (download complete).
+ Stream<double> get downloadProgressStream => _downloadProgressSubject.stream;
+
+ /// Removes the underlying cache files. It is an error to clear the cache
+ /// while a download is in progress.
+ Future<void> clearCache() async {
+ if (_downloading) {
+ throw Exception("Cannot clear cache while download is in progress");
+ }
+ _response = null;
+ final cacheFile = await this.cacheFile;
+ if (await cacheFile.exists()) {
+ await cacheFile.delete();
+ }
+ final mimeFile = await _mimeFile;
+ if (await mimeFile.exists()) {
+ await mimeFile.delete();
+ }
+ _progress = 0;
+ _downloadProgressSubject.add(0.0);
+ }
+
+ /// Get file for caching [uri] with proper extension
+ static Future<File> _getCacheFile(final Uri uri) async => File(p.joinAll([
+ (await _getCacheDir()).path,
+ 'remote',
+ sha256.convert(utf8.encode(uri.toString())).toString() +
+ p.extension(uri.path),
+ ]));
+
+ Future<File> get _partialCacheFile async =>
+ File('${(await cacheFile).path}.part');
+
+ /// We use this to record the original content type of the downloaded audio.
+ /// NOTE: We could instead rely on the cache file extension, but the original
+ /// URL might not provide a correct extension. As a fallback, we could map the
+ /// MIME type to an extension but we will need a complete dictionary.
+ Future<File> get _mimeFile async => File('${(await cacheFile).path}.mime');
+
+ Future<String> _readCachedMimeType() async {
+ final file = await _mimeFile;
+ if (file.existsSync()) {
+ return (await _mimeFile).readAsString();
+ } else {
+ return 'audio/mpeg';
+ }
+ }
+
+ /// Start downloading the whole audio file to the cache and fulfill byte-range
+ /// requests during the download. There are 3 scenarios:
+ ///
+ /// 1. If the byte range request falls entirely within the cache region, it is
+ /// fulfilled from the cache.
+ /// 2. If the byte range request overlaps the cached region, the first part is
+ /// fulfilled from the cache, and the region beyond the cache is fulfilled
+ /// from a memory buffer of the downloaded data.
+ /// 3. If the byte range request is entirely outside the cached region, a
+ /// separate HTTP request is made to fulfill it while the download of the
+ /// entire file continues in parallel.
+ Future<HttpClientResponse> _fetch() async {
+ _downloading = true;
+ final cacheFile = await this.cacheFile;
+ final partialCacheFile = await _partialCacheFile;
+
+ File getEffectiveCacheFile() =>
+ partialCacheFile.existsSync() ? partialCacheFile : cacheFile;
+
+ final httpClient = _createHttpClient(userAgent: _player?._userAgent);
+ final httpRequest = await _getUrl(httpClient, uri, headers: headers);
+ final response = await httpRequest.close();
+ if (response.statusCode != 200) {
+ httpClient.close();
+ throw Exception('HTTP Status Error: ${response.statusCode}');
+ }
+ (await _partialCacheFile).createSync(recursive: true);
+ // TODO: Should close sink after done, but it throws an error.
+ // ignore: close_sinks
+ final sink = (await _partialCacheFile).openWrite();
+ final sourceLength =
+ response.contentLength == -1 ? null : response.contentLength;
+ final mimeType = response.headers.contentType.toString();
+ final acceptRanges = response.headers.value(HttpHeaders.acceptRangesHeader);
+ final originSupportsRangeRequests =
+ acceptRanges != null && acceptRanges != 'none';
+ final mimeFile = await _mimeFile;
+ await mimeFile.writeAsString(mimeType);
+ final inProgressResponses = <_InProgressCacheResponse>[];
+ late StreamSubscription<List<int>> subscription;
+ var percentProgress = 0;
+ void updateProgress(int newPercentProgress) {
+ if (newPercentProgress != percentProgress) {
+ percentProgress = newPercentProgress;
+ _downloadProgressSubject.add(percentProgress / 100);
+ }
+ }
+
+ _progress = 0;
+ subscription = response.listen((data) async {
+ _progress += data.length;
+ final newPercentProgress = (sourceLength == null)
+ ? 0
+ : (sourceLength == 0)
+ ? 100
+ : (100 * _progress ~/ sourceLength);
+ updateProgress(newPercentProgress);
+ sink.add(data);
+ final readyRequests = _requests
+ .where((request) =>
+ !originSupportsRangeRequests ||
+ request.start == null ||
+ (request.start!) < _progress)
+ .toList();
+ final notReadyRequests = _requests
+ .where((request) =>
+ originSupportsRangeRequests &&
+ request.start != null &&
+ (request.start!) >= _progress)
+ .toList();
+ // Add this live data to any responses in progress.
+ for (var cacheResponse in inProgressResponses) {
+ final end = cacheResponse.end;
+ if (end != null && _progress >= end) {
+ // We've received enough data to fulfill the byte range request.
+ final subEnd =
+ min(data.length, max(0, data.length - (_progress - end)));
+ cacheResponse.controller.add(data.sublist(0, subEnd));
+ cacheResponse.controller.close();
+ } else {
+ cacheResponse.controller.add(data);
+ }
+ }
+ inProgressResponses.removeWhere((element) => element.controller.isClosed);
+ if (_requests.isEmpty) return;
+ // Prevent further data coming from the HTTP source until we have set up
+ // an entry in inProgressResponses to continue receiving live HTTP data.
+ subscription.pause();
+ await sink.flush();
+ // Process any requests that start within the cache.
+ for (var request in readyRequests) {
+ _requests.remove(request);
+ int? start, end;
+ if (originSupportsRangeRequests) {
+ start = request.start;
+ end = request.end;
+ } else {
+ // If the origin doesn't support range requests, the proxy should also
+ // ignore range requests and instead serve a complete 200 response
+ // which the client (AV or exo player) should know how to deal with.
+ }
+ final effectiveStart = start ?? 0;
+ final effectiveEnd = end ?? sourceLength;
+ Stream<List<int>> responseStream;
+ if (effectiveEnd != null && effectiveEnd <= _progress) {
+ responseStream =
+ getEffectiveCacheFile().openRead(effectiveStart, effectiveEnd);
+ } else {
+ final cacheResponse = _InProgressCacheResponse(end: effectiveEnd);
+ inProgressResponses.add(cacheResponse);
+ responseStream = Rx.concatEager([
+ // NOTE: The cache file part of the stream must not overlap with
+ // the live part. "_progress" should
+ // to the cache file at the time
+ getEffectiveCacheFile().openRead(effectiveStart, _progress),
+ cacheResponse.controller.stream,
+ ]);
+ }
+ request.complete(StreamAudioResponse(
+ rangeRequestsSupported: originSupportsRangeRequests,
+ sourceLength: start != null ? sourceLength : null,
+ contentLength:
+ effectiveEnd != null ? effectiveEnd - effectiveStart : null,
+ offset: start,
+ contentType: mimeType,
+ stream: responseStream.asBroadcastStream(),
+ ));
+ }
+ subscription.resume();
+ // Process any requests that start beyond the cache.
+ for (var request in notReadyRequests) {
+ _requests.remove(request);
+ final start = request.start!;
+ final end = request.end ?? sourceLength;
+ final httpClient = _createHttpClient(userAgent: _player?._userAgent);
+
+ final rangeRequest = _HttpRangeRequest(start, end);
+ _getUrl(httpClient, uri, headers: {
+ if (headers != null) ...headers!,
+ HttpHeaders.rangeHeader: rangeRequest.header,
+ }).then((httpRequest) async {
+ final response = await httpRequest.close();
+ if (response.statusCode != 206) {
+ httpClient.close();
+ throw Exception('HTTP Status Error: ${response.statusCode}');
+ }
+ request.complete(StreamAudioResponse(
+ rangeRequestsSupported: originSupportsRangeRequests,
+ sourceLength: sourceLength,
+ contentLength: end != null ? end - start : null,
+ offset: start,
+ contentType: mimeType,
+ stream: response.asBroadcastStream(),
+ ));
+ }, onError: (dynamic e, StackTrace? stackTrace) {
+ request.fail(e, stackTrace);
+ }).onError((Object e, StackTrace st) {
+ request.fail(e, st);
+ });
+ }
+ }, onDone: () async {
+ if (sourceLength == null) {
+ updateProgress(100);
+ }
+ for (var cacheResponse in inProgressResponses) {
+ if (!cacheResponse.controller.isClosed) {
+ cacheResponse.controller.close();
+ }
+ }
+ (await _partialCacheFile).renameSync(cacheFile.path);
+ await subscription.cancel();
+ httpClient.close();
+ _downloading = false;
+ }, onError: (Object e, StackTrace stackTrace) async {
+ (await _partialCacheFile).deleteSync();
+ httpClient.close();
+ // Fail all pending requests
+ for (final req in _requests) {
+ req.fail(e, stackTrace);
+ }
+ _requests.clear();
+ // Close all in progress requests
+ for (final res in inProgressResponses) {
+ res.controller.addError(e, stackTrace);
+ res.controller.close();
+ }
+ _downloading = false;
+ }, cancelOnError: true);
+ return response;
+ }
+
+ @override
+ Future<StreamAudioResponse> request([int? start, int? end]) async {
+ final cacheFile = await this.cacheFile;
+ if (cacheFile.existsSync()) {
+ final sourceLength = cacheFile.lengthSync();
+ return StreamAudioResponse(
+ rangeRequestsSupported: true,
+ sourceLength: start != null ? sourceLength : null,
+ contentLength: (end ?? sourceLength) - (start ?? 0),
+ offset: start,
+ contentType: await _readCachedMimeType(),
+ stream: cacheFile.openRead(start, end).asBroadcastStream(),
+ );
+ }
+ final byteRangeRequest = _StreamingByteRangeRequest(start, end);
+ _requests.add(byteRangeRequest);
+ _response ??=
+ _fetch().catchError((dynamic error, StackTrace? stackTrace) async {
+ // So that we can restart later
+ _response = null;
+ // Cancel any pending request
+ for (final req in _requests) {
+ req.fail(error, stackTrace);
+ }
+ return Future<HttpClientResponse>.error(error as Object, stackTrace);
+ });
+ return byteRangeRequest.future.then((response) {
+ response.stream.listen((event) {}, onError: (Object e, StackTrace st) {
+ // So that we can restart later
+ _response = null;
+ // Cancel any pending request
+ for (final req in _requests) {
+ req.fail(e, st);
+ }
+ });
+ return response;
+ });
+ }
+}
+
+/// When a byte range request on a [LockCachingAudioSource] overlaps partially
+/// with the cache file and partially with the live HTTP stream, the consumer
+/// needs to first consume the cached part before the live part. This class
+/// provides a place to buffer the live part until the consumer reaches it, and
+/// also keeps track of the [end] of the byte range so that the producer knows
+/// when to stop adding data.
+class _InProgressCacheResponse {
+ // NOTE: This isn't necessarily memory efficient. Since the entire audio file
+ // will likely be downloaded at a faster rate than the rate at which the
+ // player is consuming audio data, it is also likely that this buffered data
+ // will never be used.
+ // TODO: Improve this code.
+ // ignore: close_sinks
+ final controller = ReplaySubject<List<int>>();
+ final int? end;
+ _InProgressCacheResponse({
+ required this.end,
+ });
+}
+
+/// Request parameters for a [StreamAudioSource].
+class _StreamingByteRangeRequest {
+ /// The start of the range request.
+ final int? start;
+
+ /// The end of the range request.
+ final int? end;
+
+ /// Completes when the response is available.
+ final _completer = Completer<StreamAudioResponse>();
+
+ _StreamingByteRangeRequest(this.start, this.end);
+
+ /// The response for this request.
+ Future<StreamAudioResponse> get future => _completer.future;
+
+ /// Completes this request with the given [response].
+ void complete(StreamAudioResponse response) {
+ if (_completer.isCompleted) {
+ return;
+ }
+ _completer.complete(response);
+ }
+
+ /// Fails this request with the given [error] and [stackTrace].
+ void fail(dynamic error, [StackTrace? stackTrace]) {
+ if (_completer.isCompleted) {
+ return;
+ }
+ _completer.completeError(error as Object, stackTrace);
+ }
+}
+
+/// The type of functions that can handle HTTP requests sent to the proxy.
+typedef _ProxyHandler = void Function(
+ _ProxyHttpServer server, HttpRequest request);
+
+/// A proxy handler for serving audio from a [StreamAudioSource].
+_ProxyHandler _proxyHandlerForSource(StreamAudioSource source) {
+ Future<void> handler(_ProxyHttpServer server, HttpRequest request) async {
+ final rangeRequest =
+ _HttpRangeRequest.parse(request.headers[HttpHeaders.rangeHeader]);
+
+ request.response.headers.clear();
+
+ StreamAudioResponse sourceResponse;
+ Stream<List<int>> stream;
+ try {
+ sourceResponse =
+ await source.request(rangeRequest?.start, rangeRequest?.endEx);
+ stream = sourceResponse.stream;
+ } catch (e, st) {
+ // ignore: avoid_print
+ print("Proxy request failed: $e\n$st");
+
+ request.response.headers.clear();
+ request.response.statusCode = HttpStatus.internalServerError;
+ await request.response.close();
+ return;
+ }
+
+ request.response.headers
+ .set(HttpHeaders.contentTypeHeader, sourceResponse.contentType);
+
+ if (sourceResponse.rangeRequestsSupported) {
+ request.response.headers.set(HttpHeaders.acceptRangesHeader, 'bytes');
+ }
+
+ if (rangeRequest != null && sourceResponse.offset != null) {
+ final range = _HttpRangeResponse(
+ sourceResponse.offset!,
+ sourceResponse.offset! + sourceResponse.contentLength! - 1,
+ sourceResponse.sourceLength);
+ request.response.contentLength = range.length ?? -1;
+ request.response.headers
+ .set(HttpHeaders.contentRangeHeader, range.header);
+ request.response.statusCode = 206;
+ } else {
+ request.response.contentLength = sourceResponse.contentLength ?? -1;
+ request.response.statusCode = 200;
+ }
+
+ final completer = Completer<void>();
+ final subscription = stream.listen((event) {
+ request.response.add(event);
+ }, onError: (Object e, StackTrace st) {
+ source._player?._playbackEventSubject.addError(e, st);
+ }, onDone: () {
+ completer.complete();
+ });
+
+ request.response.done.then((dynamic value) {
+ subscription.cancel();
+ });
+
+ await completer.future;
+
+ await request.response.close();
+ }
+
+ return handler;
+}
+
+/// A proxy handler for serving audio from a URI with optional headers.
+_ProxyHandler _proxyHandlerForUri(
+ Uri uri, {
+ Map<String, String>? headers,
+ String? userAgent,
+}) {
+ // Keep redirected [Uri] to speed-up requests
+ Uri? redirectedUri;
+ Future<void> handler(_ProxyHttpServer server, HttpRequest request) async {
+ final client = _createHttpClient(userAgent: userAgent);
+ // Try to make normal request
+ String? host;
+ try {
+ final requestHeaders = <String, String>{};
+ request.headers
+ .forEach((name, value) => requestHeaders[name] = value.join(', '));
+ // write supplied headers last (to ensure supplied headers aren't overwritten)
+ headers?.forEach((name, value) => requestHeaders[name] = value);
+ final originRequest =
+ await _getUrl(client, redirectedUri ?? uri, headers: requestHeaders);
+ host = originRequest.headers.value(HttpHeaders.hostHeader);
+ final originResponse = await originRequest.close();
+ if (originResponse.redirects.isNotEmpty) {
+ redirectedUri = originResponse.redirects.last.location;
+ }
+
+ request.response.headers.clear();
+ originResponse.headers.forEach((name, value) {
+ final filteredValue = value
+ .map((e) => e.replaceAll(RegExp(r'[^\x09\x20-\x7F]'), '?'))
+ .toList();
+ request.response.headers.set(name, filteredValue);
+ });
+ request.response.statusCode = originResponse.statusCode;
+
+ // Send response
+ if (headers != null && request.uri.path.toLowerCase().endsWith('.m3u8') ||
+ ['application/x-mpegURL', 'application/vnd.apple.mpegurl']
+ .contains(request.headers.value(HttpHeaders.contentTypeHeader))) {
+ // If this is an m3u8 file with headers, prepare the nested URIs.
+ // TODO: Handle other playlist formats similarly?
+ final m3u8 = await originResponse.transform(utf8.decoder).join();
+ for (var line in const LineSplitter().convert(m3u8)) {
+ line = line.replaceAllMapped(
+ RegExp(r'#EXT-X-MEDIA:.*?URI="(.*?)".*'), (m) => m[1]!);
+ line = line.replaceAll(RegExp(r'#.*$'), '').trim();
+ if (line.isEmpty) continue;
+ try {
+ final rawNestedUri = Uri.parse(line);
+ if (rawNestedUri.hasScheme) {
+ // Don't propagate headers
+ server.addUriAudioSource(AudioSource.uri(rawNestedUri));
+ } else {
+ // This is a resource on the same server, so propagate the headers.
+ final basePath = rawNestedUri.path.startsWith('/')
+ ? ''
+ : uri.path.replaceAll(RegExp(r'/[^/]*$'), '/');
+ final nestedUri =
+ uri.replace(path: '$basePath${rawNestedUri.path}');
+ server.addUriAudioSource(
+ AudioSource.uri(nestedUri, headers: headers));
+ }
+ } catch (e) {
+ // ignore malformed lines
+ }
+ }
+ request.response.add(utf8.encode(m3u8));
+ } else {
+ request.response.bufferOutput = false;
+ var done = false;
+ request.response.done.then((dynamic _) => done = true);
+ await for (var chunk in originResponse) {
+ if (done) break;
+ request.response.add(chunk);
+ await request.response.flush();
+ }
+ }
+ await request.response.flush();
+ await request.response.close();
+ } on HttpException {
+ // We likely are dealing with a streaming protocol
+ if (uri.scheme == 'http') {
+ // Try parsing HTTP 0.9 response
+ //request.response.headers.clear();
+ final socket = await Socket.connect(uri.host, uri.port);
+ final clientSocket =
+ await request.response.detachSocket(writeHeaders: false);
+ final done = Completer<dynamic>();
+ socket.listen(
+ clientSocket.add,
+ onDone: () async {
+ await clientSocket.flush();
+ socket.close();
+ clientSocket.close();
+ done.complete();
+ },
+ );
+ // Rewrite headers
+ final headers = <String, String?>{};
+ request.headers.forEach((name, value) {
+ if (name.toLowerCase() != HttpHeaders.hostHeader) {
+ headers[name] = value.join(",");
+ }
+ });
+ for (var name in headers.keys) {
+ headers[name] = headers[name];
+ }
+ socket.write("GET ${uri.path} HTTP/1.1\n");
+ if (host != null) {
+ socket.write("Host: $host\n");
+ }
+ for (var name in headers.keys) {
+ socket.write("$name: ${headers[name]}\n");
+ }
+ socket.write("\n");
+ await socket.flush();
+ await done.future;
+ }
+ }
+ }
+
+ return handler;
+}
+
+Future<Directory> _getCacheDir() async =>
+ Directory(p.join((await getTemporaryDirectory()).path, 'just_audio_cache'));
+
+/// Defines the algorithm for shuffling the order of a
+/// [ConcatenatingAudioSource]. See [DefaultShuffleOrder] for a default
+/// implementation.
+abstract class ShuffleOrder {
+ /// The shuffled list of indices of [AudioSource]s to play. For example,
+ /// [2,0,1] specifies to play the 3rd, then the 1st, then the 2nd item.
+ List<int> get indices;
+
+ /// Shuffles the [indices]. If the current item in the player falls within the
+ /// [ConcatenatingAudioSource] being shuffled, [initialIndex] will point to
+ /// that item. Subclasses may use this information as a hint, for example, to
+ /// make [initialIndex] the first item in the shuffle order.
+ void shuffle({int? initialIndex});
+
+ /// Inserts [count] new consecutive indices starting from [index] into
+ /// [indices], at random positions.
+ void insert(int index, int count);
+
+ /// Removes the indices that are `>= start` and `< end`.
+ void removeRange(int start, int end);
+
+ /// Removes all indices.
+ void clear();
+}
+
+/// The default implementation of [ShuffleOrder] which shuffles items with the
+/// currently playing item at the head of the order.
+class DefaultShuffleOrder extends ShuffleOrder {
+ final Random _random;
+ @override
+ final indices = <int>[];
+
+ DefaultShuffleOrder({Random? random}) : _random = random ?? Random();
+
+ @override
+ void shuffle({int? initialIndex}) {
+ assert(initialIndex == null || indices.contains(initialIndex));
+ if (indices.length <= 1) return;
+ indices.shuffle(_random);
+ if (initialIndex == null) return;
+
+ const initialPos = 0;
+ final swapPos = indices.indexOf(initialIndex);
+ // Swap the indices at initialPos and swapPos.
+ final swapIndex = indices[initialPos];
+ indices[initialPos] = initialIndex;
+ indices[swapPos] = swapIndex;
+ }
+
+ @override
+ void insert(int index, int count) {
+ // Offset indices after insertion point.
+ for (var i = 0; i < indices.length; i++) {
+ if (indices[i] >= index) {
+ indices[i] += count;
+ }
+ }
+ // Insert new indices at random positions after currentIndex.
+ final newIndices = List.generate(count, (i) => index + i);
+ for (var newIndex in newIndices) {
+ final insertionIndex = _random.nextInt(indices.length + 1);
+ indices.insert(insertionIndex, newIndex);
+ }
+ }
+
+ @override
+ void removeRange(int start, int end) {
+ final count = end - start;
+ // Remove old indices.
+ final oldIndices = List.generate(count, (i) => start + i).toSet();
+ indices.removeWhere(oldIndices.contains);
+ // Offset indices after deletion point.
+ for (var i = 0; i < indices.length; i++) {
+ if (indices[i] >= end) {
+ indices[i] -= count;
+ }
+ }
+ }
+
+ @override
+ void clear() {
+ indices.clear();
+ }
+}
+
+/// An enumeration of modes that can be passed to [AudioPlayer.setLoopMode].
+enum LoopMode { off, one, all }
+
+/// Possible values that can be passed to [AudioPlayer.setWebCrossOrigin].
+enum WebCrossOrigin { anonymous, useCredentials }
+
+/// The stand-in platform implementation to use when the player is in the idle
+/// state and the native platform is deallocated.
+class _IdleAudioPlayer extends AudioPlayerPlatform {
+ final _eventSubject = BehaviorSubject<PlaybackEventMessage>();
+ late Duration _position;
+ int? _index;
+ List<IndexedAudioSource>? _sequence;
+
+ /// Holds a pending request.
+ SetAndroidAudioAttributesRequest? setAndroidAudioAttributesRequest;
+
+ _IdleAudioPlayer({
+ required String id,
+ required Stream<List<IndexedAudioSource>?> sequenceStream,
+ }) : super(id) {
+ sequenceStream.listen((sequence) => _sequence = sequence);
+ }
+
+ void _broadcastPlaybackEvent() {
+ var updateTime = DateTime.now();
+ _eventSubject.add(PlaybackEventMessage(
+ processingState: ProcessingStateMessage.idle,
+ updatePosition: _position,
+ updateTime: updateTime,
+ bufferedPosition: Duration.zero,
+ icyMetadata: null,
+ duration: _getDurationAtIndex(_index),
+ currentIndex: _index,
+ androidAudioSessionId: null,
+ ));
+ }
+
+ Duration? _getDurationAtIndex(int? index) =>
+ index != null && _sequence != null && index < _sequence!.length
+ ? _sequence![index].duration
+ : null;
+
+ @override
+ Stream<PlaybackEventMessage> get playbackEventMessageStream =>
+ _eventSubject.stream;
+
+ @override
+ Future<LoadResponse> load(LoadRequest request) async {
+ _index = request.initialIndex ?? 0;
+ _position = request.initialPosition ?? Duration.zero;
+ _broadcastPlaybackEvent();
+ return LoadResponse(duration: _getDurationAtIndex(_index));
+ }
+
+ @override
+ Future<PlayResponse> play(PlayRequest request) async {
+ return PlayResponse();
+ }
+
+ @override
+ Future<PauseResponse> pause(PauseRequest request) async {
+ return PauseResponse();
+ }
+
+ @override
+ Future<SetVolumeResponse> setVolume(SetVolumeRequest request) async {
+ return SetVolumeResponse();
+ }
+
+ @override
+ Future<SetSpeedResponse> setSpeed(SetSpeedRequest request) async {
+ return SetSpeedResponse();
+ }
+
+ @override
+ Future<SetPitchResponse> setPitch(SetPitchRequest request) async {
+ return SetPitchResponse();
+ }
+
+ @override
+ Future<SetSkipSilenceResponse> setSkipSilence(
+ SetSkipSilenceRequest request) async {
+ return SetSkipSilenceResponse();
+ }
+
+ @override
+ Future<SetLoopModeResponse> setLoopMode(SetLoopModeRequest request) async {
+ return SetLoopModeResponse();
+ }
+
+ @override
+ Future<SetShuffleModeResponse> setShuffleMode(
+ SetShuffleModeRequest request) async {
+ return SetShuffleModeResponse();
+ }
+
+ @override
+ Future<SetShuffleOrderResponse> setShuffleOrder(
+ SetShuffleOrderRequest request) async {
+ return SetShuffleOrderResponse();
+ }
+
+ @override
+ Future<SetWebCrossOriginResponse> setWebCrossOrigin(
+ SetWebCrossOriginRequest request) async {
+ return SetWebCrossOriginResponse();
+ }
+
+ @override
+ Future<SetWebSinkIdResponse> setWebSinkId(SetWebSinkIdRequest request) async {
+ return SetWebSinkIdResponse();
+ }
+
+ @override
+ Future<SetAutomaticallyWaitsToMinimizeStallingResponse>
+ setAutomaticallyWaitsToMinimizeStalling(
+ SetAutomaticallyWaitsToMinimizeStallingRequest request) async {
+ return SetAutomaticallyWaitsToMinimizeStallingResponse();
+ }
+
+ @override
+ Future<SetCanUseNetworkResourcesForLiveStreamingWhilePausedResponse>
+ setCanUseNetworkResourcesForLiveStreamingWhilePaused(
+ SetCanUseNetworkResourcesForLiveStreamingWhilePausedRequest
+ request) async {
+ return SetCanUseNetworkResourcesForLiveStreamingWhilePausedResponse();
+ }
+
+ @override
+ Future<SetPreferredPeakBitRateResponse> setPreferredPeakBitRate(
+ SetPreferredPeakBitRateRequest request) async {
+ return SetPreferredPeakBitRateResponse();
+ }
+
+ @override
+ Future<SeekResponse> seek(SeekRequest request) async {
+ _position = request.position ?? Duration.zero;
+ _index = request.index ?? _index;
+ _broadcastPlaybackEvent();
+ return SeekResponse();
+ }
+
+ @override
+ Future<SetAndroidAudioAttributesResponse> setAndroidAudioAttributes(
+ SetAndroidAudioAttributesRequest request) async {
+ setAndroidAudioAttributesRequest = request;
+ return SetAndroidAudioAttributesResponse();
+ }
+
+ @override
+ Future<DisposeResponse> dispose(DisposeRequest request) async {
+ return DisposeResponse();
+ }
+
+ @override
+ Future<ConcatenatingInsertAllResponse> concatenatingInsertAll(
+ ConcatenatingInsertAllRequest request) async {
+ return ConcatenatingInsertAllResponse();
+ }
+
+ @override
+ Future<ConcatenatingRemoveRangeResponse> concatenatingRemoveRange(
+ ConcatenatingRemoveRangeRequest request) async {
+ return ConcatenatingRemoveRangeResponse();
+ }
+
+ @override
+ Future<ConcatenatingMoveResponse> concatenatingMove(
+ ConcatenatingMoveRequest request) async {
+ return ConcatenatingMoveResponse();
+ }
+
+ @override
+ Future<AudioEffectSetEnabledResponse> audioEffectSetEnabled(
+ AudioEffectSetEnabledRequest request) async {
+ return AudioEffectSetEnabledResponse();
+ }
+
+ @override
+ Future<AndroidLoudnessEnhancerSetTargetGainResponse>
+ androidLoudnessEnhancerSetTargetGain(
+ AndroidLoudnessEnhancerSetTargetGainRequest request) async {
+ return AndroidLoudnessEnhancerSetTargetGainResponse();
+ }
+
+ @override
+ Future<AndroidEqualizerBandSetGainResponse> androidEqualizerBandSetGain(
+ AndroidEqualizerBandSetGainRequest request) async {
+ return AndroidEqualizerBandSetGainResponse();
+ }
+
+ @override
+ Future<AndroidEqualizerGetParametersResponse> androidEqualizerGetParameters(
+ AndroidEqualizerGetParametersRequest request) async {
+ return AndroidEqualizerGetParametersResponse(
+ parameters: AndroidEqualizerParametersMessage(
+ minDecibels: 0.0,
+ maxDecibels: 10.0,
+ bands: [],
+ ),
+ );
+ }
+
+ @override
+ Future<SetAllowsExternalPlaybackResponse> setAllowsExternalPlayback(
+ SetAllowsExternalPlaybackRequest request) async {
+ return SetAllowsExternalPlaybackResponse();
+ }
+}
+
+/// Holds the initial requested position and index for a newly loaded audio
+/// source.
+class _InitialSeekValues {
+ final Duration? position;
+ final int? index;
+
+ _InitialSeekValues({required this.position, required this.index});
+}
+
+class AudioPipeline {
+ final List<AndroidAudioEffect> androidAudioEffects;
+ final List<DarwinAudioEffect> darwinAudioEffects;
+
+ AudioPipeline({
+ List<AndroidAudioEffect>? androidAudioEffects,
+ List<DarwinAudioEffect>? darwinAudioEffects,
+ }) : assert(androidAudioEffects == null ||
+ androidAudioEffects.toSet().length == androidAudioEffects.length),
+ assert(darwinAudioEffects == null ||
+ darwinAudioEffects.toSet().length == darwinAudioEffects.length),
+ androidAudioEffects = androidAudioEffects ?? const [],
+ darwinAudioEffects = darwinAudioEffects ?? const [];
+
+ List<AudioEffect> get _audioEffects =>
+ <AudioEffect>[...androidAudioEffects, ...darwinAudioEffects];
+
+ void _setup(AudioPlayer player) {
+ for (var effect in _audioEffects) {
+ effect._setup(player);
+ }
+ }
+}
+
+/// Subclasses of [AudioEffect] can be inserted into an [AudioPipeline] to
+/// modify the audio signal outputted by an [AudioPlayer]. The same audio effect
+/// instance cannot be set on multiple players at the same time.
+///
+/// An [AudioEffect] is disabled by default. For an [AudioEffect] to take
+/// effect, in addition to being part of an [AudioPipeline] attached to an
+/// [AudioPlayer] you must also enable the effect via [setEnabled].
+abstract class AudioEffect {
+ AudioPlayer? _player;
+ final _enabledSubject = BehaviorSubject.seeded(false);
+
+ AudioEffect();
+
+ /// Called when an [AudioEffect] is attached to an [AudioPlayer].
+ void _setup(AudioPlayer player) {
+ assert(_player == null);
+ _player = player;
+ }
+
+ /// Called when [_player] is connected to the platform.
+ Future<void> _activate(AudioPlayerPlatform platform) async {}
+
+ /// Whether the effect is enabled. When `true`, and if the effect is part
+ /// of an [AudioPipeline] attached to an [AudioPlayer], the effect will modify
+ /// the audio player's output. When `false`, the audio pipeline will still
+ /// reserve platform resources for the effect but the effect will be bypassed.
+ bool get enabled => _enabledSubject.nvalue!;
+
+ /// A stream of the current [enabled] value.
+ Stream<bool> get enabledStream => _enabledSubject.stream;
+
+ bool get _active => _player?._active ?? false;
+
+ String get _type;
+
+ /// Set the [enabled] status of this audio effect.
+ Future<void> setEnabled(bool enabled) async {
+ _enabledSubject.add(enabled);
+ if (_active) {
+ await (await _player!._platform).audioEffectSetEnabled(
+ AudioEffectSetEnabledRequest(type: _type, enabled: enabled));
+ }
+ }
+
+ AudioEffectMessage _toMessage();
+}
+
+/// An [AudioEffect] that supports Android.
+mixin AndroidAudioEffect on AudioEffect {}
+
+/// An [AudioEffect] that supports iOS and macOS.
+mixin DarwinAudioEffect on AudioEffect {}
+
+/// An Android [AudioEffect] that boosts the volume of the audio signal to a
+/// target gain, which defaults to zero.
+class AndroidLoudnessEnhancer extends AudioEffect with AndroidAudioEffect {
+ final _targetGainSubject = BehaviorSubject.seeded(0.0);
+
+ @override
+ String get _type => 'AndroidLoudnessEnhancer';
+
+ /// The target gain in decibels.
+ double get targetGain => _targetGainSubject.nvalue!;
+
+ /// A stream of the current target gain in decibels.
+ Stream<double> get targetGainStream => _targetGainSubject.stream;
+
+ /// Sets the target gain to a value in decibels.
+ Future<void> setTargetGain(double targetGain) async {
+ _targetGainSubject.add(targetGain);
+ if (_active) {
+ await (await _player!._platform).androidLoudnessEnhancerSetTargetGain(
+ AndroidLoudnessEnhancerSetTargetGainRequest(targetGain: targetGain));
+ }
+ }
+
+ @override
+ AudioEffectMessage _toMessage() => AndroidLoudnessEnhancerMessage(
+ enabled: enabled,
+ targetGain: targetGain,
+ );
+}
+
+/// A frequency band within an [AndroidEqualizer].
+class AndroidEqualizerBand {
+ final AudioPlayer _player;
+
+ /// A zero-based index of the position of this band within its [AndroidEqualizer].
+ final int index;
+
+ /// The lower frequency of this band in hertz.
+ final double lowerFrequency;
+
+ /// The upper frequency of this band in hertz.
+ final double upperFrequency;
+
+ /// The center frequency of this band in hertz.
+ final double centerFrequency;
+ final _gainSubject = BehaviorSubject<double>();
+
+ AndroidEqualizerBand._({
+ required AudioPlayer player,
+ required this.index,
+ required this.lowerFrequency,
+ required this.upperFrequency,
+ required this.centerFrequency,
+ required double gain,
+ }) : _player = player {
+ _gainSubject.add(gain);
+ }
+
+ /// The gain for this band in decibels.
+ double get gain => _gainSubject.nvalue!;
+
+ /// A stream of the current gain for this band in decibels.
+ Stream<double> get gainStream => _gainSubject.stream;
+
+ /// Sets the gain for this band in decibels.
+ Future<void> setGain(double gain) async {
+ _gainSubject.add(gain);
+ if (_player._active) {
+ await (await _player._platform).androidEqualizerBandSetGain(
+ AndroidEqualizerBandSetGainRequest(bandIndex: index, gain: gain));
+ }
+ }
+
+ /// Restores the gain after reactivating.
+ Future<void> _restore(AudioPlayerPlatform platform) async {
+ await (platform).androidEqualizerBandSetGain(
+ AndroidEqualizerBandSetGainRequest(bandIndex: index, gain: gain));
+ }
+
+ static AndroidEqualizerBand _fromMessage(
+ AudioPlayer player, AndroidEqualizerBandMessage message) =>
+ AndroidEqualizerBand._(
+ player: player,
+ index: message.index,
+ lowerFrequency: message.lowerFrequency,
+ upperFrequency: message.upperFrequency,
+ centerFrequency: message.centerFrequency,
+ gain: message.gain,
+ );
+}
+
+/// The parameter values of an [AndroidEqualizer].
+class AndroidEqualizerParameters {
+ /// The minimum gain value supported by the equalizer.
+ final double minDecibels;
+
+ /// The maximum gain value supported by the equalizer.
+ final double maxDecibels;
+
+ /// The frequency bands of the equalizer.
+ final List<AndroidEqualizerBand> bands;
+
+ AndroidEqualizerParameters({
+ required this.minDecibels,
+ required this.maxDecibels,
+ required this.bands,
+ });
+
+ /// Restore platform state after reactivating.
+ Future<void> _restore(AudioPlayerPlatform platform) async {
+ for (var band in bands) {
+ await band._restore(platform);
+ }
+ }
+
+ static AndroidEqualizerParameters _fromMessage(
+ AudioPlayer player, AndroidEqualizerParametersMessage message) =>
+ AndroidEqualizerParameters(
+ minDecibels: message.minDecibels,
+ maxDecibels: message.maxDecibels,
+ bands: message.bands
+ .map((bandMessage) =>
+ AndroidEqualizerBand._fromMessage(player, bandMessage))
+ .toList(),
+ );
+}
+
+/// An [AudioEffect] for Android that can adjust the gain for different
+/// frequency bands of an [AudioPlayer]'s audio signal.
+class AndroidEqualizer extends AudioEffect with AndroidAudioEffect {
+ final Completer<AndroidEqualizerParameters> _parametersCompleter =
+ Completer<AndroidEqualizerParameters>();
+
+ @override
+ String get _type => 'AndroidEqualizer';
+
+ @override
+ Future<void> _activate(AudioPlayerPlatform platform) async {
+ await super._activate(platform);
+ if (_parametersCompleter.isCompleted) {
+ await (await parameters)._restore(platform);
+ return;
+ }
+ final response = await platform
+ .androidEqualizerGetParameters(AndroidEqualizerGetParametersRequest());
+ final receivedParameters =
+ AndroidEqualizerParameters._fromMessage(_player!, response.parameters);
+ _parametersCompleter.complete(receivedParameters);
+ }
+
+ /// The parameter values of this equalizer.
+ Future<AndroidEqualizerParameters> get parameters =>
+ _parametersCompleter.future;
+
+ @override
+ AudioEffectMessage _toMessage() => AndroidEqualizerMessage(
+ enabled: enabled,
+ // Parameters are only communicated from the platform.
+ parameters: null,
+ );
+}
+
+bool _isAndroid() => !kIsWeb && Platform.isAndroid;
+bool _isDarwin() => !kIsWeb && (Platform.isIOS || Platform.isMacOS);
+bool _isUnitTest() => !kIsWeb && Platform.environment['FLUTTER_TEST'] == 'true';
+
+/// Backwards compatible extensions on rxdart's ValueStream
+extension _ValueStreamExtension<T> on ValueStream<T> {
+ /// Backwards compatible version of valueOrNull.
+ T? get nvalue => hasValue ? value : null;
+}
+
+/// Information collected when a position discontinuity occurs.
+class PositionDiscontinuity {
+ /// The reason for the position discontinuity.
+ final PositionDiscontinuityReason reason;
+
+ /// The previous event before the position discontinuity.
+ final PlaybackEvent previousEvent;
+
+ /// The event that caused the position discontinuity.
+ final PlaybackEvent event;
+
+ const PositionDiscontinuity(this.reason, this.previousEvent, this.event);
+}
+
+/// The reasons for position discontinuities.
+enum PositionDiscontinuityReason {
+ /// The position discontinuity was initiated by a seek.
+ seek,
+
+ /// The position discontinuity occurred because the player reached the end of
+ /// the current item and auto-advanced to the next item.
+ autoAdvance,
+}
+
+Future<HttpClientRequest> _getUrl(HttpClient client, Uri uri,
+ {Map<String, String>? headers}) async {
+ final request = await client.getUrl(uri);
+ if (headers != null) {
+ final host = request.headers.value(HttpHeaders.hostHeader);
+ request.headers.clear();
+ request.headers.set(HttpHeaders.contentLengthHeader, '0');
+ headers.forEach((name, value) => request.headers.set(name, value));
+ if (host != null) {
+ request.headers.set(HttpHeaders.hostHeader, host);
+ }
+ if (client.userAgent != null) {
+ request.headers.set(HttpHeaders.userAgentHeader, client.userAgent!);
+ }
+ }
+ // Match ExoPlayer's native behavior
+ request.maxRedirects = 20;
+ return request;
+}
+
+HttpClient _createHttpClient({String? userAgent}) {
+ final client = HttpClient();
+ if (userAgent != null) {
+ client.userAgent = userAgent;
+ }
+ return client;
+}
diff --git a/packages/just_audio/pubspec.lock b/packages/just_audio/pubspec.lock
new file mode 100644
index 00000000..6f0468a0
--- /dev/null
+++ b/packages/just_audio/pubspec.lock
@@ -0,0 +1,514 @@
+# Generated by pub
+# See https://dart.dev/tools/pub/glossary#lockfile
+packages:
+ _fe_analyzer_shared:
+ dependency: transitive
+ description:
+ name: _fe_analyzer_shared
+ sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "93.0.0"
+ analyzer:
+ dependency: transitive
+ description:
+ name: analyzer
+ sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b
+ url: "https://pub.dev"
+ source: hosted
+ version: "10.0.1"
+ args:
+ dependency: transitive
+ description:
+ name: args
+ sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.7.0"
+ async:
+ dependency: "direct main"
+ description:
+ name: async
+ sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.13.0"
+ audio_session:
+ dependency: "direct main"
+ description:
+ name: audio_session
+ sha256: "2b7fff16a552486d078bfc09a8cde19f426dc6d6329262b684182597bec5b1ac"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.25"
+ boolean_selector:
+ dependency: transitive
+ description:
+ name: boolean_selector
+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ build:
+ dependency: transitive
+ description:
+ name: build
+ sha256: "275bf6bb2a00a9852c28d4e0b410da1d833a734d57d39d44f94bfc895a484ec3"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.0.4"
+ built_collection:
+ dependency: transitive
+ description:
+ name: built_collection
+ sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100"
+ url: "https://pub.dev"
+ source: hosted
+ version: "5.1.1"
+ built_value:
+ dependency: transitive
+ description:
+ name: built_value
+ sha256: "6ae8a6435a8c6520c7077b107e77f1fb4ba7009633259a4d49a8afd8e7efc5e9"
+ url: "https://pub.dev"
+ source: hosted
+ version: "8.12.4"
+ characters:
+ dependency: transitive
+ description:
+ name: characters
+ sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ clock:
+ dependency: transitive
+ description:
+ name: clock
+ sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.2"
+ code_builder:
+ dependency: transitive
+ description:
+ name: code_builder
+ sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.11.1"
+ collection:
+ dependency: transitive
+ description:
+ name: collection
+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.19.1"
+ convert:
+ dependency: transitive
+ description:
+ name: convert
+ sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.2"
+ crypto:
+ dependency: "direct main"
+ description:
+ name: crypto
+ sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.7"
+ dart_style:
+ dependency: transitive
+ description:
+ name: dart_style
+ sha256: "15a7db352c8fc6a4d2bc475ba901c25b39fe7157541da4c16eacce6f8be83e49"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.5"
+ fake_async:
+ dependency: transitive
+ description:
+ name: fake_async
+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.3"
+ ffi:
+ dependency: transitive
+ description:
+ name: ffi
+ sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ file:
+ dependency: transitive
+ description:
+ name: file
+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.1"
+ fixnum:
+ dependency: transitive
+ description:
+ name: fixnum
+ sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ flutter:
+ dependency: "direct main"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_lints:
+ dependency: "direct dev"
+ description:
+ name: flutter_lints
+ sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.3"
+ flutter_test:
+ dependency: "direct dev"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_web_plugins:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ glob:
+ dependency: transitive
+ description:
+ name: glob
+ sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.3"
+ just_audio_platform_interface:
+ dependency: "direct main"
+ description:
+ name: just_audio_platform_interface
+ sha256: "2532c8d6702528824445921c5ff10548b518b13f808c2e34c2fd54793b999a6a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.6.0"
+ just_audio_web:
+ dependency: "direct main"
+ description:
+ name: just_audio_web
+ sha256: "6ba8a2a7e87d57d32f0f7b42856ade3d6a9fbe0f1a11fabae0a4f00bb73f0663"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.4.16"
+ leak_tracker:
+ dependency: transitive
+ description:
+ name: leak_tracker
+ sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
+ url: "https://pub.dev"
+ source: hosted
+ version: "11.0.2"
+ leak_tracker_flutter_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_flutter_testing
+ sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.10"
+ leak_tracker_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_testing
+ sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.2"
+ lints:
+ dependency: transitive
+ description:
+ name: lints
+ sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.1"
+ logging:
+ dependency: transitive
+ description:
+ name: logging
+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.0"
+ matcher:
+ dependency: transitive
+ description:
+ name: matcher
+ sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.12.18"
+ material_color_utilities:
+ dependency: transitive
+ description:
+ name: material_color_utilities
+ sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.13.0"
+ meta:
+ dependency: "direct main"
+ description:
+ name: meta
+ sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.17.0"
+ mockito:
+ dependency: "direct dev"
+ description:
+ name: mockito
+ sha256: a45d1aa065b796922db7b9e7e7e45f921aed17adf3a8318a1f47097e7e695566
+ url: "https://pub.dev"
+ source: hosted
+ version: "5.6.3"
+ package_config:
+ dependency: transitive
+ description:
+ name: package_config
+ sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ path:
+ dependency: "direct main"
+ description:
+ name: path
+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.9.1"
+ path_provider:
+ dependency: "direct main"
+ description:
+ name: path_provider
+ sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.5"
+ path_provider_android:
+ dependency: transitive
+ description:
+ name: path_provider_android
+ sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.22"
+ path_provider_foundation:
+ dependency: transitive
+ description:
+ name: path_provider_foundation
+ sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.5.1"
+ path_provider_linux:
+ dependency: transitive
+ description:
+ name: path_provider_linux
+ sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.1"
+ path_provider_platform_interface:
+ dependency: transitive
+ description:
+ name: path_provider_platform_interface
+ sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ path_provider_windows:
+ dependency: transitive
+ description:
+ name: path_provider_windows
+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.0"
+ platform:
+ dependency: transitive
+ description:
+ name: platform
+ sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.6"
+ plugin_platform_interface:
+ dependency: "direct dev"
+ description:
+ name: plugin_platform_interface
+ sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.8"
+ pub_semver:
+ dependency: transitive
+ description:
+ name: pub_semver
+ sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ rxdart:
+ dependency: "direct main"
+ description:
+ name: rxdart
+ sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.28.0"
+ sky_engine:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ source_gen:
+ dependency: transitive
+ description:
+ name: source_gen
+ sha256: "1d562a3c1f713904ebbed50d2760217fd8a51ca170ac4b05b0db490699dbac17"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.2.0"
+ source_span:
+ dependency: transitive
+ description:
+ name: source_span
+ sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.10.2"
+ stack_trace:
+ dependency: transitive
+ description:
+ name: stack_trace
+ sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.12.1"
+ stream_channel:
+ dependency: transitive
+ description:
+ name: stream_channel
+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ string_scanner:
+ dependency: transitive
+ description:
+ name: string_scanner
+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ synchronized:
+ dependency: transitive
+ description:
+ name: synchronized
+ sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.4.0"
+ term_glyph:
+ dependency: transitive
+ description:
+ name: term_glyph
+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.2"
+ test_api:
+ dependency: transitive
+ description:
+ name: test_api
+ sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.9"
+ typed_data:
+ dependency: transitive
+ description:
+ name: typed_data
+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.0"
+ uuid:
+ dependency: "direct main"
+ description:
+ name: uuid
+ sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.5.2"
+ vector_math:
+ dependency: transitive
+ description:
+ name: vector_math
+ sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ vm_service:
+ dependency: transitive
+ description:
+ name: vm_service
+ sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
+ url: "https://pub.dev"
+ source: hosted
+ version: "15.0.2"
+ watcher:
+ dependency: transitive
+ description:
+ name: watcher
+ sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.1"
+ web:
+ dependency: transitive
+ description:
+ name: web
+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ xdg_directories:
+ dependency: transitive
+ description:
+ name: xdg_directories
+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.0"
+ yaml:
+ dependency: transitive
+ description:
+ name: yaml
+ sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.3"
+sdks:
+ dart: ">=3.9.0 <4.0.0"
+ flutter: ">=3.35.0"
diff --git a/packages/just_audio/pubspec.yaml b/packages/just_audio/pubspec.yaml
new file mode 100644
index 00000000..69af641f
--- /dev/null
+++ b/packages/just_audio/pubspec.yaml
@@ -0,0 +1,54 @@
+name: just_audio
+description: A feature-rich audio player for Flutter. Loop, clip and concatenate any sound from any source (asset/file/URL/stream) in a variety of audio formats with gapless playback.
+version: 0.9.46
+repository: https://github.com/ryanheise/just_audio/tree/minor/just_audio
+issue_tracker: https://github.com/ryanheise/just_audio/issues
+topics:
+ - audio
+ - sound
+ - player
+ - background
+
+environment:
+ sdk: ">=3.0.0 <4.0.0"
+ flutter: ">=3.10.0"
+
+dependencies:
+ just_audio_platform_interface: ^4.4.0
+ # just_audio_platform_interface:
+ # path: ../just_audio_platform_interface
+ just_audio_web: ^0.4.14
+ # just_audio_web:
+ # path: ../just_audio_web
+ audio_session: ^0.1.24
+ rxdart: '>=0.26.0 <0.29.0'
+ path: ^1.8.0
+ path_provider: ^2.0.0
+ async: ^2.5.0
+ uuid: '>=3.0.1 <5.0.0'
+ crypto: ^3.0.0
+ meta: ^1.3.0
+ flutter:
+ sdk: flutter
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ mockito: ^5.0.0
+ plugin_platform_interface: ^2.0.0
+ flutter_lints: ^2.0.1
+
+flutter:
+ plugin:
+ platforms:
+ android:
+ package: com.ryanheise.just_audio
+ pluginClass: JustAudioPlugin
+ ios:
+ pluginClass: JustAudioPlugin
+ sharedDarwinSource: true
+ macos:
+ pluginClass: JustAudioPlugin
+ sharedDarwinSource: true
+ web:
+ default_package: just_audio_web
diff --git a/pubspec.lock b/pubspec.lock
new file mode 100644
index 00000000..e4d1b54f
--- /dev/null
+++ b/pubspec.lock
@@ -0,0 +1,1097 @@
+# Generated by pub
+# See https://dart.dev/tools/pub/glossary#lockfile
+packages:
+ ansicolor:
+ dependency: transitive
+ description:
+ name: ansicolor
+ sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.3"
+ app_links:
+ dependency: "direct main"
+ description:
+ name: app_links
+ sha256: "5f88447519add627fe1cbcab4fd1da3d4fed15b9baf29f28b22535c95ecee3e8"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.4.1"
+ app_links_linux:
+ dependency: transitive
+ description:
+ name: app_links_linux
+ sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.3"
+ app_links_platform_interface:
+ dependency: transitive
+ description:
+ name: app_links_platform_interface
+ sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.2"
+ app_links_web:
+ dependency: transitive
+ description:
+ name: app_links_web
+ sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.4"
+ archive:
+ dependency: transitive
+ description:
+ name: archive
+ sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.0.9"
+ args:
+ dependency: transitive
+ description:
+ name: args
+ sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.7.0"
+ async:
+ dependency: transitive
+ description:
+ name: async
+ sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.13.0"
+ audio_service:
+ dependency: "direct main"
+ description:
+ name: audio_service
+ sha256: cb122c7c2639d2a992421ef96b67948ad88c5221da3365ccef1031393a76e044
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.18.18"
+ audio_service_platform_interface:
+ dependency: transitive
+ description:
+ name: audio_service_platform_interface
+ sha256: "6283782851f6c8b501b60904a32fc7199dc631172da0629d7301e66f672ab777"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.3"
+ audio_service_web:
+ dependency: transitive
+ description:
+ name: audio_service_web
+ sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.4"
+ audio_session:
+ dependency: "direct main"
+ description:
+ name: audio_session
+ sha256: "2b7fff16a552486d078bfc09a8cde19f426dc6d6329262b684182597bec5b1ac"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.25"
+ boolean_selector:
+ dependency: transitive
+ description:
+ name: boolean_selector
+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ cached_network_image:
+ dependency: "direct main"
+ description:
+ name: cached_network_image
+ sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.4.1"
+ cached_network_image_platform_interface:
+ dependency: transitive
+ description:
+ name: cached_network_image_platform_interface
+ sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.1"
+ cached_network_image_web:
+ dependency: transitive
+ description:
+ name: cached_network_image_web
+ sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.1"
+ change_app_package_name:
+ dependency: "direct dev"
+ description:
+ name: change_app_package_name
+ sha256: "8e43b754fe960426904d77ed4c62fa8c9834deaf6e293ae40963fa447482c4c5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.5.0"
+ characters:
+ dependency: transitive
+ description:
+ name: characters
+ sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ checked_yaml:
+ dependency: transitive
+ description:
+ name: checked_yaml
+ sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.4"
+ cli_util:
+ dependency: transitive
+ description:
+ name: cli_util
+ sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.4.2"
+ clock:
+ dependency: transitive
+ description:
+ name: clock
+ sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.2"
+ collection:
+ dependency: transitive
+ description:
+ name: collection
+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.19.1"
+ connectivity_plus:
+ dependency: "direct main"
+ description:
+ name: connectivity_plus
+ sha256: b5e72753cf63becce2c61fd04dfe0f1c430cc5278b53a1342dc5ad839eab29ec
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.1.5"
+ connectivity_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: connectivity_plus_platform_interface
+ sha256: "42657c1715d48b167930d5f34d00222ac100475f73d10162ddf43e714932f204"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.1"
+ cross_file:
+ dependency: transitive
+ description:
+ name: cross_file
+ sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.3.5+2"
+ crypto:
+ dependency: "direct main"
+ description:
+ name: crypto
+ sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.7"
+ csslib:
+ dependency: transitive
+ description:
+ name: csslib
+ sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.2"
+ dbus:
+ dependency: transitive
+ description:
+ name: dbus
+ sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.12"
+ device_info_plus:
+ dependency: "direct main"
+ description:
+ name: device_info_plus
+ sha256: "98f28b42168cc509abc92f88518882fd58061ea372d7999aecc424345c7bff6a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "11.5.0"
+ device_info_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: device_info_plus_platform_interface
+ sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.3"
+ dynamic_color:
+ dependency: "direct main"
+ description:
+ name: dynamic_color
+ sha256: "43a5a6679649a7731ab860334a5812f2067c2d9ce6452cf069c5e0c25336c17c"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.8.1"
+ fading_edge_scrollview:
+ dependency: transitive
+ description:
+ name: fading_edge_scrollview
+ sha256: "1f84fe3ea8e251d00d5735e27502a6a250e4aa3d3b330d3fdcb475af741464ef"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.1"
+ fake_async:
+ dependency: transitive
+ description:
+ name: fake_async
+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.3"
+ ffi:
+ dependency: transitive
+ description:
+ name: ffi
+ sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ file:
+ dependency: transitive
+ description:
+ name: file
+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.1"
+ file_picker:
+ dependency: "direct main"
+ description:
+ name: file_picker
+ sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810
+ url: "https://pub.dev"
+ source: hosted
+ version: "8.3.7"
+ fixnum:
+ dependency: transitive
+ description:
+ name: fixnum
+ sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ flutter:
+ dependency: "direct main"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_cache_manager:
+ dependency: transitive
+ description:
+ name: flutter_cache_manager
+ sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.4.1"
+ flutter_chrome_cast:
+ dependency: "direct main"
+ description:
+ name: flutter_chrome_cast
+ sha256: "2d87e9dc8c625faaf13fc2c8036ebe6e4675f358e36e646e7d18c18973108279"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ flutter_launcher_icons:
+ dependency: "direct dev"
+ description:
+ name: flutter_launcher_icons
+ sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.14.4"
+ flutter_lints:
+ dependency: "direct dev"
+ description:
+ name: flutter_lints
+ sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.2"
+ flutter_local_notifications:
+ dependency: "direct main"
+ description:
+ name: flutter_local_notifications
+ sha256: "674173fd3c9eda9d4c8528da2ce0ea69f161577495a9cc835a2a4ecd7eadeb35"
+ url: "https://pub.dev"
+ source: hosted
+ version: "17.2.4"
+ flutter_local_notifications_linux:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_linux
+ sha256: c49bd06165cad9beeb79090b18cd1eb0296f4bf4b23b84426e37dd7c027fc3af
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.0.1"
+ flutter_local_notifications_platform_interface:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_platform_interface
+ sha256: "85f8d07fe708c1bdcf45037f2c0109753b26ae077e9d9e899d55971711a4ea66"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.2.0"
+ flutter_native_splash:
+ dependency: "direct dev"
+ description:
+ name: flutter_native_splash
+ sha256: "4fb9f4113350d3a80841ce05ebf1976a36de622af7d19aca0ca9a9911c7ff002"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.7"
+ flutter_plugin_android_lifecycle:
+ dependency: transitive
+ description:
+ name: flutter_plugin_android_lifecycle
+ sha256: ee8068e0e1cd16c4a82714119918efdeed33b3ba7772c54b5d094ab53f9b7fd1
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.33"
+ flutter_test:
+ dependency: "direct dev"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_web_plugins:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ get:
+ dependency: transitive
+ description:
+ name: get
+ sha256: "5ed34a7925b85336e15d472cc4cfe7d9ebf4ab8e8b9f688585bf6b50f4c3d79a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.7.3"
+ gtk:
+ dependency: transitive
+ description:
+ name: gtk
+ sha256: e8ce9ca4b1df106e4d72dad201d345ea1a036cc12c360f1a7d5a758f78ffa42c
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.0"
+ html:
+ dependency: transitive
+ description:
+ name: html
+ sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.15.6"
+ http:
+ dependency: "direct main"
+ description:
+ name: http
+ sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.6.0"
+ http_parser:
+ dependency: transitive
+ description:
+ name: http_parser
+ sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.2"
+ image:
+ dependency: transitive
+ description:
+ name: image
+ sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.8.0"
+ js:
+ dependency: transitive
+ description:
+ name: js
+ sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.2"
+ json_annotation:
+ dependency: transitive
+ description:
+ name: json_annotation
+ sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.11.0"
+ just_audio:
+ dependency: "direct main"
+ description:
+ path: "packages/just_audio"
+ relative: true
+ source: path
+ version: "0.9.46"
+ just_audio_platform_interface:
+ dependency: transitive
+ description:
+ name: just_audio_platform_interface
+ sha256: "2532c8d6702528824445921c5ff10548b518b13f808c2e34c2fd54793b999a6a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.6.0"
+ just_audio_web:
+ dependency: transitive
+ description:
+ name: just_audio_web
+ sha256: "6ba8a2a7e87d57d32f0f7b42856ade3d6a9fbe0f1a11fabae0a4f00bb73f0663"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.4.16"
+ leak_tracker:
+ dependency: transitive
+ description:
+ name: leak_tracker
+ sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
+ url: "https://pub.dev"
+ source: hosted
+ version: "11.0.2"
+ leak_tracker_flutter_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_flutter_testing
+ sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.10"
+ leak_tracker_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_testing
+ sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.2"
+ lints:
+ dependency: transitive
+ description:
+ name: lints
+ sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.0"
+ logging:
+ dependency: transitive
+ description:
+ name: logging
+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.0"
+ marquee:
+ dependency: transitive
+ description:
+ name: marquee
+ sha256: a87e7e80c5d21434f90ad92add9f820cf68be374b226404fe881d2bba7be0862
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.0"
+ matcher:
+ dependency: transitive
+ description:
+ name: matcher
+ sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.12.18"
+ material_color_utilities:
+ dependency: transitive
+ description:
+ name: material_color_utilities
+ sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.13.0"
+ material_design_icons_flutter:
+ dependency: "direct main"
+ description:
+ name: material_design_icons_flutter
+ sha256: "6f986b7a51f3ad4c00e33c5c84e8de1bdd140489bbcdc8b66fc1283dad4dea5a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.7296"
+ meta:
+ dependency: transitive
+ description:
+ name: meta
+ sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.17.0"
+ nested:
+ dependency: transitive
+ description:
+ name: nested
+ sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.0"
+ nm:
+ dependency: transitive
+ description:
+ name: nm
+ sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.5.0"
+ octo_image:
+ dependency: transitive
+ description:
+ name: octo_image
+ sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.0"
+ open_filex:
+ dependency: "direct main"
+ description:
+ name: open_filex
+ sha256: "9976da61b6a72302cf3b1efbce259200cd40232643a467aac7370addf94d6900"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.7.0"
+ package_info_plus:
+ dependency: "direct main"
+ description:
+ name: package_info_plus
+ sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968"
+ url: "https://pub.dev"
+ source: hosted
+ version: "8.3.1"
+ package_info_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: package_info_plus_platform_interface
+ sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.2.1"
+ path:
+ dependency: transitive
+ description:
+ name: path
+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.9.1"
+ path_provider:
+ dependency: "direct main"
+ description:
+ name: path_provider
+ sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.5"
+ path_provider_android:
+ dependency: transitive
+ description:
+ name: path_provider_android
+ sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.22"
+ path_provider_foundation:
+ dependency: transitive
+ description:
+ name: path_provider_foundation
+ sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.5.1"
+ path_provider_linux:
+ dependency: transitive
+ description:
+ name: path_provider_linux
+ sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.1"
+ path_provider_platform_interface:
+ dependency: transitive
+ description:
+ name: path_provider_platform_interface
+ sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ path_provider_windows:
+ dependency: transitive
+ description:
+ name: path_provider_windows
+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.0"
+ permission_handler:
+ dependency: "direct main"
+ description:
+ name: permission_handler
+ sha256: bc917da36261b00137bbc8896bf1482169cd76f866282368948f032c8c1caae1
+ url: "https://pub.dev"
+ source: hosted
+ version: "12.0.1"
+ permission_handler_android:
+ dependency: transitive
+ description:
+ name: permission_handler_android
+ sha256: "1e3bc410ca1bf84662104b100eb126e066cb55791b7451307f9708d4007350e6"
+ url: "https://pub.dev"
+ source: hosted
+ version: "13.0.1"
+ permission_handler_apple:
+ dependency: transitive
+ description:
+ name: permission_handler_apple
+ sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023
+ url: "https://pub.dev"
+ source: hosted
+ version: "9.4.7"
+ permission_handler_html:
+ dependency: transitive
+ description:
+ name: permission_handler_html
+ sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.3+5"
+ permission_handler_platform_interface:
+ dependency: transitive
+ description:
+ name: permission_handler_platform_interface
+ sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.3.0"
+ permission_handler_windows:
+ dependency: transitive
+ description:
+ name: permission_handler_windows
+ sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.2.1"
+ petitparser:
+ dependency: transitive
+ description:
+ name: petitparser
+ sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.2"
+ platform:
+ dependency: transitive
+ description:
+ name: platform
+ sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.6"
+ plugin_platform_interface:
+ dependency: transitive
+ description:
+ name: plugin_platform_interface
+ sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.8"
+ posix:
+ dependency: transitive
+ description:
+ name: posix
+ sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.0.3"
+ provider:
+ dependency: "direct main"
+ description:
+ name: provider
+ sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.1.5+1"
+ rename_app:
+ dependency: "direct dev"
+ description:
+ name: rename_app
+ sha256: "387a88335f853674b39bed7943955388bbaf6aae4ffdc812e2ef275ce119abc7"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.6.5"
+ rxdart:
+ dependency: transitive
+ description:
+ name: rxdart
+ sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.28.0"
+ sensors_plus:
+ dependency: "direct main"
+ description:
+ name: sensors_plus
+ sha256: "8e7fa79b4940442bb595bfc0ee9da4af5a22a0fe6ebacc74998245ee9496a82d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.0.2"
+ sensors_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: sensors_plus_platform_interface
+ sha256: bc472d6cfd622acb4f020e726433ee31788b038056691ba433fec80e448a094f
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.0"
+ shared_preferences:
+ dependency: "direct main"
+ description:
+ name: shared_preferences
+ sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.5.4"
+ shared_preferences_android:
+ dependency: transitive
+ description:
+ name: shared_preferences_android
+ sha256: cbc40be9be1c5af4dab4d6e0de4d5d3729e6f3d65b89d21e1815d57705644a6f
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.20"
+ shared_preferences_foundation:
+ dependency: transitive
+ description:
+ name: shared_preferences_foundation
+ sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.5.6"
+ shared_preferences_linux:
+ dependency: transitive
+ description:
+ name: shared_preferences_linux
+ sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.1"
+ shared_preferences_platform_interface:
+ dependency: transitive
+ description:
+ name: shared_preferences_platform_interface
+ sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.1"
+ shared_preferences_web:
+ dependency: transitive
+ description:
+ name: shared_preferences_web
+ sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.3"
+ shared_preferences_windows:
+ dependency: transitive
+ description:
+ name: shared_preferences_windows
+ sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.1"
+ sky_engine:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ source_span:
+ dependency: transitive
+ description:
+ name: source_span
+ sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.10.2"
+ sqflite:
+ dependency: transitive
+ description:
+ name: sqflite
+ sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.2"
+ sqflite_android:
+ dependency: transitive
+ description:
+ name: sqflite_android
+ sha256: ecd684501ebc2ae9a83536e8b15731642b9570dc8623e0073d227d0ee2bfea88
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.2+2"
+ sqflite_common:
+ dependency: transitive
+ description:
+ name: sqflite_common
+ sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.5.6"
+ sqflite_darwin:
+ dependency: transitive
+ description:
+ name: sqflite_darwin
+ sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.2"
+ sqflite_platform_interface:
+ dependency: transitive
+ description:
+ name: sqflite_platform_interface
+ sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.0"
+ stack_trace:
+ dependency: transitive
+ description:
+ name: stack_trace
+ sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.12.1"
+ stream_channel:
+ dependency: transitive
+ description:
+ name: stream_channel
+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ string_scanner:
+ dependency: transitive
+ description:
+ name: string_scanner
+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ synchronized:
+ dependency: transitive
+ description:
+ name: synchronized
+ sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.4.0"
+ term_glyph:
+ dependency: transitive
+ description:
+ name: term_glyph
+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.2"
+ test_api:
+ dependency: transitive
+ description:
+ name: test_api
+ sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.9"
+ timezone:
+ dependency: transitive
+ description:
+ name: timezone
+ sha256: "2236ec079a174ce07434e89fcd3fcda430025eb7692244139a9cf54fdcf1fc7d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.4"
+ typed_data:
+ dependency: transitive
+ description:
+ name: typed_data
+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.0"
+ universal_io:
+ dependency: transitive
+ description:
+ name: universal_io
+ sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.1"
+ url_launcher:
+ dependency: "direct main"
+ description:
+ name: url_launcher
+ sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.3.2"
+ url_launcher_android:
+ dependency: transitive
+ description:
+ name: url_launcher_android
+ sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.3.28"
+ url_launcher_ios:
+ dependency: transitive
+ description:
+ name: url_launcher_ios
+ sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.4.1"
+ url_launcher_linux:
+ dependency: transitive
+ description:
+ name: url_launcher_linux
+ sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.2.2"
+ url_launcher_macos:
+ dependency: transitive
+ description:
+ name: url_launcher_macos
+ sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.2.5"
+ url_launcher_platform_interface:
+ dependency: transitive
+ description:
+ name: url_launcher_platform_interface
+ sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.2"
+ url_launcher_web:
+ dependency: transitive
+ description:
+ name: url_launcher_web
+ sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.2"
+ url_launcher_windows:
+ dependency: transitive
+ description:
+ name: url_launcher_windows
+ sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.5"
+ uuid:
+ dependency: transitive
+ description:
+ name: uuid
+ sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.5.2"
+ vector_math:
+ dependency: transitive
+ description:
+ name: vector_math
+ sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ vm_service:
+ dependency: transitive
+ description:
+ name: vm_service
+ sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
+ url: "https://pub.dev"
+ source: hosted
+ version: "15.0.2"
+ web:
+ dependency: transitive
+ description:
+ name: web
+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ win32:
+ dependency: transitive
+ description:
+ name: win32
+ sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
+ url: "https://pub.dev"
+ source: hosted
+ version: "5.15.0"
+ win32_registry:
+ dependency: transitive
+ description:
+ name: win32_registry
+ sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.0"
+ xdg_directories:
+ dependency: transitive
+ description:
+ name: xdg_directories
+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.0"
+ xml:
+ dependency: transitive
+ description:
+ name: xml
+ sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.6.1"
+ yaml:
+ dependency: transitive
+ description:
+ name: yaml
+ sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.3"
+sdks:
+ dart: ">=3.10.0 <4.0.0"
+ flutter: ">=3.38.0"
diff --git a/pubspec.yaml b/pubspec.yaml
new file mode 100644
index 00000000..c97277f0
--- /dev/null
+++ b/pubspec.yaml
@@ -0,0 +1,96 @@
+name: absorb
+description: A Material 3 Audiobookshelf client for Android.
+publish_to: 'none'
+version: 1.6.0+25
+
+environment:
+ sdk: '>=3.1.0 <4.0.0'
+
+dependencies:
+ flutter:
+ sdk: flutter
+
+ # Networking
+ http: ^1.1.0
+
+ # State Management
+ provider: ^6.1.1
+
+ # Storage
+ shared_preferences: ^2.2.2
+
+ # Dynamic Color (Material You)
+ dynamic_color: ^1.6.8
+
+ # Image caching
+ cached_network_image: ^3.3.0
+
+ # Icons
+ material_design_icons_flutter: ^7.0.7296
+
+ # Audio playback
+ just_audio:
+ path: packages/just_audio
+
+ audio_service: ^0.18.13
+
+ # Permissions
+ permission_handler: ^12.0.1
+
+ # Downloads & offline
+ path_provider: ^2.1.1
+ connectivity_plus: ^6.0.3
+
+ # Shake detection for sleep timer
+ sensors_plus: ^4.0.2
+
+ # Download notifications
+ flutter_local_notifications: ^17.2.1
+
+ device_info_plus: ^11.0.0
+
+ # choose file location
+ file_picker: ^8.0.0
+
+ package_info_plus: ^8.0.0
+
+ #OIDC
+ crypto: ^3.0.3
+ url_launcher: ^6.2.5
+ app_links: ^6.1.1
+
+ # Pausing for interruptions
+ audio_session: ^0.1.21
+
+ # Open filex to share epub files
+ open_filex: ^4.5.0
+
+ # chromecast
+ flutter_chrome_cast: ^1.2.6
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ flutter_lints: ^3.0.1
+ flutter_launcher_icons: ^0.14.3
+ flutter_native_splash: ^2.4.4
+ change_app_package_name: ^1.5.0
+ rename_app: ^1.6.5
+
+flutter:
+ uses-material-design: true
+ assets:
+ - assets/icon/
+
+flutter_launcher_icons:
+ android: true
+ image_path: "assets/icon/app_icon.png"
+ adaptive_icon_background: "#000000"
+ adaptive_icon_foreground: "assets/icon/app_icon_foreground.png"
+
+flutter_native_splash:
+ color: "#000000"
+ image: "assets/icon/splash_logo.png"
+ android_12:
+ color: "#000000"
+ image: "assets/icon/splash_logo.png"
diff --git a/screenshots/absorbing.png b/screenshots/absorbing.png
new file mode 100644
index 00000000..7301d52e
Binary files /dev/null and b/screenshots/absorbing.png differ
diff --git a/screenshots/details.png b/screenshots/details.png
new file mode 100644
index 00000000..4b4abdae
Binary files /dev/null and b/screenshots/details.png differ
diff --git a/screenshots/library.png b/screenshots/library.png
new file mode 100644
index 00000000..5f535ef1
Binary files /dev/null and b/screenshots/library.png differ
diff --git a/screenshots/stats.png b/screenshots/stats.png
new file mode 100644
index 00000000..87171dbc
Binary files /dev/null and b/screenshots/stats.png differ