Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Let you hide a book from your finished-this-year stats

Barnabas7bd39e29fc20
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 64015d86..464ab614 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -90,6 +90,30 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
'subscribed_podcasts', _subscribedPodcasts.toList());
}
+ // ── "Finished this year" local hide list ──
+
+ Future<void> _loadYearHidden() async {
+ _yearHiddenIds =
+ (await ScopedPrefs.getStringList('year_hidden_ids')).toSet();
+ }
+
+ /// Hide a finished book from Absorb's local "finished this year" count and
+ /// list. The server's finished date is untouched; this only affects Absorb.
+ Future<void> hideFromThisYear(String itemId) async {
+ if (itemId.isEmpty || !_yearHiddenIds.add(itemId)) return;
+ await ScopedPrefs.setStringList('year_hidden_ids', _yearHiddenIds.toList());
+ notifyListeners();
+ HomeWidgetService().refreshStats(force: true);
+ }
+
+ /// Undo a local hide so the book counts toward this year again.
+ Future<void> unhideFromThisYear(String itemId) async {
+ if (!_yearHiddenIds.remove(itemId)) return;
+ await ScopedPrefs.setStringList('year_hidden_ids', _yearHiddenIds.toList());
+ notifyListeners();
+ HomeWidgetService().refreshStats(force: true);
+ }
+
// ── Offline mode ──
Future<void> setManualOffline(bool value) async {
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index f6c5b402..ca250f0a 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -57,6 +57,9 @@ mixin _StateMixin on ChangeNotifier {
Set<String> _rollingDownloadSeries = {};
Set<String> _subscribedPodcasts = {};
+ // Book ids the user hid from the local "finished this year" stats list.
+ // Purely local; the server's finished date is left untouched.
+ Set<String> _yearHiddenIds = {};
bool _manualOffline = false;
bool _networkOffline = false;
@@ -158,6 +161,8 @@ mixin _StateMixin on ChangeNotifier {
if (p['isFinished'] != true) continue;
final ep = p['episodeId'];
if (ep is String && ep.isNotEmpty) continue;
+ final id = p['libraryItemId'];
+ if (id is String && _yearHiddenIds.contains(id)) continue;
final raw = p['finishedAt'];
if (raw is! num) continue;
final dt = DateTime.fromMillisecondsSinceEpoch(raw.toInt());
@@ -183,12 +188,16 @@ mixin _StateMixin on ChangeNotifier {
if (dt.year != year) continue;
final id = p['libraryItemId'] as String?;
if (id == null) continue;
+ if (_yearHiddenIds.contains(id)) continue;
entries.add(MapEntry(id, ts));
}
entries.sort((a, b) => b.value.compareTo(a.value));
return entries.map((e) => e.key).toList();
}
+ /// Book ids the user hid from the local "finished this year" list.
+ Set<String> get yearHiddenIds => _yearHiddenIds;
+
int get finishedEpisodesThisYearCount {
final year = DateTime.now().year;
var count = 0;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 7bcd1f60..c555d4f1 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -148,6 +148,7 @@ class LibraryProvider extends ChangeNotifier
await _loadManualAbsorbing();
await _loadRollingDownloadSeries();
await _loadSubscribedPodcasts();
+ await _loadYearHidden();
await _loadKnownEpisodeIds();
Future.microtask(() => checkSubscribedPodcasts());
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index efd53e23..7d72a39f 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -306,7 +306,14 @@ class _StatsScreenState extends State<StatsScreen>
child: _accentStatCard(tt, cs, Icons.auto_stories_rounded,
Colors.teal, '$_booksFinishedThisYear', l.statsBooksThisYear,
onTap: _booksFinishedThisYear > 0
- ? () => showFinishedBooksThisYearSheet(context)
+ ? () async {
+ await showFinishedBooksThisYearSheet(context);
+ if (mounted) {
+ setState(() => _booksFinishedThisYear = context
+ .read<LibraryProvider>()
+ .finishedBooksThisYearCount);
+ }
+ }
: null)),
if (_episodesFinishedThisYear > 0) ...[
const SizedBox(width: 8),
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 5d56ce1f..6ac8508d 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -12,6 +12,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'audio_player_service.dart';
import 'api_service.dart';
import 'download_service.dart';
+import 'scoped_prefs.dart';
import 'wear_player_service.dart';
const String _androidWidgetName = 'NowPlayingWidget';
@@ -700,7 +701,8 @@ class HomeWidgetService {
final today = _todaySeconds(dailyMap).round();
final week = _weekSeconds(dailyMap).round();
final streak = _currentStreak(dailyMap);
- final booksYear = _countBooksFinishedThisYear(me);
+ final hidden = (await ScopedPrefs.getStringList('year_hidden_ids')).toSet();
+ final booksYear = _countBooksFinishedThisYear(me, hidden);
debugPrint('[StatsWidget] Computed: today=${today}s week=${week}s streak=${streak}d booksThisYear=$booksYear (dailyMapKeys=${dailyMap.length})');
@@ -829,7 +831,7 @@ class HomeWidgetService {
return streak;
}
- int _countBooksFinishedThisYear(Map<String, dynamic>? me) {
+ int _countBooksFinishedThisYear(Map<String, dynamic>? me, Set<String> hidden) {
if (me == null) return 0;
final progress = me['mediaProgress'];
if (progress is! List) return 0;
@@ -842,6 +844,8 @@ class HomeWidgetService {
// count doesn't inflate with every finished podcast episode.
final episodeId = entry['episodeId'];
if (episodeId is String && episodeId.isNotEmpty) continue;
+ final id = entry['libraryItemId'];
+ if (id is String && hidden.contains(id)) continue;
final raw = entry['finishedAt'];
if (raw is! num) continue;
final dt = DateTime.fromMillisecondsSinceEpoch(raw.toInt());
diff --git a/lib/widgets/finished_books_this_year_sheet.dart b/lib/widgets/finished_books_this_year_sheet.dart
index dd90df6d..5b63c7f9 100644
--- a/lib/widgets/finished_books_this_year_sheet.dart
+++ b/lib/widgets/finished_books_this_year_sheet.dart
@@ -8,13 +8,14 @@ import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/download_service.dart';
import 'book_detail_sheet.dart';
+import 'overlay_toast.dart';
import 'stackable_sheet.dart';
/// Show a modal sheet listing every book the user has finished in the
/// current calendar year. Loads full item metadata on demand so it can
/// render covers + metadata + still-in-library detection for each one.
-void showFinishedBooksThisYearSheet(BuildContext context) {
- showStackableSheet(
+Future<void> showFinishedBooksThisYearSheet(BuildContext context) async {
+ await showStackableSheet(
context: context,
useSafeArea: true,
showHandle: true,
@@ -41,6 +42,7 @@ class _FinishedBooksThisYearSheetState
extends State<FinishedBooksThisYearSheet> {
bool _isLoading = true;
bool _gridView = false;
+ bool _showHidden = false;
List<Map<String, dynamic>> _items = [];
@override
@@ -56,7 +58,17 @@ class _FinishedBooksThisYearSheetState
final auth = context.read<AuthProvider>();
final lib = context.read<LibraryProvider>();
final api = auth.apiService;
- final ids = lib.finishedBooksThisYearIds;
+ final List<String> ids;
+ if (_showHidden) {
+ ids = lib.yearHiddenIds.toList()
+ ..sort((a, b) {
+ final fa = (lib.getProgressData(a)?['finishedAt'] as num?)?.toInt() ?? 0;
+ final fb = (lib.getProgressData(b)?['finishedAt'] as num?)?.toInt() ?? 0;
+ return fb.compareTo(fa);
+ });
+ } else {
+ ids = lib.finishedBooksThisYearIds;
+ }
if (api == null || ids.isEmpty) {
if (mounted) setState(() => _isLoading = false);
@@ -84,6 +96,62 @@ class _FinishedBooksThisYearSheetState
PlayerSettings.setSectionGridView(_gridView);
}
+ void _toggleShowHidden() {
+ setState(() {
+ _showHidden = !_showHidden;
+ _isLoading = true;
+ _items = [];
+ });
+ _load();
+ }
+
+ /// Long-press action: hide this book from Absorb's local "finished this year"
+ /// list. Spells out that the server's finished date is left alone.
+ Future<void> _confirmRemove(String itemId, String title, int? finishedAtMs) async {
+ final l = AppLocalizations.of(context)!;
+ final dateStr = finishedAtMs != null ? _fmtDate(finishedAtMs) : null;
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Remove from this year'),
+ content: Text(dateStr != null
+ ? 'The finished date will still be $dateStr on the server. This only removes "$title" from your Absorb books-this-year list.'
+ : 'The finished date stays on the server. This only removes "$title" from your Absorb books-this-year list.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Remove')),
+ ],
+ ),
+ );
+ if (confirmed != true || !mounted) return;
+ await context.read<LibraryProvider>().hideFromThisYear(itemId);
+ if (!mounted) return;
+ setState(() => _items.removeWhere((it) => (it['id'] as String?) == itemId));
+ showOverlayToast(context, 'Removed from this year', icon: Icons.remove_circle_outline_rounded);
+ }
+
+ /// Long-press action while viewing hidden books: add one back so it counts
+ /// toward this year again.
+ Future<void> _confirmRestore(String itemId, String title) async {
+ final l = AppLocalizations.of(context)!;
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Add back to this year'),
+ content: Text('Add "$title" back to your Absorb books-this-year list?'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Add back')),
+ ],
+ ),
+ );
+ if (confirmed != true || !mounted) return;
+ await context.read<LibraryProvider>().unhideFromThisYear(itemId);
+ if (!mounted) return;
+ setState(() => _items.removeWhere((it) => (it['id'] as String?) == itemId));
+ showOverlayToast(context, 'Added back to this year', icon: Icons.check_circle_outline_rounded);
+ }
+
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
@@ -98,13 +166,24 @@ class _FinishedBooksThisYearSheetState
Icon(Icons.auto_stories_rounded, size: 20, color: cs.primary),
const SizedBox(width: 10),
Expanded(
- child: Text(l.statsBooksThisYear,
+ child: Text(_showHidden ? 'Hidden from this year' : l.statsBooksThisYear,
style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),
maxLines: 1,
overflow: TextOverflow.ellipsis),
),
Text('${_items.length}',
style: tt.labelMedium?.copyWith(color: cs.onSurfaceVariant)),
+ if (lib.yearHiddenIds.isNotEmpty || _showHidden) ...[
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: _toggleShowHidden,
+ child: Icon(
+ _showHidden ? Icons.visibility_rounded : Icons.visibility_off_rounded,
+ size: 20,
+ color: _showHidden ? cs.primary : cs.onSurfaceVariant,
+ ),
+ ),
+ ],
const SizedBox(width: 12),
GestureDetector(
onTap: _toggleGridView,
@@ -122,7 +201,7 @@ class _FinishedBooksThisYearSheetState
? const Center(child: CircularProgressIndicator())
: _items.isEmpty
? Center(
- child: Text(l.noBooksFound,
+ child: Text(_showHidden ? 'Nothing hidden' : l.noBooksFound,
style: tt.bodyLarge
?.copyWith(color: cs.onSurfaceVariant)))
: _gridView
@@ -165,6 +244,10 @@ class _FinishedBooksThisYearSheetState
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => showBookDetailSheet(context, itemId),
+ onLongPress: () => _showHidden
+ ? _confirmRestore(itemId, title)
+ : _confirmRemove(itemId, title,
+ finishedAt is num ? finishedAt.toInt() : null),
borderRadius: BorderRadius.circular(14),
child: SizedBox(
height: 128,
@@ -247,6 +330,10 @@ class _FinishedBooksThisYearSheetState
return GestureDetector(
onTap: () => showBookDetailSheet(context, itemId),
+ onLongPress: () => _showHidden
+ ? _confirmRestore(itemId, title)
+ : _confirmRemove(
+ itemId, title, finishedAt is num ? finishedAt.toInt() : null),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [