Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Backup and restore update, plus REAL in-app updater fixed

Barnabas62047c171104
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 038eba05..dfc4ffd4 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -10,12 +10,15 @@
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<!-- External storage write access (Android 9 and below) -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" tools:replace="android:maxSdkVersion"/>
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" tools:replace="android:maxSdkVersion"/>
<!-- Full file access for custom download locations (Android 11+) -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
+ <!-- In-app APK updater (GitHub flavor only; stripped from Play Store build) -->
+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
+
<!-- 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"/>
diff --git a/android/app/src/playstore/AndroidManifest.xml b/android/app/src/playstore/AndroidManifest.xml
index fefb445f..f9d7f087 100644
--- a/android/app/src/playstore/AndroidManifest.xml
+++ b/android/app/src/playstore/AndroidManifest.xml
@@ -4,4 +4,7 @@
<!-- Remove MANAGE_EXTERNAL_STORAGE for Play Store compliance -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:node="remove"/>
+ <!-- Remove APK installer permission: Play Store flavor never sideloads -->
+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove"/>
+
</manifest>
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 4bf253a1..3a888835 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -26,7 +26,7 @@ import 'stats_screen.dart';
import 'settings_screen.dart';
import '../widgets/welcome_sheet.dart';
import '../services/update_checker_service.dart';
-import 'package:url_launcher/url_launcher.dart';
+import '../widgets/update_dialog.dart';
class AppShell extends StatefulWidget {
const AppShell({super.key});
@@ -331,34 +331,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
final includePreReleases = await PlayerSettings.getIncludePreReleases();
final info = await UpdateCheckerService.check(includePreReleases: includePreReleases);
if (info == null || !mounted) return;
- final l = AppLocalizations.of(context)!;
- showDialog(
- context: context,
- builder: (ctx) => AlertDialog(
- title: Text(info.isPreRelease ? l.preReleaseAvailable : l.updateAvailable),
- content: Text(l.updateDialogContent(
- info.isPreRelease ? l.updateKindPreRelease : l.updateKindVersion,
- info.latestVersion,
- info.currentVersion,
- )),
- actions: [
- TextButton(
- onPressed: () {
- UpdateCheckerService.dismiss(info.latestVersion);
- Navigator.pop(ctx);
- },
- child: Text(l.later),
- ),
- FilledButton(
- onPressed: () {
- Navigator.pop(ctx);
- launchUrl(Uri.parse(info.downloadUrl), mode: LaunchMode.externalApplication);
- },
- child: Text(l.downloadButton),
- ),
- ],
- ),
- );
+ await UpdateDialog.show(context, info);
}
@override
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 2b9d5b41..c57e1dd9 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -20,6 +20,7 @@ import '../services/scoped_prefs.dart';
import '../screens/login_screen.dart';
import '../screens/app_shell.dart';
import '../services/update_checker_service.dart';
+import '../widgets/update_dialog.dart';
import '../screens/admin_screen.dart';
import '../screens/downloads_screen.dart';
import '../screens/bookmarks_screen.dart';
@@ -2393,30 +2394,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
return;
}
- showDialog(
- context: context,
- builder: (ctx) => AlertDialog(
- title: Text(info.isPreRelease ? l.preReleaseAvailable : l.updateAvailable),
- content: Text(l.updateDialogContent(
- info.isPreRelease ? l.updateKindPreRelease : l.updateKindVersion,
- info.latestVersion,
- info.currentVersion,
- )),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(ctx),
- child: Text(l.later),
- ),
- FilledButton(
- onPressed: () {
- Navigator.pop(ctx);
- launchUrl(Uri.parse(info.downloadUrl), mode: LaunchMode.externalApplication);
- },
- child: Text(l.downloadButton),
- ),
- ],
- ),
- );
+ await UpdateDialog.show(context, info);
},
icon: const Icon(Icons.system_update_rounded, size: 16),
label: Text(l.checkForUpdate),
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index ce72234e..aa70be7c 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -81,6 +81,22 @@ class BackupService {
'sheetGridView': await PlayerSettings.getSheetGridView(),
'sheetCollapseSeries': await PlayerSettings.getSheetCollapseSeries(),
'skipChapterBarrier': await PlayerSettings.getSkipChapterBarrier(),
+ 'audibleRegion': await PlayerSettings.getAudibleRegion(),
+ 'upcomingReleasesSortByDate': await PlayerSettings.getUpcomingReleasesSortByDate(),
+ 'libraryTagFilter': await PlayerSettings.getLibraryTagFilter(),
+ 'librarySeriesFilter': await PlayerSettings.getLibrarySeriesFilter(),
+ 'narratorSort': await PlayerSettings.getNarratorSort(),
+ 'narratorSortAsc': await PlayerSettings.getNarratorSortAsc(),
+ 'classicWording': await PlayerSettings.getClassicWording(),
+ 'sectionGridView': await PlayerSettings.getSectionGridView(),
+ 'collapseBookSeries': await PlayerSettings.getCollapseBookSeries(),
+ 'showExplicitBadge': await PlayerSettings.getShowExplicitBadge(),
+ 'includePreReleases': await PlayerSettings.getIncludePreReleases(),
+ 'language': await PlayerSettings.getLanguage(),
+ 'showUpNextLabel': await PlayerSettings.getShowUpNextLabel(),
+ 'queuePlaylistId': await PlayerSettings.getQueuePlaylistId(),
+ 'coverSeedColor': await PlayerSettings.getCoverSeedColor(),
+ 'speedPresets': await PlayerSettings.getSpeedPresets(),
};
// AutoRewind (scoped)
@@ -113,6 +129,9 @@ class BackupService {
'virtualizer': await ScopedPrefs.getDouble('eq_virtualizer') ?? 0.0,
'loudnessGain': await ScopedPrefs.getDouble('eq_loudnessGain') ?? 0.0,
'bands': await ScopedPrefs.getString('eq_bands'),
+ 'mono': await ScopedPrefs.getBool('eq_mono') ?? false,
+ 'skipSilence': await ScopedPrefs.getBool('eq_skipSilence') ?? false,
+ 'perItem': await ScopedPrefs.getBool('eq_perItem') ?? false,
};
// Per-book speeds (scoped - scan scoped keys)
@@ -158,6 +177,80 @@ class BackupService {
// Rolling download series (scoped)
final rollingDownloadSeries = await ScopedPrefs.getStringList('rolling_download_series');
+ // Podcast subscriptions + manually-curated Absorbing list (scoped)
+ final subscribedPodcasts = await ScopedPrefs.getStringList('subscribed_podcasts');
+ final absorbingManualAdds = await ScopedPrefs.getStringList('absorbing_manual_adds');
+ final absorbingManualRemoves = await ScopedPrefs.getStringList('absorbing_manual_removes');
+
+ // Pending offline state (scoped) - server hasn't received these yet
+ final pendingSyncs = await ScopedPrefs.getStringList('pending_syncs');
+ final pendingOfflineListening = await ScopedPrefs.getStringList('pending_offline_listening');
+ final bookmarksPendingCreates = await ScopedPrefs.getString('bookmarks_pending_creates');
+ final bookmarksPendingDeletes = await ScopedPrefs.getString('bookmarks_pending_deletes');
+
+ // Offline listening accumulators (scoped) - keyed by itemId
+ final offlineListening = <String, int>{};
+ final offlinePrefix = scope.isNotEmpty ? '$scope:offline_listening_' : 'offline_listening_';
+ for (final key in prefs.getKeys()) {
+ if (key.startsWith(offlinePrefix)) {
+ final itemId = key.substring(offlinePrefix.length);
+ final seconds = prefs.getInt(key);
+ if (seconds != null && seconds > 0) offlineListening[itemId] = seconds;
+ }
+ }
+
+ // RMAB integration config (scoped)
+ final rmab = <String, dynamic>{
+ 'baseUrl': await ScopedPrefs.getString('rmab_base_url'),
+ 'apiToken': await ScopedPrefs.getString('rmab_api_token'),
+ 'legacyUrl': await ScopedPrefs.getString('rmab_url'),
+ };
+
+ // Home screen layout per library (scoped, keyed by libraryId)
+ final homeLayouts = <String, Map<String, List<String>>>{};
+ final scopePrefix = scope.isNotEmpty ? '$scope:' : '';
+ void collectHome(String shortPrefix, String bucket) {
+ final fullPrefix = '$scopePrefix$shortPrefix';
+ for (final key in prefs.getKeys()) {
+ if (!key.startsWith(fullPrefix)) continue;
+ final libId = key.substring(fullPrefix.length);
+ final list = prefs.getStringList(key);
+ if (list == null) continue;
+ homeLayouts.putIfAbsent(libId, () => {})[bucket] = list;
+ }
+ }
+ collectHome('home_section_order_', 'order');
+ collectHome('home_hidden_sections_', 'hidden');
+ collectHome('home_genre_sections_', 'genres');
+
+ // Per-item metadata overrides (scoped, keyed by itemId)
+ final metadataOverrides = <String, String>{};
+ final metaPrefix = '${scopePrefix}metadata_override_';
+ for (final key in prefs.getKeys()) {
+ if (!key.startsWith(metaPrefix)) continue;
+ final itemId = key.substring(metaPrefix.length);
+ final value = prefs.getString(key);
+ if (value != null && value.isNotEmpty) metadataOverrides[itemId] = value;
+ }
+
+ // Per-podcast UI prefs (GLOBAL, not scoped - keyed by itemId)
+ final podcastPrefs = <String, Map<String, dynamic>>{};
+ void collectPodcast(String prefix, String bucket, Object? Function(String) read) {
+ for (final key in prefs.getKeys()) {
+ if (!key.startsWith(prefix)) continue;
+ final itemId = key.substring(prefix.length);
+ final value = read(key);
+ if (value == null) continue;
+ podcastPrefs.putIfAbsent(itemId, () => {})[bucket] = value;
+ }
+ }
+ collectPodcast('podcast_sort_newest_', 'sortNewest', (k) => prefs.getBool(k));
+ collectPodcast('podcast_hide_finished_', 'hideFinished', (k) => prefs.getBool(k));
+ collectPodcast('podcast_advance_dir_', 'advanceDir', (k) => prefs.getString(k));
+
+ // Custom download path (GLOBAL)
+ final customDownloadPath = prefs.getString('custom_download_path');
+
// Accounts & custom headers (optional - contain auth data)
List<Map<String, dynamic>>? accounts;
Map<String, String>? customHeaders;
@@ -175,7 +268,7 @@ class BackupService {
}
return {
- 'version': 2,
+ 'version': 3,
'createdAt': DateTime.now().toIso8601String(),
'appVersion': pkgInfo.version,
'settings': settings,
@@ -188,6 +281,19 @@ class BackupService {
'notes': notes,
'savedEbooks': savedEbooks,
'rollingDownloadSeries': rollingDownloadSeries,
+ 'subscribedPodcasts': subscribedPodcasts,
+ 'absorbingManualAdds': absorbingManualAdds,
+ 'absorbingManualRemoves': absorbingManualRemoves,
+ 'pendingSyncs': pendingSyncs,
+ 'pendingOfflineListening': pendingOfflineListening,
+ 'bookmarksPendingCreates': bookmarksPendingCreates,
+ 'bookmarksPendingDeletes': bookmarksPendingDeletes,
+ 'offlineListening': offlineListening,
+ 'rmab': rmab,
+ 'homeLayouts': homeLayouts,
+ 'metadataOverrides': metadataOverrides,
+ 'podcastPrefs': podcastPrefs,
+ 'customDownloadPath': customDownloadPath,
'accounts': accounts,
'customHeaders': customHeaders,
};
@@ -292,6 +398,24 @@ class BackupService {
if (s['sheetGridView'] != null) PlayerSettings.setSheetGridView(s['sheetGridView'] as bool);
if (s['sheetCollapseSeries'] != null) PlayerSettings.setSheetCollapseSeries(s['sheetCollapseSeries'] as bool);
if (s['skipChapterBarrier'] != null) PlayerSettings.setSkipChapterBarrier(s['skipChapterBarrier'] as bool);
+ if (s['audibleRegion'] != null) await PlayerSettings.setAudibleRegion(s['audibleRegion'] as String);
+ if (s['upcomingReleasesSortByDate'] != null) await PlayerSettings.setUpcomingReleasesSortByDate(s['upcomingReleasesSortByDate'] as bool);
+ if (s['libraryTagFilter'] != null) await PlayerSettings.setLibraryTagFilter(s['libraryTagFilter'] as String);
+ if (s['librarySeriesFilter'] != null) await PlayerSettings.setLibrarySeriesFilter(s['librarySeriesFilter'] as String);
+ if (s['narratorSort'] != null) await PlayerSettings.setNarratorSort(s['narratorSort'] as String);
+ if (s['narratorSortAsc'] != null) await PlayerSettings.setNarratorSortAsc(s['narratorSortAsc'] as bool);
+ if (s['classicWording'] != null) await PlayerSettings.setClassicWording(s['classicWording'] as bool);
+ if (s['sectionGridView'] != null) await PlayerSettings.setSectionGridView(s['sectionGridView'] as bool);
+ if (s['collapseBookSeries'] != null) await PlayerSettings.setCollapseBookSeries(s['collapseBookSeries'] as bool);
+ if (s['showExplicitBadge'] != null) await PlayerSettings.setShowExplicitBadge(s['showExplicitBadge'] as bool);
+ if (s['includePreReleases'] != null) await PlayerSettings.setIncludePreReleases(s['includePreReleases'] as bool);
+ if (s['language'] != null) await PlayerSettings.setLanguage(s['language'] as String);
+ if (s['showUpNextLabel'] != null) await PlayerSettings.setShowUpNextLabel(s['showUpNextLabel'] as bool);
+ if (s['queuePlaylistId'] != null) await PlayerSettings.setQueuePlaylistId(s['queuePlaylistId'] as String?);
+ if (s['coverSeedColor'] != null) await PlayerSettings.setCoverSeedColor(s['coverSeedColor'] as int);
+ if (s['speedPresets'] is List) {
+ await PlayerSettings.setSpeedPresets((s['speedPresets'] as List).map((e) => (e as num).toDouble()).toList());
+ }
// AutoRewind (scoped via save())
final r = data['autoRewind'] as Map<String, dynamic>?;
@@ -330,6 +454,9 @@ class BackupService {
if (eq['bands'] != null) {
await ScopedPrefs.setString('eq_bands', eq['bands'] as String);
}
+ if (eq['mono'] != null) await ScopedPrefs.setBool('eq_mono', eq['mono'] as bool);
+ if (eq['skipSilence'] != null) await ScopedPrefs.setBool('eq_skipSilence', eq['skipSilence'] as bool);
+ if (eq['perItem'] != null) await ScopedPrefs.setBool('eq_perItem', eq['perItem'] as bool);
}
// Per-book speeds (scoped)
@@ -377,5 +504,95 @@ class BackupService {
);
}
+ // Podcast subscriptions + Absorbing manual list (scoped)
+ final subscribedPodcasts = data['subscribedPodcasts'] as List<dynamic>?;
+ if (subscribedPodcasts != null) {
+ await ScopedPrefs.setStringList('subscribed_podcasts', subscribedPodcasts.cast<String>());
+ }
+ final absorbingManualAdds = data['absorbingManualAdds'] as List<dynamic>?;
+ if (absorbingManualAdds != null) {
+ await ScopedPrefs.setStringList('absorbing_manual_adds', absorbingManualAdds.cast<String>());
+ }
+ final absorbingManualRemoves = data['absorbingManualRemoves'] as List<dynamic>?;
+ if (absorbingManualRemoves != null) {
+ await ScopedPrefs.setStringList('absorbing_manual_removes', absorbingManualRemoves.cast<String>());
+ }
+
+ // Pending offline state (scoped) - so offline changes still push after restore
+ final pendingSyncs = data['pendingSyncs'] as List<dynamic>?;
+ if (pendingSyncs != null && pendingSyncs.isNotEmpty) {
+ await ScopedPrefs.setStringList('pending_syncs', pendingSyncs.cast<String>());
+ }
+ final pendingOfflineListening = data['pendingOfflineListening'] as List<dynamic>?;
+ if (pendingOfflineListening != null && pendingOfflineListening.isNotEmpty) {
+ await ScopedPrefs.setStringList('pending_offline_listening', pendingOfflineListening.cast<String>());
+ }
+ final bmpc = data['bookmarksPendingCreates'] as String?;
+ if (bmpc != null) await ScopedPrefs.setString('bookmarks_pending_creates', bmpc);
+ final bmpd = data['bookmarksPendingDeletes'] as String?;
+ if (bmpd != null) await ScopedPrefs.setString('bookmarks_pending_deletes', bmpd);
+
+ // Offline listening accumulators (scoped, per-item) - write through SharedPreferences
+ // directly because ScopedPrefs doesn't expose setInt with scope handling here.
+ final offlineListening = data['offlineListening'] as Map<String, dynamic>?;
+ if (offlineListening != null && offlineListening.isNotEmpty) {
+ final scope = UserAccountService().activeScopeKey;
+ final prefix = scope.isNotEmpty ? '$scope:offline_listening_' : 'offline_listening_';
+ for (final entry in offlineListening.entries) {
+ await prefs.setInt('$prefix${entry.key}', (entry.value as num).toInt());
+ }
+ }
+
+ // RMAB integration config (scoped)
+ final rmab = data['rmab'] as Map<String, dynamic>?;
+ if (rmab != null) {
+ final baseUrl = rmab['baseUrl'] as String?;
+ if (baseUrl != null) await ScopedPrefs.setString('rmab_base_url', baseUrl);
+ final apiToken = rmab['apiToken'] as String?;
+ if (apiToken != null) await ScopedPrefs.setString('rmab_api_token', apiToken);
+ final legacyUrl = rmab['legacyUrl'] as String?;
+ if (legacyUrl != null) await ScopedPrefs.setString('rmab_url', legacyUrl);
+ }
+
+ // Home screen layout per library (scoped)
+ final homeLayouts = data['homeLayouts'] as Map<String, dynamic>?;
+ if (homeLayouts != null) {
+ for (final entry in homeLayouts.entries) {
+ final libId = entry.key;
+ final layout = entry.value as Map<String, dynamic>;
+ final order = layout['order'] as List<dynamic>?;
+ final hidden = layout['hidden'] as List<dynamic>?;
+ final genres = layout['genres'] as List<dynamic>?;
+ if (order != null) await ScopedPrefs.setStringList('home_section_order_$libId', order.cast<String>());
+ if (hidden != null) await ScopedPrefs.setStringList('home_hidden_sections_$libId', hidden.cast<String>());
+ if (genres != null) await ScopedPrefs.setStringList('home_genre_sections_$libId', genres.cast<String>());
+ }
+ }
+
+ // Per-item metadata overrides (scoped)
+ final metadataOverrides = data['metadataOverrides'] as Map<String, dynamic>?;
+ if (metadataOverrides != null) {
+ for (final entry in metadataOverrides.entries) {
+ await ScopedPrefs.setString('metadata_override_${entry.key}', entry.value as String);
+ }
+ }
+
+ // Per-podcast UI prefs (GLOBAL, not scoped)
+ final podcastPrefs = data['podcastPrefs'] as Map<String, dynamic>?;
+ if (podcastPrefs != null) {
+ for (final entry in podcastPrefs.entries) {
+ final itemId = entry.key;
+ final p = entry.value as Map<String, dynamic>;
+ if (p['sortNewest'] != null) await prefs.setBool('podcast_sort_newest_$itemId', p['sortNewest'] as bool);
+ if (p['hideFinished'] != null) await prefs.setBool('podcast_hide_finished_$itemId', p['hideFinished'] as bool);
+ if (p['advanceDir'] != null) await prefs.setString('podcast_advance_dir_$itemId', p['advanceDir'] as String);
+ }
+ }
+
+ // Custom download path (GLOBAL)
+ final customDownloadPath = data['customDownloadPath'] as String?;
+ if (customDownloadPath != null) {
+ await prefs.setString('custom_download_path', customDownloadPath);
+ }
}
}
diff --git a/lib/services/update_checker_service.dart b/lib/services/update_checker_service.dart
index 7f94fb25..1e6123be 100644
--- a/lib/services/update_checker_service.dart
+++ b/lib/services/update_checker_service.dart
@@ -1,7 +1,12 @@
+import 'dart:async';
import 'dart:convert';
+import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
+import 'package:open_filex/open_filex.dart';
import 'package:package_info_plus/package_info_plus.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
class UpdateInfo {
@@ -124,3 +129,109 @@ class UpdateCheckerService {
await prefs.setString(_dismissedKey, version);
}
}
+
+enum ApkInstallStatus {
+ ok,
+ downloadFailed,
+ permissionDenied,
+ launchFailed,
+ cancelled,
+}
+
+class ApkInstallResult {
+ final ApkInstallStatus status;
+ final String? message;
+ const ApkInstallResult(this.status, [this.message]);
+}
+
+/// Downloads the APK in-app and hands it to the system installer.
+///
+/// Why: launching the URL in a browser leaves Chrome holding the APK in its
+/// SafeBrowsing "scanning" limbo - the download bar hits 100% and never
+/// finalises. Pulling the bytes ourselves and opening the file with
+/// open_filex bypasses the browser entirely.
+class ApkUpdater {
+ static http.Client? _activeClient;
+
+ static Future<ApkInstallResult> downloadAndInstall(
+ UpdateInfo info, {
+ required void Function(int received, int total) onProgress,
+ }) async {
+ if (!Platform.isAndroid) {
+ return const ApkInstallResult(ApkInstallStatus.launchFailed, 'Android only');
+ }
+
+ final perm = await Permission.requestInstallPackages.request();
+ if (!perm.isGranted) {
+ return const ApkInstallResult(ApkInstallStatus.permissionDenied);
+ }
+
+ final File file;
+ try {
+ file = await _download(info, onProgress);
+ } on _CancelledException {
+ return const ApkInstallResult(ApkInstallStatus.cancelled);
+ } catch (e) {
+ debugPrint('[ApkUpdater] Download failed: $e');
+ return ApkInstallResult(ApkInstallStatus.downloadFailed, e.toString());
+ }
+
+ final result = await OpenFilex.open(file.path, type: 'application/vnd.android.package-archive');
+ if (result.type != ResultType.done) {
+ debugPrint('[ApkUpdater] OpenFilex failed: ${result.type} ${result.message}');
+ return ApkInstallResult(ApkInstallStatus.launchFailed, result.message);
+ }
+ return const ApkInstallResult(ApkInstallStatus.ok);
+ }
+
+ /// Cancel an in-flight download started by [downloadAndInstall].
+ static void cancel() {
+ _activeClient?.close();
+ _activeClient = null;
+ }
+
+ static Future<File> _download(
+ UpdateInfo info,
+ void Function(int, int) onProgress,
+ ) async {
+ final dir = await getTemporaryDirectory();
+ final filename = Uri.parse(info.downloadUrl).pathSegments.last;
+ final file = File('${dir.path}/$filename');
+ if (await file.exists()) await file.delete();
+
+ final client = http.Client();
+ _activeClient = client;
+ try {
+ final request = http.Request('GET', Uri.parse(info.downloadUrl));
+ final response = await client.send(request);
+ if (response.statusCode != 200) {
+ throw HttpException('HTTP ${response.statusCode}');
+ }
+ final total = response.contentLength ?? 0;
+ var received = 0;
+ final sink = file.openWrite();
+ try {
+ await for (final chunk in response.stream) {
+ if (_activeClient != client) {
+ await sink.close();
+ throw const _CancelledException();
+ }
+ sink.add(chunk);
+ received += chunk.length;
+ onProgress(received, total);
+ }
+ await sink.flush();
+ } finally {
+ await sink.close();
+ }
+ return file;
+ } finally {
+ if (_activeClient == client) _activeClient = null;
+ client.close();
+ }
+ }
+}
+
+class _CancelledException implements Exception {
+ const _CancelledException();
+}
diff --git a/lib/widgets/update_dialog.dart b/lib/widgets/update_dialog.dart
new file mode 100644
index 00000000..db0ec863
--- /dev/null
+++ b/lib/widgets/update_dialog.dart
@@ -0,0 +1,105 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/update_checker_service.dart';
+import 'overlay_toast.dart';
+import 'wavy_progress_indicator.dart';
+
+class UpdateDialog {
+ /// Show the "Update available" prompt. Tapping Download performs an in-app
+ /// download with a progress dialog, then launches the system installer.
+ /// On any failure, falls back to launching the URL in the browser.
+ static Future<void> show(BuildContext context, UpdateInfo info) async {
+ final l = AppLocalizations.of(context)!;
+ final go = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(info.isPreRelease ? l.preReleaseAvailable : l.updateAvailable),
+ content: Text(l.updateDialogContent(
+ info.isPreRelease ? l.updateKindPreRelease : l.updateKindVersion,
+ info.latestVersion,
+ info.currentVersion,
+ )),
+ actions: [
+ TextButton(
+ onPressed: () {
+ UpdateCheckerService.dismiss(info.latestVersion);
+ Navigator.pop(ctx, false);
+ },
+ child: Text(l.later),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: Text(l.downloadButton),
+ ),
+ ],
+ ),
+ );
+ if (go != true || !context.mounted) return;
+ await _runInstall(context, info);
+ }
+
+ static Future<void> _runInstall(BuildContext context, UpdateInfo info) async {
+ final l = AppLocalizations.of(context)!;
+ final progress = ValueNotifier<double?>(null);
+
+ unawaited(showDialog<void>(
+ context: context,
+ barrierDismissible: false,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.updateDownloading),
+ content: ValueListenableBuilder<double?>(
+ valueListenable: progress,
+ builder: (_, p, __) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ WavyProgressIndicator(value: p),
+ const SizedBox(height: 12),
+ Text(
+ p == null ? '...' : '${(p * 100).toStringAsFixed(0)}%',
+ textAlign: TextAlign.center,
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () {
+ ApkUpdater.cancel();
+ Navigator.pop(ctx);
+ },
+ child: Text(l.cancel),
+ ),
+ ],
+ ),
+ ));
+
+ final result = await ApkUpdater.downloadAndInstall(
+ info,
+ onProgress: (received, total) {
+ progress.value = total > 0 ? received / total : null;
+ },
+ );
+
+ if (context.mounted && Navigator.canPop(context)) Navigator.pop(context);
+ progress.dispose();
+ if (!context.mounted) return;
+
+ switch (result.status) {
+ case ApkInstallStatus.ok:
+ case ApkInstallStatus.cancelled:
+ return;
+ case ApkInstallStatus.permissionDenied:
+ showOverlayToast(context, l.updateInstallPermissionDenied, icon: Icons.error_outline_rounded);
+ return;
+ case ApkInstallStatus.downloadFailed:
+ case ApkInstallStatus.launchFailed:
+ showOverlayToast(context, l.updateOpeningInBrowser, icon: Icons.open_in_browser_rounded);
+ await launchUrl(Uri.parse(info.downloadUrl), mode: LaunchMode.externalApplication);
+ }
+ }
+}
diff --git a/lib/widgets/wavy_progress_indicator.dart b/lib/widgets/wavy_progress_indicator.dart
new file mode 100644
index 00000000..5f5d04c7
--- /dev/null
+++ b/lib/widgets/wavy_progress_indicator.dart
@@ -0,0 +1,173 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+
+/// Material 3 Expressive wavy linear progress indicator.
+///
+/// Flutter 3.41's stock LinearProgressIndicator only supports the 2023 M3
+/// look (stop indicator + track gap), not the 2024 expressive squiggle.
+/// Drop-in once Flutter ships it.
+class WavyProgressIndicator extends StatefulWidget {
+ const WavyProgressIndicator({
+ super.key,
+ required this.value,
+ this.color,
+ this.trackColor,
+ this.height = 12,
+ this.amplitude = 2.5,
+ this.wavelength = 36,
+ this.strokeWidth = 4,
+ this.gap = 6,
+ });
+
+ final double? value;
+ final Color? color;
+ final Color? trackColor;
+ final double height;
+ final double amplitude;
+ final double wavelength;
+ final double strokeWidth;
+ final double gap;
+
+ @override
+ State<WavyProgressIndicator> createState() => _WavyProgressIndicatorState();
+}
+
+class _WavyProgressIndicatorState extends State<WavyProgressIndicator>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _ctrl;
+
+ @override
+ void initState() {
+ super.initState();
+ _ctrl = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1400),
+ )..repeat();
+ }
+
+ @override
+ void dispose() {
+ _ctrl.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ return SizedBox(
+ height: widget.height,
+ child: AnimatedBuilder(
+ animation: _ctrl,
+ builder: (_, __) => CustomPaint(
+ painter: _WavyPainter(
+ value: widget.value,
+ color: widget.color ?? cs.primary,
+ trackColor: widget.trackColor ?? cs.surfaceContainerHighest,
+ phase: _ctrl.value * 2 * math.pi,
+ amplitude: widget.amplitude,
+ wavelength: widget.wavelength,
+ strokeWidth: widget.strokeWidth,
+ gap: widget.gap,
+ indeterminate: widget.value == null,
+ ),
+ size: Size.infinite,
+ ),
+ ),
+ );
+ }
+}
+
+class _WavyPainter extends CustomPainter {
+ _WavyPainter({
+ required this.value,
+ required this.color,
+ required this.trackColor,
+ required this.phase,
+ required this.amplitude,
+ required this.wavelength,
+ required this.strokeWidth,
+ required this.gap,
+ required this.indeterminate,
+ });
+
+ final double? value;
+ final Color color;
+ final Color trackColor;
+ final double phase;
+ final double amplitude;
+ final double wavelength;
+ final double strokeWidth;
+ final double gap;
+ final bool indeterminate;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final centerY = size.height / 2;
+ final v = (value ?? 0).clamp(0.0, 1.0);
+ // Damp the wave near the ends so it doesn't poke past the rounded caps.
+ final tail = strokeWidth;
+ final filledEnd = indeterminate ? size.width : size.width * v;
+
+ final wavePaint = Paint()
+ ..color = color
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = strokeWidth
+ ..strokeCap = StrokeCap.round
+ ..strokeJoin = StrokeJoin.round;
+
+ final trackPaint = Paint()
+ ..color = trackColor
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = strokeWidth
+ ..strokeCap = StrokeCap.round;
+
+ // Wavy filled portion.
+ if (filledEnd > tail) {
+ final path = Path();
+ const step = 1.5;
+ for (double x = tail / 2; x <= filledEnd - tail / 2; x += step) {
+ // Fade amplitude in over the first wavelength and out over the last.
+ final fromStart = (x / wavelength).clamp(0.0, 1.0);
+ final toEnd = ((filledEnd - x) / wavelength).clamp(0.0, 1.0);
+ final amp = amplitude * fromStart * toEnd;
+ final y = centerY +
+ amp * math.sin(2 * math.pi * x / wavelength - phase);
+ if (x == tail / 2) {
+ path.moveTo(x, y);
+ } else {
+ path.lineTo(x, y);
+ }
+ }
+ canvas.drawPath(path, wavePaint);
+ }
+
+ // Remaining track (straight) with a small gap after the wave.
+ if (!indeterminate) {
+ final trackStart = filledEnd + gap;
+ final trackEnd = size.width - strokeWidth / 2;
+ if (trackStart < trackEnd) {
+ canvas.drawLine(
+ Offset(trackStart, centerY),
+ Offset(trackEnd, centerY),
+ trackPaint,
+ );
+ }
+ // Stop indicator at the very end.
+ final stopRadius = strokeWidth / 2;
+ canvas.drawCircle(
+ Offset(size.width - stopRadius, centerY),
+ stopRadius,
+ Paint()..color = color,
+ );
+ }
+ }
+
+ @override
+ bool shouldRepaint(_WavyPainter old) =>
+ old.value != value ||
+ old.phase != phase ||
+ old.color != color ||
+ old.trackColor != trackColor ||
+ old.indeterminate != indeterminate;
+}
diff --git a/pubspec.lock b/pubspec.lock
index 40ec7cbc..fc1a126f 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -619,6 +619,14 @@ packages:
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:
diff --git a/pubspec.yaml b/pubspec.yaml
index b6b0d553..1275dffe 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.89+133
+version: 1.8.90+134
environment:
sdk: '>=3.1.0 <4.0.0'
@@ -44,10 +44,13 @@ dependencies:
# Permissions
permission_handler: ^12.0.1
-
+
# Downloads & offline
path_provider: ^2.1.1
connectivity_plus: ^6.0.3
+
+ # In-app APK install (GitHub flavor updater)
+ open_filex: ^4.5.0
# Shake detection for sleep timer
sensors_plus: ^4.0.2