Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

iOS motion permission, mobile data offline fix, series pagination fix

Nathan Poulson93677a7cdc59
diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist
index 32a57b35..d478b5cd 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -89,6 +89,8 @@
</array>
<key>UIStatusBarHidden</key>
<false/>
+ <key>NSMotionUsageDescription</key>
+ <string>Absorb uses motion to detect shaking, which can reset or extend your sleep timer.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Absorb may use the microphone for audio features.</string>
<key>NSPhotoLibraryUsageDescription</key>
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index a5b02456..9c67145f 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -678,19 +678,31 @@ class LibraryProvider extends ChangeNotifier {
setNetworkOffline(true);
_auth?.clearLocalOverride();
} 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);
if (result.contains(ConnectivityResult.wifi)) {
- // WiFi available — check if local server is reachable
+ // WiFi available — optimistically go online and check local server
+ setNetworkOffline(false);
_auth?.checkLocalServer();
if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();
_catchUpQueueAutoDownloads();
catchUpSubscribedPodcasts();
} else {
- // WiFi dropped but still have connectivity (e.g. mobile data) —
- // local server won't be reachable, revert to remote URL.
+ // Mobile data only — local server won't be reachable.
_auth?.clearLocalOverride();
+ // If the remote server URL is a private/local address, it won't be
+ // reachable over mobile data either. Stay offline and ping instead
+ // of optimistically going online (which would flash green then fail).
+ final serverUrl = _auth?.serverUrl ?? '';
+ if (_isLocalUrl(serverUrl)) {
+ debugPrint('[Library] Mobile data only with local server URL — staying offline');
+ if (_networkOffline) {
+ _startServerPingTimer();
+ } else {
+ _goOffline();
+ }
+ } else {
+ // Remote server should be reachable over mobile — go online optimistically
+ setNetworkOffline(false);
+ }
}
}
});
@@ -806,6 +818,27 @@ class LibraryProvider extends ChangeNotifier {
SocketService().softReconnect();
}
+ /// Returns true if the URL points to a private/local network address
+ /// that won't be reachable over mobile data.
+ static bool _isLocalUrl(String url) {
+ final uri = Uri.tryParse(url);
+ if (uri == null || uri.host.isEmpty) return false;
+ final host = uri.host.toLowerCase();
+ if (host == 'localhost' || host == '127.0.0.1' || host == '::1') return true;
+ // Private IPv4 ranges
+ final parts = host.split('.');
+ if (parts.length == 4) {
+ final a = int.tryParse(parts[0]);
+ final b = int.tryParse(parts[1]);
+ if (a == 10) return true; // 10.0.0.0/8
+ if (a == 172 && b != null && b >= 16 && b <= 31) return true; // 172.16.0.0/12
+ if (a == 192 && b == 168) return true; // 192.168.0.0/16
+ }
+ // .local mDNS hostnames (e.g. myserver.local)
+ if (host.endsWith('.local')) return true;
+ return false;
+ }
+
/// Returns true for exceptions that indicate a real network problem
/// (unreachable server, DNS failure, TLS error). Non-network errors like
/// server 500s or JSON parse failures should not trigger offline mode.
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 717518a0..2881cf6d 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -779,12 +779,12 @@ class ApiService {
}
/// Get a single series with its books (paginated).
- Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId, int page = 0, int limit = 50}) async {
+ Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId}) async {
try {
Map<String, dynamic>? seriesMeta;
- // Get series metadata (only on first page)
- if (libraryId != null && page == 0) {
+ // Get series metadata
+ if (libraryId != null) {
final metaResp = await http.get(
Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),
headers: _headers,
@@ -794,23 +794,33 @@ class ApiService {
}
}
- // Get books in the series via library items filter
+ // Get all books in the series, paginating if needed.
// 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=$limit&page=$page&collapseseries=0';
- final itemsResp = await http.get(
- Uri.parse(url),
- headers: _headers,
- ).timeout(const Duration(seconds: 15));
- if (itemsResp.statusCode == 200) {
+ const pageSize = 500;
+ final allResults = <dynamic>[];
+ int total = 0;
+ int page = 0;
+ while (true) {
+ final url = '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=media.metadata.series.sequence&limit=$pageSize&page=$page&collapseseries=0';
+ final itemsResp = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (itemsResp.statusCode != 200) break;
final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;
final results = data['results'] as List<dynamic>? ?? [];
- final total = (data['total'] as num?)?.toInt() ?? results.length;
+ total = (data['total'] as num?)?.toInt() ?? results.length;
+ allResults.addAll(results);
+ if (allResults.length >= total || results.isEmpty) break;
+ page++;
+ }
+ if (allResults.isNotEmpty) {
return {
'id': seriesId,
'name': seriesMeta?['name'] ?? '',
- 'books': results,
+ 'books': allResults,
'total': total,
};
}
diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dart
index ca09d6e0..65781bf7 100644
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@ -73,12 +73,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
bool _didAutoScroll = false;
- // Pagination
- int _currentPage = 0;
int _totalBooks = 0;
- bool _isLoadingMore = false;
- bool _hasMore = true;
- static const int _pageSize = 50;
@override
void initState() {
@@ -94,24 +89,14 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
_fetchFromApi();
_loadAutoDownloadState();
context.read<LibraryProvider>().addListener(_onLibraryChanged);
- widget.scrollController.addListener(_onScroll);
}
@override
void dispose() {
- widget.scrollController.removeListener(_onScroll);
context.read<LibraryProvider>().removeListener(_onLibraryChanged);
super.dispose();
}
- void _onScroll() {
- if (_isLoadingMore || !_hasMore) return;
- final pos = widget.scrollController.position;
- if (pos.pixels >= pos.maxScrollExtent - 300) {
- _loadMoreBooks();
- }
- }
-
void _onLibraryChanged() {
// Re-fetch to pick up cover changes, metadata updates, etc.
_fetchFromApi();
@@ -237,7 +222,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
return;
}
final lib = context.read<LibraryProvider>();
- final data = await api.getSeries(seriesId, libraryId: widget.libraryId ?? lib.selectedLibraryId, page: 0, limit: _pageSize);
+ final data = await api.getSeries(seriesId, libraryId: widget.libraryId ?? lib.selectedLibraryId);
if (data != null && mounted) {
final rawBooks = data['books'] ?? data['libraryItems'] ?? [];
final total = (data['total'] as num?)?.toInt() ?? 0;
@@ -247,9 +232,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
_books = fetched;
_sortBooks();
_isLoading = false;
- _currentPage = 0;
_totalBooks = total;
- _hasMore = _books.length < total;
});
_scrollToUpNext();
return;
@@ -258,33 +241,6 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
if (mounted) setState(() => _isLoading = false);
}
- Future<void> _loadMoreBooks() async {
- if (_isLoadingMore || !_hasMore) return;
- final seriesId = widget.seriesId;
- if (seriesId == null || seriesId.isEmpty) return;
- final auth = context.read<AuthProvider>();
- final api = auth.apiService;
- if (api == null) return;
- setState(() => _isLoadingMore = true);
- final nextPage = _currentPage + 1;
- final lib = context.read<LibraryProvider>();
- final data = await api.getSeries(seriesId, libraryId: widget.libraryId ?? lib.selectedLibraryId, page: nextPage, limit: _pageSize);
- if (data != null && mounted) {
- final rawBooks = data['books'] ?? data['libraryItems'] ?? [];
- if (rawBooks is List && rawBooks.isNotEmpty) {
- final fetched = _unwrapBooks(rawBooks);
- setState(() {
- _books.addAll(fetched);
- _sortBooks();
- _currentPage = nextPage;
- _hasMore = _books.length < _totalBooks;
- _isLoadingMore = false;
- });
- return;
- }
- }
- if (mounted) setState(() { _isLoadingMore = false; _hasMore = false; });
- }
bool get _allFinished {
final lib = context.read<LibraryProvider>();
@@ -617,15 +573,8 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
builder: (context, _) => ListView.builder(
controller: widget.scrollController,
padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
- itemCount: _books.length + (_hasMore ? 1 : 0),
+ itemCount: _books.length,
itemBuilder: (context, index) {
- if (index >= _books.length) {
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 16),
- child: Center(child: SizedBox(width: 24, height: 24,
- child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary))),
- );
- }
final book = _books[index];
final bookId = book['id'] as String? ?? '';
final media = book['media'] as Map<String, dynamic>? ?? {};