Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Make browsing, search, series and authors hold up on very large libraries

Barnabas9f11e4678105
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 51c67f85..46556f55 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -728,6 +728,10 @@ class AuthProvider extends ChangeNotifier {
_accessToken = tokens.token;
_refreshToken = tokens.refreshToken;
debugPrint('[Auth] Login response keys: ${result.keys.toList()}');
+ final serverSettings = result['serverSettings'];
+ debugPrint('[Auth] Server version='
+ '${serverSettings is Map ? serverSettings['version'] : null} '
+ 'source=${result['Source']}');
debugPrint('[Auth] Login user keys: ${user.keys.toList()}');
debugPrint(
'[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken',
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index f9299337..288f7ee0 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -331,6 +331,12 @@ class LibraryScreenState extends State<LibraryScreen>
String? _allNarratorsCacheLibraryId;
bool _isSearching = false;
bool _hasSearched = false;
+ // One server search in flight at a time; the newest query typed meanwhile
+ // waits in _pendingSearch. _searchGen drops responses that a newer query
+ // (or clearing the search) has made stale.
+ int _searchGen = 0;
+ bool _searchInFlight = false;
+ String? _pendingSearch;
bool get _isInSearchMode => _searchController.text.trim().isNotEmpty;
// ── Batch selection (books tab and authors tab) ──
@@ -401,6 +407,9 @@ class LibraryScreenState extends State<LibraryScreen>
bool _isLoadingPage = false;
bool _hasMore = true;
+ // The last page request timed out or errored: the grid shows a retry in the
+ // loader slot and stops auto-fetching until the user asks.
+ bool _loadFailed = false;
// Tracks the offline state so the grid reloads when it flips (offline shows
// only downloads; back online shows the full library again).
bool _wasOffline = false;
@@ -408,7 +417,14 @@ class LibraryScreenState extends State<LibraryScreen>
int _totalItems = 0;
int? _randomSeed;
int _loadGeneration = 0; // prevents stale async loads from corrupting state
- static const _pageSize = 20;
+ // Largest grid page. The first request asks for 20 so something paints
+ // fast, then sizes double (20, 40, 80) and stay at 80: on a slow server a
+ // page costs roughly per item, and 80 at a time means a screenful or more
+ // between waits instead of one.
+ static const _pageSize = 80;
+ // Raw items received for the current view; page*limit offsets are computed
+ // from it so the growing page sizes stay aligned.
+ int _loadedCount = 0;
final _scrollController = ScrollController();
@@ -431,6 +447,13 @@ class LibraryScreenState extends State<LibraryScreen>
List<Map<String, dynamic>> _authors = [];
bool _isLoadingAuthors = false;
bool _authorsLoaded = false;
+ // Authors come in pages of 100, sorted server-side, so a library with tens
+ // of thousands of authors never needs one response holding all of them.
+ int _authorsPage = 0;
+ bool _hasMoreAuthors = true;
+ int _totalAuthors = 0;
+ int _authorsGen = 0;
+ static const _authorsPageSize = 100;
LibrarySort _authorSort = LibrarySort.alphabetical;
bool _authorSortAsc = true;
final _authorsScrollController = ScrollController();
@@ -495,11 +518,28 @@ class LibraryScreenState extends State<LibraryScreen>
final lib = context.read<LibraryProvider>();
final api = context.read<AuthProvider>().apiService;
if (api == null || lib.selectedLibraryId == null || lib.isOffline) return;
- final authors = await api.getLibraryAuthors(lib.selectedLibraryId!);
- if (!mounted) return;
+ // Re-fetch the pages already on screen and swap them in.
+ final libId = lib.selectedLibraryId!;
+ final pages = _authorsPage;
+ final gen = _authorsGen;
+ final fresh = <Map<String, dynamic>>[];
+ int? total;
+ for (var p = 0; p < pages; p++) {
+ final result = await api.getLibraryAuthorsPage(
+ libId,
+ page: p,
+ limit: _authorsPageSize,
+ sort: _authorServerSort,
+ desc: _authorSortAsc ? 0 : 1,
+ );
+ if (!mounted || gen != _authorsGen || result == null) return;
+ fresh.addAll(_authorPageResults(result));
+ total = (result['total'] as num?)?.toInt() ?? total;
+ }
setState(() {
- _authors = authors;
+ _authors = fresh;
_sortAuthors();
+ if (total != null) _totalAuthors = total;
});
});
}
@@ -601,6 +641,10 @@ class LibraryScreenState extends State<LibraryScreen>
_authors.clear();
_authorsLoaded = false;
_isLoadingAuthors = false;
+ _authorsPage = 0;
+ _hasMoreAuthors = true;
+ _totalAuthors = 0;
+ _authorsGen++;
_narrators.clear();
_narratorsLoaded = false;
_isLoadingNarrators = false;
@@ -999,7 +1043,10 @@ class LibraryScreenState extends State<LibraryScreen>
// ══════════════════════════════════════════════════════════════
Future<void> _loadPage() async {
if (_isLoadingPage || !_hasMore) return;
- setState(() => _isLoadingPage = true);
+ setState(() {
+ _isLoadingPage = true;
+ _loadFailed = false;
+ });
final gen = ++_loadGeneration;
final auth = context.read<AuthProvider>();
@@ -1118,6 +1165,10 @@ class LibraryScreenState extends State<LibraryScreen>
collapseSeries:
_collapseSeries && !useClientFilter && !lib.isPodcastLibrary,
);
+ if (result == null) {
+ debugPrint('[LibPage] fetch-all page=$fetchPage failed, showing '
+ 'what loaded so far');
+ }
if (result == null || !mounted || gen != _loadGeneration) break;
final results = (result['results'] as List<dynamic>?) ?? [];
total = (result['total'] as int?) ?? 0;
@@ -1155,10 +1206,17 @@ class LibraryScreenState extends State<LibraryScreen>
});
}
} else {
+ if (_page == 0) _loadedCount = 0;
+ // Each size divides the count loaded so far (20, 40, 80, 160, ...),
+ // which is what a page*limit offset needs.
+ final limit =
+ _loadedCount < 40 ? 20 : (_loadedCount < 80 ? 40 : _pageSize);
+ final pageIndex = _loadedCount ~/ limit;
+ final sw = Stopwatch()..start();
final result = await api.getLibraryItems(
lib.selectedLibraryId!,
- page: _page,
- limit: _pageSize,
+ page: pageIndex,
+ limit: limit,
sort: sort,
desc: desc,
filter: filter,
@@ -1189,11 +1247,12 @@ class LibraryScreenState extends State<LibraryScreen>
_items.add(r);
}
}
+ _loadedCount += results.length;
_page++;
// Compare raw server results to page size, not filtered _items to total.
// Client-side filters (e.g. hide-ebook-only) reduce _items below total,
// which would leave _hasMore permanently true and the loader spinning.
- _hasMore = results.length >= _pageSize;
+ _hasMore = results.length >= limit;
// Alpha: memory next to the page count, for the dense-grid OOM
// kills (no [CRASH] line, log just stops). rss is the whole
// process; imgCache is Flutter's decoded-cover cache (count/MB, and
@@ -1201,13 +1260,21 @@ class LibraryScreenState extends State<LibraryScreen>
final imgCache = PaintingBinding.instance.imageCache;
final rssMb = kIsWeb ? -1 : ProcessInfo.currentRss ~/ 1048576;
debugPrint(
- '[LibPage] page=${_page - 1} results=${results.length} pageSize=$_pageSize filtered=${_items.length} total=$total hideEbook=$_hideEbookOnly hasMore=$_hasMore '
+ '[LibPage] page=$pageIndex ms=${sw.elapsedMilliseconds} results=${results.length} pageSize=$limit loaded=$_loadedCount filtered=${_items.length} total=$total hideEbook=$_hideEbookOnly hasMore=$_hasMore '
'rss=${rssMb}MB imgCache=${imgCache.currentSize}/${imgCache.currentSizeBytes ~/ 1048576}MB live=${imgCache.liveImageCount} cols=${responsiveGridCount(context)}',
);
_isLoadingPage = false;
});
} else if (mounted && gen == _loadGeneration) {
- setState(() => _isLoadingPage = false);
+ // Timed out or errored. Show a retry in the loader slot instead of a
+ // spinner, and stop the fill loop refetching on every rebuild - on a
+ // struggling server that was one more request every 15s, forever.
+ debugPrint('[LibPage] page=$pageIndex limit=$limit failed after '
+ '${sw.elapsedMilliseconds}ms, waiting for retry');
+ setState(() {
+ _isLoadingPage = false;
+ _loadFailed = true;
+ });
}
}
}
@@ -1278,14 +1345,23 @@ class LibraryScreenState extends State<LibraryScreen>
) {
if (filter == SeriesFilter.none) return true;
final books = series['books'] as List<dynamic>? ?? const [];
- if (books.isEmpty) return false;
+ // Servers that send only libraryItemIds (no books) still give us enough
+ // for a progress filter.
+ final ids = books.isNotEmpty
+ ? books
+ .whereType<Map<String, dynamic>>()
+ .map((b) => b['id'] as String? ?? '')
+ .where((id) => id.isNotEmpty)
+ .toList()
+ : ((series['libraryItemIds'] as List<dynamic>?)
+ ?.map((e) => e.toString())
+ .toList() ??
+ const <String>[]);
+ if (ids.isEmpty) return false;
var finishedCount = 0;
var startedCount = 0;
- for (final b in books) {
- if (b is! Map<String, dynamic>) continue;
- final id = b['id'] as String?;
- if (id == null || id.isEmpty) continue;
+ for (final id in ids) {
final pd = lib.getProgressData(id);
final isFinished = pd?['isFinished'] == true;
final progress = lib.getProgress(id);
@@ -1299,7 +1375,7 @@ class LibraryScreenState extends State<LibraryScreen>
return seriesProgressMatchesFilter(
filter,
- bookCount: books.length,
+ bookCount: ids.length,
startedCount: startedCount,
finishedCount: finishedCount,
);
@@ -1405,6 +1481,7 @@ class LibraryScreenState extends State<LibraryScreen>
}
}
+ final sw = Stopwatch()..start();
final result = await api.getLibrarySeries(
lib.selectedLibraryId!,
page: _seriesPage,
@@ -1416,6 +1493,12 @@ class LibraryScreenState extends State<LibraryScreen>
if (result != null && mounted) {
final results = (result['results'] as List<dynamic>?) ?? [];
final total = (result['total'] as int?) ?? 0;
+ final first =
+ results.isNotEmpty ? results.first as Map<String, dynamic>? : null;
+ debugPrint('[SeriesPage] page=$_seriesPage ms=${sw.elapsedMilliseconds} '
+ 'results=${results.length} total=$total '
+ 'firstBooks=${(first?['books'] as List?)?.length} '
+ 'firstKeys=${first?.keys.join(',')}');
setState(() {
_totalSeries = total;
for (final r in results) {
@@ -1436,6 +1519,8 @@ class LibraryScreenState extends State<LibraryScreen>
);
}
} else if (mounted) {
+ debugPrint('[SeriesPage] page=$_seriesPage failed after '
+ '${sw.elapsedMilliseconds}ms');
setState(() => _isLoadingSeriesPage = false);
}
}
@@ -1449,7 +1534,11 @@ class LibraryScreenState extends State<LibraryScreen>
final allItems = <Map<String, dynamic>>[];
int page = 0;
int total = 0;
- while (true) {
+ // Only refresh libraries of up to 5000 series (100 pages). A 244k-book
+ // library has far more, and walking them all was thousands of heavy
+ // requests every time the tab opened, queued ahead of whatever the user
+ // tapped next; there the on-demand paging is all we do.
+ while (page < 100) {
final result = await api.getLibrarySeries(
lib.selectedLibraryId!,
page: page,
@@ -1460,6 +1549,10 @@ class LibraryScreenState extends State<LibraryScreen>
if (result == null) break;
final results = (result['results'] as List<dynamic>?) ?? [];
total = (result['total'] as int?) ?? 0;
+ if (total > 5000) {
+ debugPrint('[SeriesPage] background refresh skipped: $total series');
+ return;
+ }
for (final r in results) {
if (r is Map<String, dynamic>) allItems.add(r);
}
@@ -1481,8 +1574,28 @@ class LibraryScreenState extends State<LibraryScreen>
// ══════════════════════════════════════════════════════════════
// AUTHORS TAB - Load all authors
// ══════════════════════════════════════════════════════════════
+ String get _authorServerSort =>
+ _authorSort == LibrarySort.totalDuration ? 'numBooks' : 'name';
+
+ List<Map<String, dynamic>> _authorPageResults(Map<String, dynamic>? result) =>
+ ((result?['results'] ?? result?['authors']) as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .toList();
+
+ void _resetAuthors() {
+ _authorsGen++;
+ setState(() {
+ _authors.clear();
+ _authorsLoaded = false;
+ _isLoadingAuthors = false;
+ _authorsPage = 0;
+ _hasMoreAuthors = true;
+ _totalAuthors = 0;
+ });
+ }
+
Future<void> _loadAuthors() async {
- if (_isLoadingAuthors) return;
+ if (_isLoadingAuthors || (_authorsLoaded && !_hasMoreAuthors)) return;
setState(() => _isLoadingAuthors = true);
final auth = context.read<AuthProvider>();
@@ -1492,19 +1605,38 @@ class LibraryScreenState extends State<LibraryScreen>
setState(() {
_isLoadingAuthors = false;
_authorsLoaded = true;
+ _hasMoreAuthors = false;
});
return;
}
- final authors = await api.getLibraryAuthors(lib.selectedLibraryId!);
- if (mounted) {
- setState(() {
- _authors = authors;
- _sortAuthors();
- _isLoadingAuthors = false;
- _authorsLoaded = true;
- });
- }
+ final gen = _authorsGen;
+ final result = await api.getLibraryAuthorsPage(
+ lib.selectedLibraryId!,
+ page: _authorsPage,
+ limit: _authorsPageSize,
+ sort: _authorServerSort,
+ desc: _authorSortAsc ? 0 : 1,
+ );
+ if (!mounted || gen != _authorsGen) return;
+ final results = _authorPageResults(result);
+ final total = (result?['total'] as num?)?.toInt();
+ setState(() {
+ final seen = _authors.map((a) => a['id']).toSet();
+ final fresh = results.where((a) => !seen.contains(a['id'])).toList();
+ _authors.addAll(fresh);
+ _sortAuthors();
+ _authorsPage++;
+ _totalAuthors = total ?? _authors.length;
+ // A server that ignores paging answers with everything at once, which
+ // shows as a page of the wrong size or nothing new.
+ _hasMoreAuthors = result != null &&
+ fresh.isNotEmpty &&
+ results.length == _authorsPageSize &&
+ (total == null || _authors.length < total);
+ _isLoadingAuthors = false;
+ _authorsLoaded = true;
+ });
}
void _sortAuthors() {
@@ -1664,7 +1796,14 @@ class LibraryScreenState extends State<LibraryScreen>
}
PlayerSettings.setAuthorSort(_authorSort.name);
PlayerSettings.setAuthorSortAsc(_authorSortAsc);
- setState(() => _sortAuthors());
+ if (_hasMoreAuthors) {
+ // Only part of the list is here, so the new order has to come from the
+ // server.
+ _resetAuthors();
+ _loadAuthors();
+ } else {
+ setState(() => _sortAuthors());
+ }
if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
}
@@ -1955,6 +2094,8 @@ class LibraryScreenState extends State<LibraryScreen>
// Always show bars when entering/exiting search
_revealDriver.resetToShown();
if (query.trim().isEmpty) {
+ _searchGen++;
+ _pendingSearch = null;
setState(() {
_searchBookResults = [];
_searchSeriesResults = [];
@@ -1974,21 +2115,45 @@ class LibraryScreenState extends State<LibraryScreen>
}
Future<void> _performSearch(String query) async {
+ // On a huge library every server search is several full-table scans, so
+ // stacking one per keystroke left the server unable to answer anything
+ // else, and a slow early response could land after a later one and
+ // overwrite it. Serialize: one in flight, the newest query waits its turn.
+ if (_searchInFlight) {
+ _pendingSearch = query;
+ return;
+ }
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 gen = ++_searchGen;
final isPodcast = lib.isPodcastLibrary;
- final result = await api.searchLibrary(lib.selectedLibraryId!, query);
- if (result != null && mounted) {
+ final libId = lib.selectedLibraryId!;
+ Map<String, dynamic>? result;
+ _searchInFlight = true;
+ try {
+ result = await api.searchLibrary(libId, query);
+ } finally {
+ _searchInFlight = false;
+ final pending = _pendingSearch;
+ _pendingSearch = null;
+ if (pending != null && pending != query && mounted) {
+ unawaited(_performSearch(pending));
+ }
+ }
+ // A newer query took over while this one was out, or the search was
+ // cleared: leave whatever is showing alone.
+ if (!mounted || gen != _searchGen) return;
+ final data = result;
+ if (data != null) {
setState(() {
if (isPodcast) {
- _searchBookResults = (result['podcast'] as List<dynamic>?) ?? [];
+ _searchBookResults = (data['podcast'] as List<dynamic>?) ?? [];
} else {
- _searchBookResults = (result['book'] as List<dynamic>?) ?? [];
+ _searchBookResults = (data['book'] as List<dynamic>?) ?? [];
if (_hideEbookOnly) {
_searchBookResults = _searchBookResults.where((r) {
final item =
@@ -1998,8 +2163,8 @@ class LibraryScreenState extends State<LibraryScreen>
}).toList();
}
}
- _searchSeriesResults = (result['series'] as List<dynamic>?) ?? [];
- _searchAuthorResults = (result['authors'] as List<dynamic>?) ?? [];
+ _searchSeriesResults = (data['series'] as List<dynamic>?) ?? [];
+ _searchAuthorResults = (data['authors'] as List<dynamic>?) ?? [];
if (!isPodcast) {
final q = query.toLowerCase();
_searchTagResults = _availableTags
@@ -2038,9 +2203,9 @@ class LibraryScreenState extends State<LibraryScreen>
// Only override when the index actually built, so a failed fetch keeps the
// server results instead of blanking them.
if (!isPodcast) {
- final libId = lib.selectedLibraryId!;
await BookSearchIndex().ensureIndex(api, libId);
if (mounted &&
+ gen == _searchGen &&
BookSearchIndex().isReady(libId) &&
_searchController.text.trim() == query) {
var books = BookSearchIndex()
@@ -3096,7 +3261,7 @@ class LibraryScreenState extends State<LibraryScreen>
countText = l.librarySeriesCount(_totalSeries);
break;
case 2:
- countText = l.libraryAuthorsCount(_authors.length);
+ countText = l.libraryAuthorsCount(max(_totalAuthors, _authors.length));
break;
case 3:
countText = l.libraryNarratorsCount(_narrators.length);
@@ -3305,11 +3470,7 @@ class LibraryScreenState extends State<LibraryScreen>
}
Future<void> _refreshAuthors() async {
- setState(() {
- _authors.clear();
- _authorsLoaded = false;
- _isLoadingAuthors = false;
- });
+ _resetAuthors();
await _loadAuthors();
}
@@ -3322,6 +3483,7 @@ class LibraryScreenState extends State<LibraryScreen>
items: _visibleLibraryItems(lib),
isLoadingPage: _isLoadingPage,
hasMore: _hasMore,
+ loadFailed: _loadFailed,
filter: _filter,
genreFilter: _genreFilter,
tagFilter: _tagFilter,
@@ -3587,6 +3749,8 @@ class LibraryScreenState extends State<LibraryScreen>
authors: _authors,
isLoadingAuthors: _isLoadingAuthors,
authorsLoaded: _authorsLoaded,
+ hasMore: _hasMoreAuthors,
+ onLoadMore: _loadAuthors,
onRefresh: _refreshAuthors,
headerSliver: headerSliver,
scrollController: _authorsScrollController,
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 55cbdb6f..a3f736ef 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -993,8 +993,10 @@ class ApiService {
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
}
+ debugPrint('[API] getLibraryItems page=$page limit=$limit: '
+ 'HTTP ${response.statusCode}');
} catch (e) {
- // ignore
+ debugPrint('[API] getLibraryItems page=$page limit=$limit failed: $e');
}
return null;
}
@@ -1373,8 +1375,9 @@ class ApiService {
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
}
+ debugPrint('[API] getLibrarySeries page=$page: HTTP ${response.statusCode}');
} catch (e) {
- // ignore
+ debugPrint('[API] getLibrarySeries page=$page failed: $e');
}
return null;
}
@@ -1447,6 +1450,61 @@ class ApiService {
return [];
}
+ /// One page of a library's authors, sorted server-side. [sort] is `name`,
+ /// `lastFirst`, `addedAt`, `updatedAt` or `numBooks`. Stock ABS answers
+ /// `{results, total, ...}`; a server that ignores paging answers `{authors}`
+ /// with everything, which callers treat as the only page.
+ Future<Map<String, dynamic>?> getLibraryAuthorsPage(
+ String libraryId, {
+ int page = 0,
+ int limit = 100,
+ String sort = 'name',
+ int desc = 0,
+ }) async {
+ try {
+ final sw = Stopwatch()..start();
+ final response = await _authGet(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/authors'
+ '?limit=$limit&page=$page&sort=$sort&desc=$desc'),
+ timeout: const Duration(seconds: 30),
+ );
+ debugPrint('[API] getLibraryAuthorsPage page=$page: HTTP '
+ '${response.statusCode} in ${sw.elapsedMilliseconds}ms');
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ debugPrint('[API] getLibraryAuthorsPage page=$page failed: $e');
+ }
+ return null;
+ }
+
+ /// Fetch several items by id in one request. One indexed query server-side,
+ /// unlike the filtered items listing, which sorts the whole library first.
+ Future<List<Map<String, dynamic>>> getLibraryItemsBatch(
+ List<String> ids) async {
+ if (ids.isEmpty) return const [];
+ try {
+ final sw = Stopwatch()..start();
+ final response = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/items/batch/get'),
+ body: jsonEncode({'libraryItemIds': ids}),
+ timeout: const Duration(seconds: 30),
+ );
+ debugPrint('[API] getLibraryItemsBatch ${ids.length} ids: HTTP '
+ '${response.statusCode} in ${sw.elapsedMilliseconds}ms');
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ return (data['libraryItems'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .toList();
+ }
+ } catch (e) {
+ debugPrint('[API] getLibraryItemsBatch failed: $e');
+ }
+ return const [];
+ }
+
/// Get all narrators for a library. ABS exposes narrators only via the
/// filterdata endpoint as a list of name strings (no IDs/images/bios).
Future<List<String>> getLibraryNarrators(String libraryId) async {
@@ -2514,55 +2572,78 @@ class ApiService {
}
Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId, void Function(List<dynamic> books, int total, {double? totalDuration})? onPageLoaded}) async {
+ if (libraryId == null) return null;
try {
- Map<String, dynamic>? seriesMeta;
+ // ABS filter format: series.<base64(seriesId)>
+ final filterValue = base64Encode(utf8.encode(seriesId));
+ const pageSize = 100;
+ final allResults = <dynamic>[];
+ int total = 0;
+ int page = 0;
- // Get series metadata
- if (libraryId != null) {
- final metaResp = await _authGet(
- Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),
- timeout: const Duration(seconds: 30));
- if (metaResp.statusCode == 200) {
- seriesMeta = jsonDecode(metaResp.body) as Map<String, dynamic>;
+ Future<Map<String, dynamic>?> fetchMeta() async {
+ final sw = Stopwatch()..start();
+ try {
+ final resp = await _authGet(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),
+ timeout: const Duration(seconds: 30));
+ debugPrint('[API] getSeries $seriesId meta: HTTP ${resp.statusCode} '
+ 'in ${sw.elapsedMilliseconds}ms');
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ debugPrint('[API] getSeries $seriesId meta failed after '
+ '${sw.elapsedMilliseconds}ms: $e');
}
+ return null;
}
- // Get all books in the series, paginating if needed.
- // ABS filter format: series.<base64(seriesId)>
- if (libraryId != null) {
- final filterValue = base64Encode(utf8.encode(seriesId));
- const pageSize = 100;
- 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 _authGet(
- Uri.parse(url),
- timeout: const Duration(seconds: 30));
- if (itemsResp.statusCode != 200) {
- debugPrint('[API] getSeries items page $page failed: ${itemsResp.statusCode}');
- break;
- }
- final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;
- final results = data['results'] as List<dynamic>? ?? [];
- total = (data['total'] as num?)?.toInt() ?? results.length;
- allResults.addAll(results);
- onPageLoaded?.call(allResults, total, totalDuration: (seriesMeta?['totalDuration'] as num?)?.toDouble());
- if (allResults.length >= total || results.isEmpty) break;
- page++;
+ Future<http.Response> fetchItems(int p) => _authGet(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=media.metadata.series.sequence&limit=$pageSize&page=$p&collapseseries=0'),
+ timeout: const Duration(seconds: 30));
+
+ // The books are what the sheet shows; the series record only adds the
+ // name and total duration. Ask for the first page of books before the
+ // record so a slow server answers the important one first, and let the
+ // record land whenever it does.
+ var itemsFuture = fetchItems(0);
+ final metaFuture = fetchMeta();
+ while (true) {
+ final pageSw = Stopwatch()..start();
+ final itemsResp = await itemsFuture;
+ if (itemsResp.statusCode != 200) {
+ debugPrint('[API] getSeries $seriesId items page $page failed: ${itemsResp.statusCode}');
+ break;
}
- if (allResults.isNotEmpty) {
- return {
- 'id': seriesId,
- 'name': seriesMeta?['name'] ?? '',
- 'books': allResults,
- 'total': total,
- if (seriesMeta != null) 'totalDuration': seriesMeta['totalDuration'],
- };
+ final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;
+ final results = data['results'] as List<dynamic>? ?? [];
+ total = (data['total'] as num?)?.toInt() ?? results.length;
+ debugPrint('[API] getSeries $seriesId items page=$page results=${results.length} '
+ 'total=$total in ${pageSw.elapsedMilliseconds}ms');
+ allResults.addAll(results);
+ onPageLoaded?.call(allResults, total);
+ if (allResults.length >= total || results.isEmpty) break;
+ page++;
+ itemsFuture = fetchItems(page);
+ }
+
+ final seriesMeta = await metaFuture;
+ final totalDuration = (seriesMeta?['totalDuration'] as num?)?.toDouble();
+ if (allResults.isNotEmpty) {
+ if (totalDuration != null) {
+ onPageLoaded?.call(allResults, total, totalDuration: totalDuration);
}
+ return {
+ 'id': seriesId,
+ 'name': seriesMeta?['name'] ?? '',
+ 'books': allResults,
+ 'total': total,
+ if (seriesMeta != null) 'totalDuration': seriesMeta['totalDuration'],
+ };
}
- } catch (_) {
+ } catch (e) {
+ debugPrint('[API] getSeries $seriesId failed: $e');
}
return null;
}
@@ -2575,6 +2656,7 @@ class ApiService {
final filterValue = base64Encode(utf8.encode(seriesId));
final allResults = <dynamic>[];
int page = 0;
+ final sw = Stopwatch()..start();
while (true) {
final url = '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=addedAt&limit=100&page=$page&collapseseries=1';
final resp = await _authGet(Uri.parse(url), timeout: const Duration(seconds: 60));
@@ -2585,6 +2667,9 @@ class ApiService {
final data = jsonDecode(resp.body) as Map<String, dynamic>;
final results = data['results'] as List<dynamic>? ?? [];
final total = (data['total'] as num?)?.toInt() ?? results.length;
+ debugPrint('[API] getSeriesCollapsed page=$page results=${results.length} '
+ 'total=$total in ${sw.elapsedMilliseconds}ms');
+ sw.reset();
allResults.addAll(results);
if (allResults.length >= total || results.isEmpty) break;
page++;
diff --git a/lib/services/book_search_index.dart b/lib/services/book_search_index.dart
index 9e1f256e..07746228 100644
--- a/lib/services/book_search_index.dart
+++ b/lib/services/book_search_index.dart
@@ -38,9 +38,13 @@ class BookSearchIndex {
final Map<String, List<_Indexed>> _cache = {};
final Map<String, Future<void>> _inFlight = {};
- // Libraries whose index hit the item cap: their search results are missing
- // the newest items, so callers must merge the server's results in rather
- // than replacing them (GH #349 - books past 10k vanished from search).
+ // Libraries past the item cap are never indexed: the cap would cover a
+ // sliver of them (4% of a 244k-book library) and fetching it is the heaviest
+ // burst the app can put on a server. Search stays server-side for these.
+ final Set<String> _serverOnly = {};
+ // Libraries whose index is missing items because a page failed mid-build:
+ // callers must merge the server's results in rather than replacing them, or
+ // the missing books vanish from search for the session (GH #349 shape).
final Set<String> _truncated = {};
void _onItemUpdated(Map<String, dynamic> item) => patchItem(item);
@@ -73,8 +77,8 @@ class BookSearchIndex {
bool isReady(String libraryId) => _cache.containsKey(libraryId);
- /// True when the library has more items than the index cap, meaning search
- /// results from this index are incomplete for the newest items.
+ /// True when the index is missing some of the library's items (a page failed
+ /// to fetch while building), so results from it alone are incomplete.
bool isTruncated(String libraryId) => _truncated.contains(libraryId);
/// Drop everything (call on logout / account switch so a reused libraryId
@@ -82,14 +86,18 @@ class BookSearchIndex {
void clear() {
_cache.clear();
_inFlight.clear();
+ _serverOnly.clear();
_truncated.clear();
}
/// Build the index for [libraryId] if not already cached. Concurrent callers
/// share the same in-flight build. A failed fetch is not cached, so the next
- /// call retries.
+ /// call retries. Libraries over the cap are remembered and never built, so
+ /// this returns at once for them without a request.
Future<void> ensureIndex(ApiService api, String libraryId) {
- if (_cache.containsKey(libraryId)) return Future.value();
+ if (_cache.containsKey(libraryId) || _serverOnly.contains(libraryId)) {
+ return Future.value();
+ }
final existing = _inFlight[libraryId];
if (existing != null) return existing;
final f = _build(api, libraryId);
@@ -100,6 +108,12 @@ class BookSearchIndex {
Future<void> _build(ApiService api, String libraryId) async {
const pageSize = 100;
const maxPages = 100; // ~10k items safety cap
+ // Pages fetched at once. This used to fire every page in one go, which on
+ // a 244k-book server queued a few hundred SQLite queries ahead of everything
+ // else the app asked for (grid pages, the library list) until they all
+ // timed out, and the server kept grinding through them after the phone
+ // had given up.
+ const concurrency = 3;
final first =
await api.getLibraryItems(libraryId, page: 0, limit: pageSize);
@@ -108,21 +122,38 @@ class BookSearchIndex {
_collect(first, items);
final total = (first['total'] as num?)?.toInt() ?? items.length;
final pages = (total / pageSize).ceil();
- final lastPage = pages > maxPages ? maxPages : pages;
-
- if (lastPage > 1) {
- final futures = <Future<Map<String, dynamic>?>>[
- for (var p = 1; p < lastPage; p++)
- api.getLibraryItems(libraryId, page: p, limit: pageSize),
- ];
- for (final pd in await Future.wait(futures)) {
- if (pd != null) _collect(pd, items);
+ if (pages > maxPages) {
+ _serverOnly.add(libraryId);
+ debugPrint('[BookSearchIndex] $libraryId has $total items, over the '
+ '${maxPages * pageSize} cap - not indexing, search stays server-side.');
+ return;
+ }
+
+ final fetched = <int, Map<String, dynamic>>{};
+ var failed = false;
+ var next = 1;
+ Future<void> worker() async {
+ while (next < pages) {
+ final p = next++;
+ var pd = await api.getLibraryItems(libraryId, page: p, limit: pageSize);
+ pd ??= await api.getLibraryItems(libraryId, page: p, limit: pageSize);
+ if (pd == null) {
+ failed = true;
+ } else {
+ fetched[p] = pd;
+ }
}
}
- if (pages > maxPages) {
+
+ await Future.wait([for (var i = 0; i < concurrency; i++) worker()]);
+ for (var p = 1; p < pages; p++) {
+ final pd = fetched[p];
+ if (pd != null) _collect(pd, items);
+ }
+ if (failed) {
_truncated.add(libraryId);
- debugPrint('[BookSearchIndex] $libraryId has $total items; indexed first '
- '${maxPages * pageSize}. Callers merge server results for the rest.');
+ debugPrint('[BookSearchIndex] $libraryId: some pages failed, indexed '
+ '${items.length} of $total. Callers merge server results.');
} else {
_truncated.remove(libraryId);
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 4223e9e6..d255edff 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -1811,10 +1811,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
if (seriesId == null) return;
final auth = context.read<AuthProvider>();
final itemLibraryId = _item?['libraryId'] as String?;
+ // This book is in the series by definition, so the sheet can show it at
+ // once instead of a spinner while the server answers.
+ final item = _item;
showSeriesBooksSheet(
context,
seriesName: seriesName,
seriesId: seriesId,
+ books: item != null ? [item] : const [],
serverUrl: auth.serverUrl,
token: auth.token,
libraryId: itemLibraryId,
diff --git a/lib/widgets/library_authors_tab.dart b/lib/widgets/library_authors_tab.dart
index 10121df4..a1fb2684 100644
--- a/lib/widgets/library_authors_tab.dart
+++ b/lib/widgets/library_authors_tab.dart
@@ -7,6 +7,11 @@ class LibraryAuthorsTab extends StatelessWidget {
final List<Map<String, dynamic>> authors;
final bool isLoadingAuthors;
final bool authorsLoaded;
+
+ /// More pages exist past [authors]: the grid shows a loader cell and calls
+ /// [onLoadMore] as the user nears the bottom.
+ final bool hasMore;
+ final VoidCallback? onLoadMore;
final Future<void> Function() onRefresh;
final Widget? headerSliver;
final ScrollController? scrollController;
@@ -21,6 +26,8 @@ class LibraryAuthorsTab extends StatelessWidget {
required this.authors,
required this.isLoadingAuthors,
required this.authorsLoaded,
+ this.hasMore = false,
+ this.onLoadMore,
required this.onRefresh,
this.headerSliver,
this.scrollController,
@@ -39,7 +46,7 @@ class LibraryAuthorsTab extends StatelessWidget {
final headers = <Widget>[if (headerSliver != null) headerSliver!];
Widget body;
- if (isLoadingAuthors) {
+ if (isLoadingAuthors && authors.isEmpty) {
body = CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
@@ -91,6 +98,14 @@ class LibraryAuthorsTab extends StatelessWidget {
),
delegate: SliverChildBuilderDelegate(
(context, index) {
+ if (index >= authors.length) {
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
final author = authors[index];
final authorId = author['id'] as String? ?? '';
return GridAuthorTile(
@@ -103,7 +118,7 @@ class LibraryAuthorsTab extends StatelessWidget {
: () => onSelectionToggle!(author, index),
);
},
- childCount: authors.length,
+ childCount: authors.length + (hasMore ? 1 : 0),
),
),
),
@@ -111,6 +126,32 @@ class LibraryAuthorsTab extends StatelessWidget {
);
}
- return RefreshIndicator(onRefresh: onRefresh, child: body);
+ // Same load-ahead as the books grid: pull the next page while there is
+ // less than ~two screens left, and stay quiet while a sheet is on top.
+ const loadAheadPx = 1200.0;
+ final loadMore = onLoadMore;
+ if (hasMore && !isLoadingAuthors && authors.isNotEmpty && loadMore != null) {
+ final route = ModalRoute.of(context);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (route != null && !route.isCurrent) return;
+ final c = scrollController;
+ if (c != null && c.hasClients && c.position.extentAfter < loadAheadPx) {
+ loadMore();
+ }
+ });
+ }
+
+ return NotificationListener<ScrollNotification>(
+ onNotification: (n) {
+ if (hasMore &&
+ loadMore != null &&
+ n is ScrollUpdateNotification &&
+ n.metrics.pixels >= n.metrics.maxScrollExtent - loadAheadPx) {
+ loadMore();
+ }
+ return false;
+ },
+ child: RefreshIndicator(onRefresh: onRefresh, child: body),
+ );
}
}
diff --git a/lib/widgets/library_books_tab.dart b/lib/widgets/library_books_tab.dart
index c359cde3..270c41a5 100644
--- a/lib/widgets/library_books_tab.dart
+++ b/lib/widgets/library_books_tab.dart
@@ -7,6 +7,10 @@ class LibraryBooksTab extends StatelessWidget {
final List<Map<String, dynamic>> items;
final bool isLoadingPage;
final bool hasMore;
+
+ /// The last page request failed. The loader slot becomes a retry button and
+ /// the auto-fetch triggers stay quiet until the user taps it or refreshes.
+ final bool loadFailed;
final LibraryFilter filter;
final String? genreFilter;
final String? tagFilter;
@@ -22,10 +26,15 @@ class LibraryBooksTab extends StatelessWidget {
/// floats independently.
final Widget? headerSliver;
- /// Called when the user scrolls within ~400px of the bottom; library_screen
- /// owns the actual page-fetch logic.
+ /// Called when the user scrolls within [_loadAheadPx] of the bottom, or taps
+ /// retry after a failed page; library_screen owns the actual page-fetch
+ /// logic.
final VoidCallback onLoadMore;
+ // How far above the bottom the next page is requested. About two phone
+ // screens, so the fetch is usually done before the user gets there.
+ static const double _loadAheadPx = 1200;
+
/// Optional explicit ScrollController. When tabs are kept alive in an
/// IndexedStack each one needs its own controller so scroll positions don't
/// collide on the PrimaryScrollController.
@@ -39,6 +48,7 @@ class LibraryBooksTab extends StatelessWidget {
required this.items,
required this.isLoadingPage,
required this.hasMore,
+ this.loadFailed = false,
required this.filter,
this.genreFilter,
this.tagFilter,
@@ -76,6 +86,33 @@ class LibraryBooksTab extends StatelessWidget {
),
],
);
+ } else if (items.isEmpty && !isLoadingPage && loadFailed) {
+ // The first page never arrived. Say so rather than "no books", which is
+ // what an empty grid otherwise claims.
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.cloud_off_outlined,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(l.failedToLoad,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 4),
+ TextButton(onPressed: onLoadMore, child: Text(l.retry)),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
} else if (items.isEmpty && !isLoadingPage) {
final filterMsg = isPodcastLibrary && filter != LibraryFilter.none
? l.libraryNoItemsMatchingFilter
@@ -157,6 +194,21 @@ class LibraryBooksTab extends StatelessWidget {
delegate: SliverChildBuilderDelegate(
(context, index) {
if (index >= items.length) {
+ if (loadFailed) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(l.failedToLoad,
+ textAlign: TextAlign.center,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ TextButton(
+ onPressed: onLoadMore, child: Text(l.retry)),
+ ],
+ ),
+ );
+ }
return const Center(
child: Padding(
padding: EdgeInsets.all(16),
@@ -190,13 +242,20 @@ class LibraryBooksTab extends StatelessWidget {
// On a tall/wide viewport (tablets) a page of results can land entirely
// within the current screen, so nothing scrolls and the bottom-trigger
// below never fires. After layout, keep pulling pages while there's less
- // content below the fold than the scroll-trigger's own 400px margin -
+ // content below the fold than the scroll-trigger's own margin -
// stopping merely at "technically scrollable" left iPads sitting on a
// visible, forever-spinning loader until the user nudged the grid.
- if (hasMore && !isLoadingPage && items.isNotEmpty) {
+ if (hasMore && !isLoadingPage && !loadFailed && items.isNotEmpty) {
+ // Don't keep pulling pages while a sheet is open on top: on a slow
+ // server every grid page is seconds of work, queued ahead of whatever
+ // the sheet is asking for.
+ final route = ModalRoute.of(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (route != null && !route.isCurrent) return;
final c = scrollController;
- if (c != null && c.hasClients && c.position.extentAfter < 400) {
+ if (c != null &&
+ c.hasClients &&
+ c.position.extentAfter < _loadAheadPx) {
onLoadMore();
}
});
@@ -204,8 +263,9 @@ class LibraryBooksTab extends StatelessWidget {
return NotificationListener<ScrollNotification>(
onNotification: (n) {
- if (n is ScrollUpdateNotification &&
- n.metrics.pixels >= n.metrics.maxScrollExtent - 400) {
+ if (!loadFailed &&
+ n is ScrollUpdateNotification &&
+ n.metrics.pixels >= n.metrics.maxScrollExtent - _loadAheadPx) {
onLoadMore();
}
return false;
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index b87f3540..eac974a0 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -541,6 +541,7 @@ class GridSeriesTile extends StatelessWidget {
seriesName: seriesName,
seriesId: seriesId,
books: const [],
+ itemIds: itemIds,
serverUrl: auth.serverUrl,
token: auth.token,
);
@@ -610,7 +611,22 @@ class GridSeriesTileDirect extends StatelessWidget {
final seriesName = series['name'] as String? ?? l.libraryGridTilesUnknownSeries;
final seriesId = series['id'] as String? ?? '';
final books = series['books'] as List<dynamic>? ?? [];
- final numBooks = books.length;
+ // Some servers send the series list without the books, carrying only
+ // libraryItemIds + numBooks (the collapsed-series shape). Covers, count and
+ // progress only need the ids, so fall back to those.
+ final itemIds = books.isNotEmpty
+ ? books
+ .map((b) => (b as Map<String, dynamic>)['id'] as String? ?? '')
+ .where((id) => id.isNotEmpty)
+ .toList()
+ : ((series['libraryItemIds'] as List<dynamic>?)
+ ?.map((e) => e.toString())
+ .toList() ??
+ const <String>[]);
+ final rawNumBooks = series['numBooks'] as int? ?? 0;
+ final numBooks = books.isNotEmpty
+ ? books.length
+ : (rawNumBooks > 0 ? rawNumBooks : itemIds.length);
// Get author from first book
String author = '';
@@ -621,21 +637,13 @@ class GridSeriesTileDirect extends StatelessWidget {
author = metadata['authorName'] as String? ?? '';
}
- // Gather up to 4 cover URLs from books
- final coverUrls = books
- .take(4)
- .map((b) {
- final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
- return bookId.isNotEmpty ? lib.getCoverUrl(bookId) : null;
- })
- .toList();
+ // Gather up to 4 cover URLs
+ final coverUrls = itemIds.take(4).map((id) => lib.getCoverUrl(id)).toList();
// Calculate series progress
double totalProgress = 0;
int finished = 0;
- for (final b in books) {
- final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
- if (bookId.isEmpty) continue;
+ for (final bookId in itemIds) {
final pd = lib.getProgressData(bookId);
if (pd?['isFinished'] == true) {
finished++;
@@ -644,7 +652,8 @@ class GridSeriesTileDirect extends StatelessWidget {
totalProgress += lib.getProgress(bookId);
}
}
- final seriesProgress = books.isNotEmpty ? totalProgress / books.length : 0.0;
+ final seriesProgress =
+ itemIds.isNotEmpty ? totalProgress / itemIds.length : 0.0;
return GestureDetector(
behavior: HitTestBehavior.opaque,
@@ -657,6 +666,7 @@ class GridSeriesTileDirect extends StatelessWidget {
seriesName: seriesName,
seriesId: seriesId.isEmpty ? null : seriesId,
books: seriesId.isEmpty ? books : const [],
+ itemIds: itemIds,
serverUrl: auth.serverUrl,
token: auth.token,
parentSeriesId: parentSeriesId,
diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dart
index 4190a6d9..7f10a744 100644
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@ -29,6 +29,7 @@ void showSeriesBooksSheet(BuildContext context, {
required String seriesName,
String? seriesId,
List<dynamic> books = const [],
+ List<String> itemIds = const [],
String? serverUrl,
String? token,
String? libraryId,
@@ -41,6 +42,7 @@ void showSeriesBooksSheet(BuildContext context, {
seriesName: seriesName,
seriesId: seriesId,
books: books,
+ itemIds: itemIds,
serverUrl: serverUrl,
token: token,
libraryId: libraryId,
@@ -53,6 +55,11 @@ void showSeriesBooksSheet(BuildContext context, {
class SeriesBooksSheet extends StatefulWidget {
final String seriesName;
final String? seriesId;
+
+ /// Ids of the books in the series when the caller already has them (series
+ /// lists that carry libraryItemIds). Lets the sheet fetch them in one batch
+ /// instead of the filtered items query.
+ final List<String> itemIds;
final List<dynamic> books;
final String? serverUrl;
final String? token;
@@ -65,6 +72,7 @@ class SeriesBooksSheet extends StatefulWidget {
required this.seriesName,
this.seriesId,
required this.books,
+ this.itemIds = const [],
required this.serverUrl,
required this.token,
this.libraryId,
@@ -79,6 +87,9 @@ class SeriesBooksSheet extends StatefulWidget {
class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
List<Map<String, dynamic>> _books = [];
bool _isLoading = true;
+ // The server fetch failed and there is nothing to show; offer a retry
+ // instead of claiming the series has no books.
+ bool _loadFailed = false;
bool _isDownloadingAll = false;
bool _isMarkingAll = false;
bool _autoDownloadEnabled = false;
@@ -551,6 +562,30 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
final lib = context.read<LibraryProvider>();
final libraryId = widget.libraryId ?? lib.selectedLibraryId;
+ // Series lists that carry libraryItemIds: hydrate those in one batch
+ // request. That is one indexed query, where the filtered items listing
+ // below makes the server sort the whole library first - 30s and more on
+ // a 244k-book server.
+ if (_books.isEmpty && widget.itemIds.isNotEmpty) {
+ final items = await api.getLibraryItemsBatch(widget.itemIds);
+ if (!mounted) return;
+ if (items.isNotEmpty) {
+ final fetched = _unwrapBooks(items);
+ setState(() {
+ _books = fetched;
+ _sortBooks();
+ _isLoading = false;
+ _totalBooks = fetched.length;
+ });
+ if (!_didAutoScroll) _scrollToUpNext();
+ try {
+ lib.setSeriesBooksCache(seriesId, items, items.length);
+ } catch (_) {}
+ if (_collapseSeries && !_subSeriesLoaded) _loadSubSeriesData();
+ return;
+ }
+ }
+
// For large series (100+ books), serve cached data instantly
// then refresh in background. Small series always fetch fresh.
final cached = lib.getSeriesBooksCache(seriesId);
@@ -589,7 +624,12 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
}
},
);
- if (data == null && mounted) setState(() => _isLoading = false);
+ if (data == null && mounted) {
+ setState(() {
+ _isLoading = false;
+ _loadFailed = _books.isEmpty;
+ });
+ }
// If collapse is enabled and we now have books, load sub-series data
if (_collapseSeries && _books.isNotEmpty && !_subSeriesLoaded) {
_loadSubSeriesData();
@@ -1049,6 +1089,26 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
if (_isLoading && _books.isEmpty)
const Expanded(
child: Center(child: CircularProgressIndicator()))
+ else if (_books.isEmpty && _loadFailed)
+ Expanded(
+ child: Center(
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Text(l.failedToLoad,
+ style: tt.bodyLarge
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ TextButton(
+ onPressed: () {
+ setState(() {
+ _isLoading = true;
+ _loadFailed = false;
+ });
+ _fetchFromApi();
+ },
+ child: Text(l.retry),
+ ),
+ ]),
+ ),
+ )
else if (_books.isEmpty)
Expanded(
child: Center(