A cross platform Audiobookshelf client for Android and iOS
Dart
Add Upcoming Releases - scan Audible for new/recent books across all series
Nathan Poulsoneedcac5c28cd
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex e3c00e5f..3a3b479c 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -17,6 +17,8 @@ import '../widgets/library_books_tab.dart';import '../widgets/library_series_tab.dart';import '../widgets/library_authors_tab.dart';import 'admin_podcasts_screen.dart';+import 'upcoming_releases_screen.dart';+import '../widgets/audible_series_sheet.dart' show showAudibleRegionPicker;/// Responsive grid column count based on available width./// Returns 3 on phones, scales up on tablets/iPads.@@ -1152,6 +1154,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_loadPage();},isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,+ onUpcomingReleases: tab == LibraryTab.series ? () {+ Navigator.pop(ctx);+ _openUpcomingReleases();+ } : null,),);}@@ -1361,63 +1367,76 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiWidget _buildFloatingTabBar(ColorScheme cs) {const labels = ['Library', 'Series', 'Authors'];- return Center(- child: ClipRRect(- borderRadius: BorderRadius.circular(24),- child: BackdropFilter(- filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),- child: Container(- padding: const EdgeInsets.all(4),- decoration: BoxDecoration(- color: cs.surface.withValues(alpha: 0.6),- borderRadius: BorderRadius.circular(24),- border: Border.all(color: cs.primary.withValues(alpha: 0.25)),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: List.generate(3, (i) {- final active = _currentTab == i;- return GestureDetector(- onTap: () {- if (active) {- _showSortFilterSheet(context, cs, Theme.of(context).textTheme);- } else {- _tabController?.animateTo(i);- }- },- child: AnimatedContainer(- duration: const Duration(milliseconds: 200),- curve: Curves.easeInOut,- padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),- decoration: BoxDecoration(- color: active ? cs.primary.withValues(alpha: 0.15) : Colors.transparent,- borderRadius: BorderRadius.circular(20),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- labels[i],- style: TextStyle(- fontSize: 13,- fontWeight: active ? FontWeight.w700 : FontWeight.w500,- color: active ? cs.primary : cs.onSurfaceVariant,- ),+ return Center(child: ClipRRect(+ borderRadius: BorderRadius.circular(24),+ child: BackdropFilter(+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),+ child: Container(+ padding: const EdgeInsets.all(4),+ decoration: BoxDecoration(+ color: cs.surface.withValues(alpha: 0.6),+ borderRadius: BorderRadius.circular(24),+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: List.generate(3, (i) {+ final active = _currentTab == i;+ return GestureDetector(+ onTap: () {+ if (active) {+ _showSortFilterSheet(context, cs, Theme.of(context).textTheme);+ } else {+ _tabController?.animateTo(i);+ }+ },+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 200),+ curve: Curves.easeInOut,+ padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),+ decoration: BoxDecoration(+ color: active ? cs.primary.withValues(alpha: 0.15) : Colors.transparent,+ borderRadius: BorderRadius.circular(20),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ labels[i],+ style: TextStyle(+ fontSize: 13,+ fontWeight: active ? FontWeight.w700 : FontWeight.w500,+ color: active ? cs.primary : cs.onSurfaceVariant,),- if (active) ...[- const SizedBox(width: 4),- Icon(Icons.sort_rounded, size: 14, color: cs.primary),- ],+ ),+ if (active) ...[+ const SizedBox(width: 4),+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),],- ),+ ],),- );- }),- ),+ ),+ );+ }),),),),- );+ ));+ }+++ Future<void> _openUpcomingReleases() async {+ final saved = await PlayerSettings.getAudibleRegion();+ if (saved.isEmpty) {+ if (!mounted) return;+ final chosen = await showAudibleRegionPicker(context, currentRegion: '');+ if (chosen == null || !mounted) return;+ await PlayerSettings.setAudibleRegion(chosen);+ }+ if (!mounted) return;+ Navigator.push(context, MaterialPageRoute(+ builder: (_) => const UpcomingReleasesScreen(),+ ));}Widget _buildFloatingSortButton(ColorScheme cs, TextTheme tt) {@@ -1749,3 +1768,4 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi);}}+diff --git a/lib/screens/upcoming_releases_screen.dart b/lib/screens/upcoming_releases_screen.dartnew file mode 100644index 00000000..f5d7bfaa--- /dev/null+++ b/lib/screens/upcoming_releases_screen.dart@@ -0,0 +1,709 @@+import 'package:flutter/material.dart';+import 'package:cached_network_image/cached_network_image.dart';+import 'package:provider/provider.dart';+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';+import '../services/api_service.dart';+import '../services/audio_player_service.dart';+import '../services/upcoming_releases_service.dart';+import '../widgets/absorb_page_header.dart';+import '../widgets/audible_series_sheet.dart';+import '../widgets/overlay_toast.dart';++class UpcomingReleasesScreen extends StatefulWidget {+ const UpcomingReleasesScreen({super.key});++ @override+ State<UpcomingReleasesScreen> createState() => _UpcomingReleasesScreenState();+}++class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {+ final _service = UpcomingReleasesService();+ String _region = 'us';+ bool _sortByDate = false;++ @override+ void initState() {+ super.initState();+ _service.addListener(_onServiceChanged);+ _initAndStart();+ }++ Future<void> _initAndStart() async {+ final saved = await PlayerSettings.getAudibleRegion();+ _region = saved.isNotEmpty ? saved : ApiService.debugRegion;+ _service.setRegion(_region);++ // If already running (e.g. came back to this screen), just attach+ if (_service.isRunning) {+ if (mounted) setState(() {});+ return;+ }++ // Try loading cache first+ final hasCache = await _service.loadCache();+ if (mounted) setState(() {});+ if (hasCache) {+ // If cache is stale, prompt for rescan+ if (_service.isCacheStale && mounted) {+ _showStalePrompt();+ }+ return;+ }++ // No cache - start a fresh scan+ _startScan();+ }++ void _startScan() {+ final auth = context.read<AuthProvider>();+ final lib = context.read<LibraryProvider>();+ final api = auth.apiService;+ final libraryId = lib.selectedLibraryId;+ if (api == null || libraryId == null) return;++ _service.start(api: api, libraryId: libraryId, region: _region);+ }++ void _onServiceChanged() {+ if (mounted) setState(() {});+ }++ Future<void> _changeRegion() async {+ final chosen = await showAudibleRegionPicker(context, currentRegion: _region);+ if (chosen == null || chosen == _region || !mounted) return;++ await PlayerSettings.setAudibleRegion(chosen);+ setState(() => _region = chosen);+ _service.setRegion(chosen);+ _startScan();+ }++ void _rescan() {+ _startScan();+ }++ void _showStalePrompt() {+ final days = DateTime.now().difference(_service.cacheTime!).inDays;+ showDialog(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('Rescan?'),+ content: Text(+ 'These results are $days days old. Release dates may have changed - would you like to rescan?',+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Not now')),+ FilledButton(onPressed: () { Navigator.pop(ctx); _rescan(); }, child: const Text('Rescan')),+ ],+ ),+ );+ }++ @override+ void dispose() {+ _service.removeListener(_onServiceChanged);+ super.dispose();+ }++ String _formatDate(String dateStr) {+ final date = DateTime.tryParse(dateStr);+ if (date == null) return dateStr;+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+ return '${months[date.month - 1]} ${date.day}, ${date.year}';+ }++ String _formatRuntime(dynamic minutes) {+ final mins = (minutes is num) ? minutes.toInt() : 0;+ if (mins <= 0) return '';+ final h = mins ~/ 60;+ final m = mins % 60;+ if (h > 0 && m > 0) return '${h}h ${m}m';+ if (h > 0) return '${h}h';+ return '${m}m';+ }++ void _showBookMenu(Map<String, dynamic> book, String seriesName) {+ showAudibleBookMenu(context,+ book: book,+ seriesName: seriesName,+ region: _region,+ extraActions: [+ ListTile(+ leading: Icon(Icons.refresh_rounded, color: Theme.of(context).colorScheme.primary, size: 22),+ title: const Text('Rescan Release Date', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),+ dense: true, visualDensity: VisualDensity.compact,+ onTap: () {+ Navigator.pop(context);+ _rescanBook(book['asin'] as String? ?? '');+ },+ ),+ ],+ );+ }++ Future<void> _rescanBook(String asin) async {+ if (!mounted) return;+ showOverlayToast(context, 'Rescanning...', icon: Icons.refresh_rounded);+ final updated = await _service.rescanBook(asin);+ if (!mounted) return;+ if (updated != null) {+ final newDate = updated['releaseDate'] as String? ?? '';+ if (newDate.isNotEmpty) {+ showOverlayToast(context, 'Updated - ${_formatDate(newDate)}', icon: Icons.check_rounded);+ } else {+ showOverlayToast(context, 'No release date found', icon: Icons.info_outline_rounded);+ }+ } else {+ showOverlayToast(context, 'Rescan failed', icon: Icons.error_outline_rounded);+ }+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ return Scaffold(+ body: SafeArea(+ child: Column(+ children: [+ AbsorbPageHeader(+ title: 'Upcoming Releases',+ actions: [+ // Sort by date toggle (only when scan is done and has results)+ if (_service.isComplete && _service.results.isNotEmpty)+ GestureDetector(+ onTap: () => setState(() => _sortByDate = !_sortByDate),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),+ decoration: BoxDecoration(+ color: _sortByDate ? cs.primary.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(20),+ border: _sortByDate ? Border.all(color: cs.primary.withValues(alpha: 0.3)) : null,+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.calendar_today_rounded, size: 13,+ color: _sortByDate ? cs.primary : cs.onSurfaceVariant),+ const SizedBox(width: 4),+ Text('Date', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600,+ color: _sortByDate ? cs.primary : cs.onSurfaceVariant)),+ ]),+ ),+ ),+ // Rescan button (only when not already scanning)+ if (_service.isComplete)+ GestureDetector(+ onTap: _rescan,+ child: Container(+ padding: const EdgeInsets.all(6),+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ shape: BoxShape.circle,+ ),+ child: Icon(Icons.refresh_rounded, size: 18, color: cs.onSurfaceVariant),+ ),+ ),+ // Region button+ GestureDetector(+ onTap: _changeRegion,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),+ decoration: BoxDecoration(+ color: cs.primary.withValues(alpha: 0.1),+ borderRadius: BorderRadius.circular(20),+ border: Border.all(color: cs.primary.withValues(alpha: 0.2)),+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.language_rounded, size: 14, color: cs.primary),+ const SizedBox(width: 4),+ Text(+ ApiService.audibleRegions[_region] ?? _region.toUpperCase(),+ style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.primary),+ ),+ ]),+ ),+ ),+ ],+ ),++ // Progress indicator+ if (_service.isRunning) ...[+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(4),+ child: LinearProgressIndicator(+ value: _service.totalSeries > 0+ ? _service.processedCount / _service.totalSeries+ : null,+ minHeight: 3,+ backgroundColor: cs.surfaceContainerHighest,+ color: cs.primary,+ ),+ ),+ const SizedBox(height: 6),+ Text(+ _service.currentSeriesName != null+ ? 'Checking ${_service.currentSeriesName}... (${_service.processedCount}/${_service.totalSeries})'+ : 'Loading series...',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ ),+ ),+ ],++ // Summary when complete+ if (_service.isComplete)+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),+ child: Row(children: [+ Text(+ _buildSummary(),+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ if (_service.hasCachedResults && _service.cacheTime != null) ...[+ const SizedBox(width: 6),+ Text(_cacheAgeLabel(), style: tt.bodySmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.5), fontSize: 11)),+ ],+ ]),+ ),++ const SizedBox(height: 8),++ // Results list+ Expanded(+ child: _buildContent(cs, tt),+ ),+ ],+ ),+ ),+ );+ }++ String _cacheAgeLabel() {+ final age = DateTime.now().difference(_service.cacheTime!);+ if (age.inDays == 0) return '(scanned today)';+ if (age.inDays == 1) return '(scanned yesterday)';+ return '(scanned ${age.inDays} days ago)';+ }++ String _buildSummary() {+ final totalUpcoming = _service.results.fold<int>(0, (sum, r) => sum + r.upcomingBooks.length);+ final totalRecent = _service.results.fold<int>(0, (sum, r) => sum + r.recentBooks.length);+ final parts = <String>[];+ if (totalUpcoming > 0) parts.add('$totalUpcoming upcoming');+ if (totalRecent > 0) parts.add('$totalRecent recent');+ if (parts.isEmpty) return 'No upcoming or recent releases found';+ final seriesCount = _service.results.length;+ return '${parts.join(', ')} across $seriesCount series';+ }++ Widget _buildContent(ColorScheme cs, TextTheme tt) {+ if (_service.error != null) {+ return Center(+ child: Padding(+ padding: const EdgeInsets.all(32),+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.error_outline_rounded, size: 48, color: cs.error.withValues(alpha: 0.5)),+ const SizedBox(height: 12),+ Text(_service.error!, style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),+ textAlign: TextAlign.center),+ ]),+ ),+ );+ }++ if (_service.isComplete && _service.results.isEmpty) {+ return Center(+ child: Padding(+ padding: const EdgeInsets.all(32),+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.event_available_rounded, size: 48, color: cs.primary.withValues(alpha: 0.5)),+ const SizedBox(height: 12),+ Text('No upcoming or recent releases found', style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),+ textAlign: TextAlign.center),+ const SizedBox(height: 4),+ Text('Checked ${_service.totalSeries} series on Audible',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6)),+ textAlign: TextAlign.center),+ ]),+ ),+ );+ }++ if (!_service.isRunning && !_service.isComplete && _service.results.isEmpty) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }++ if (_sortByDate && !_service.isRunning) {+ return _buildDateSortedList(cs, tt);+ }++ return ListView.builder(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),+ itemCount: _service.results.length + (_service.isRunning ? 1 : 0),+ itemBuilder: (context, index) {+ if (index >= _service.results.length) {+ return const Padding(+ padding: EdgeInsets.symmetric(vertical: 24),+ child: Center(child: CircularProgressIndicator(strokeWidth: 2)),+ );+ }+ return _buildSeriesSection(cs, tt, _service.results[index]);+ },+ );+ }++ Widget _buildDateSortedList(ColorScheme cs, TextTheme tt) {+ // Flatten all books with their series name and upcoming/recent status+ final allBooks = <({Map<String, dynamic> book, String seriesName, bool isUpcoming})>[];+ for (final result in _service.results) {+ for (final book in result.upcomingBooks) {+ allBooks.add((book: book, seriesName: result.seriesName, isUpcoming: true));+ }+ for (final book in result.recentBooks) {+ allBooks.add((book: book, seriesName: result.seriesName, isUpcoming: false));+ }+ }++ // Sort by release date (soonest first for upcoming, most recent first for recent)+ allBooks.sort((a, b) {+ final dateA = DateTime.tryParse(a.book['releaseDate'] as String? ?? '') ?? DateTime(2099);+ final dateB = DateTime.tryParse(b.book['releaseDate'] as String? ?? '') ?? DateTime(2099);+ return dateA.compareTo(dateB);+ });++ return ListView.builder(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),+ itemCount: allBooks.length,+ itemBuilder: (context, index) {+ final entry = allBooks[index];+ return _buildDateSortedCard(cs, tt, entry.book, entry.seriesName, entry.isUpcoming);+ },+ );+ }++ Widget _buildDateSortedCard(ColorScheme cs, TextTheme tt, Map<String, dynamic> book, String seriesName, bool isUpcoming) {+ final title = book['title'] as String? ?? '';+ final subtitle = book['subtitle'] as String? ?? '';+ final authors = book['authors'] as String? ?? '';+ final sequence = book['sequence'] as String? ?? '';+ final coverUrl = book['coverUrl'] as String? ?? '';+ final releaseDate = book['releaseDate'] as String? ?? '';+ final runtime = _formatRuntime(book['runtimeMinutes']);+ final isOwned = book['_owned'] == true;+ final isDark = Theme.of(context).brightness == Brightness.dark;+ final downloadGreen = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;++ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: GestureDetector(+ onTap: () => _showBookMenu(book, seriesName),+ child: Card(+ elevation: 0,+ color: isUpcoming+ ? cs.primaryContainer.withValues(alpha: 0.3)+ : isOwned+ ? cs.surfaceContainerHigh.withValues(alpha: 0.5)+ : cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ clipBehavior: Clip.antiAlias,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 100),+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ // Cover+ Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: 100,+ height: 100,+ child: Stack(children: [+ Positioned.fill(+ child: coverUrl.isNotEmpty+ ? CachedNetworkImage(+ imageUrl: coverUrl, fit: BoxFit.cover,+ placeholder: (_, __) => _placeholder(cs),+ errorWidget: (_, __, ___) => _placeholder(cs))+ : _placeholder(cs),+ ),+ if (sequence.isNotEmpty)+ Positioned(top: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.7), borderRadius: BorderRadius.circular(6)),+ child: Text('#$sequence', style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w600)),+ ),+ ),+ if (isUpcoming)+ Positioned(bottom: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6)),+ child: const Text('UPCOMING', style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w700)),+ ),+ ),+ if (!isUpcoming)+ Positioned(bottom: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(+ color: isOwned ? downloadGreen.withValues(alpha: 0.9) : cs.error.withValues(alpha: 0.9),+ borderRadius: BorderRadius.circular(6),+ ),+ child: Text(isOwned ? 'ADDED' : 'MISSING',+ style: const TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w700)),+ ),+ ),+ ]),+ ),+ ),+ // Details+ Expanded(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ // Series name label+ Text(seriesName, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.primary, fontSize: 10, fontWeight: FontWeight.w600)),+ const SizedBox(height: 2),+ Text(title, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),+ if (subtitle.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: 1),+ child: Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontSize: 11)),+ ),+ const SizedBox(height: 4),+ if (authors.isNotEmpty)+ Text(authors, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),+ const SizedBox(height: 4),+ Row(children: [+ if (releaseDate.isNotEmpty) ...[+ Icon(isUpcoming ? Icons.event_rounded : Icons.calendar_today_rounded,+ size: 11, color: isUpcoming ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 3),+ Text(_formatDate(releaseDate),+ style: TextStyle(fontSize: 10,+ fontWeight: isUpcoming ? FontWeight.w600 : FontWeight.w400,+ color: isUpcoming ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.5))),+ ],+ if (releaseDate.isNotEmpty && runtime.isNotEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6),+ child: Text('.', style: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 10)),+ ),+ if (runtime.isNotEmpty) ...[+ Icon(Icons.schedule_rounded, size: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 3),+ Text(runtime, style: TextStyle(fontSize: 10, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),+ ],+ ]),+ ],+ ),+ ),+ ),+ ]),+ ),+ ),+ ),+ );+ }++ Widget _buildSeriesSection(ColorScheme cs, TextTheme tt, UpcomingSeriesResult result) {+ final totalCount = result.upcomingBooks.length + result.recentBooks.length;+ return Padding(+ padding: const EdgeInsets.only(bottom: 16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // Series header+ Padding(+ padding: const EdgeInsets.fromLTRB(4, 0, 4, 8),+ child: Row(children: [+ Expanded(+ child: Text(+ result.seriesName,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ const SizedBox(width: 8),+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),+ decoration: BoxDecoration(+ color: cs.primary.withValues(alpha: 0.12),+ borderRadius: BorderRadius.circular(10),+ ),+ child: Text(+ '$totalCount',+ style: TextStyle(fontSize: 11, fontWeight: FontWeight.w700, color: cs.primary),+ ),+ ),+ ]),+ ),+ // Upcoming books+ ...result.upcomingBooks.map((book) => _buildBookCard(cs, tt, book, result.seriesName, isUpcoming: true)),+ // Recent releases+ ...result.recentBooks.map((book) => _buildBookCard(cs, tt, book, result.seriesName, isUpcoming: false)),+ ],+ ),+ );+ }++ Widget _buildBookCard(ColorScheme cs, TextTheme tt, Map<String, dynamic> book, String seriesName, {required bool isUpcoming}) {+ final title = book['title'] as String? ?? '';+ final subtitle = book['subtitle'] as String? ?? '';+ final authors = book['authors'] as String? ?? '';+ final narrators = book['narrators'] as String? ?? '';+ final sequence = book['sequence'] as String? ?? '';+ final coverUrl = book['coverUrl'] as String? ?? '';+ final releaseDate = book['releaseDate'] as String? ?? '';+ final runtime = _formatRuntime(book['runtimeMinutes']);+ final isOwned = book['_owned'] == true;+ final isDark = Theme.of(context).brightness == Brightness.dark;+ final downloadGreen = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;++ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: GestureDetector(+ onTap: () => _showBookMenu(book, seriesName),+ child: Card(+ elevation: 0,+ color: isUpcoming+ ? cs.primaryContainer.withValues(alpha: 0.3)+ : isOwned+ ? cs.surfaceContainerHigh.withValues(alpha: 0.5)+ : cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ clipBehavior: Clip.antiAlias,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 100),+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ // Cover+ Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: 100,+ height: 100,+ child: Stack(children: [+ Positioned.fill(+ child: coverUrl.isNotEmpty+ ? CachedNetworkImage(+ imageUrl: coverUrl, fit: BoxFit.cover,+ placeholder: (_, __) => _placeholder(cs),+ errorWidget: (_, __, ___) => _placeholder(cs))+ : _placeholder(cs),+ ),+ if (sequence.isNotEmpty)+ Positioned(top: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.7), borderRadius: BorderRadius.circular(6)),+ child: Text('#$sequence', style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w600)),+ ),+ ),+ if (isUpcoming)+ Positioned(bottom: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6)),+ child: const Text('UPCOMING', style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w700)),+ ),+ ),+ if (!isUpcoming)+ Positioned(bottom: 4, left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),+ decoration: BoxDecoration(+ color: isOwned+ ? downloadGreen.withValues(alpha: 0.9)+ : cs.error.withValues(alpha: 0.9),+ borderRadius: BorderRadius.circular(6),+ ),+ child: Text(+ isOwned ? 'ADDED' : 'MISSING',+ style: const TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w700),+ ),+ ),+ ),+ ]),+ ),+ ),+ // Details+ Expanded(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(title, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),+ if (subtitle.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: 1),+ child: Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontSize: 11)),+ ),+ const SizedBox(height: 6),+ if (authors.isNotEmpty)+ Text(authors, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),+ if (narrators.isNotEmpty)+ Text('Narrated by $narrators', maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6), fontSize: 10)),+ const SizedBox(height: 4),+ Row(children: [+ if (releaseDate.isNotEmpty) ...[+ Icon(isUpcoming ? Icons.event_rounded : Icons.calendar_today_rounded,+ size: 11, color: isUpcoming ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 3),+ Text(_formatDate(releaseDate),+ style: TextStyle(fontSize: 10,+ fontWeight: isUpcoming ? FontWeight.w600 : FontWeight.w400,+ color: isUpcoming ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.5))),+ ],+ if (releaseDate.isNotEmpty && runtime.isNotEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6),+ child: Text('.', style: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 10)),+ ),+ if (runtime.isNotEmpty) ...[+ Icon(Icons.schedule_rounded, size: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 3),+ Text(runtime, style: TextStyle(fontSize: 10, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),+ ],+ ]),+ ],+ ),+ ),+ ),+ ]),+ ),+ ),+ ),+ );+ }++ Widget _placeholder(ColorScheme cs) {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Center(child: Icon(Icons.auto_stories_rounded, color: cs.onSurface.withValues(alpha: 0.15), size: 28)),+ );+ }+}diff --git a/lib/services/upcoming_releases_service.dart b/lib/services/upcoming_releases_service.dartnew file mode 100644index 00000000..a89a0b49--- /dev/null+++ b/lib/services/upcoming_releases_service.dart@@ -0,0 +1,607 @@+import 'dart:convert';+import 'package:flutter/foundation.dart';+import 'package:flutter_local_notifications/flutter_local_notifications.dart';+import 'package:shared_preferences/shared_preferences.dart';+import 'api_service.dart';++/// Result for a single series that has upcoming or recently released books.+class UpcomingSeriesResult {+ final String seriesId;+ final String seriesName;+ final String audibleAsin;+ final List<Map<String, dynamic>> upcomingBooks;+ final List<Map<String, dynamic>> recentBooks; // released in last 30 days++ UpcomingSeriesResult({+ required this.seriesId,+ required this.seriesName,+ required this.audibleAsin,+ required this.upcomingBooks,+ this.recentBooks = const [],+ });++ Map<String, dynamic> toJson() => {+ 'seriesId': seriesId,+ 'seriesName': seriesName,+ 'audibleAsin': audibleAsin,+ 'upcomingBooks': upcomingBooks,+ 'recentBooks': recentBooks,+ };++ factory UpcomingSeriesResult.fromJson(Map<String, dynamic> json) => UpcomingSeriesResult(+ seriesId: json['seriesId'] as String? ?? '',+ seriesName: json['seriesName'] as String? ?? '',+ audibleAsin: json['audibleAsin'] as String? ?? '',+ upcomingBooks: (json['upcomingBooks'] as List<dynamic>?)+ ?.map((e) => Map<String, dynamic>.from(e as Map))+ .toList() ?? [],+ recentBooks: (json['recentBooks'] as List<dynamic>?)+ ?.map((e) => Map<String, dynamic>.from(e as Map))+ .toList() ?? [],+ );+}++/// Scans library series for upcoming Audible releases.+///+/// Singleton service that survives screen navigation and continues in the+/// background. Results are cached to SharedPreferences so they persist+/// across app restarts.+class UpcomingReleasesService extends ChangeNotifier {+ // Singleton+ static final UpcomingReleasesService _instance = UpcomingReleasesService._();+ factory UpcomingReleasesService() => _instance;+ UpcomingReleasesService._();++ final List<UpcomingSeriesResult> _results = [];+ List<UpcomingSeriesResult> get results => _results;++ bool _isRunning = false;+ bool get isRunning => _isRunning;++ bool _isComplete = false;+ bool get isComplete => _isComplete;++ bool _hasCachedResults = false;+ bool get hasCachedResults => _hasCachedResults;++ int _processedCount = 0;+ int get processedCount => _processedCount;++ int _totalSeries = 0;+ int get totalSeries => _totalSeries;++ String? _currentSeriesName;+ String? get currentSeriesName => _currentSeriesName;++ String? _error;+ String? get error => _error;++ String _region = 'us';+ String get region => _region;++ int _generation = 0;++ // Cache: series ID -> Audible ASIN (or empty string if unresolvable)+ final Map<String, String> _asinCache = {};+ // Cache: Audible ASIN -> discovered books+ final Map<String, List<Map<String, dynamic>>> _discoveryCache = {};++ // Notification+ static const _notifChannelId = 'absorb_upcoming_scan';+ static const _notifChannelName = 'Upcoming Release Scan';+ static const _notifChannelDesc = 'Shows progress while scanning for upcoming releases';+ static const _scanNotifId = 9100;+ static const _completeNotifId = 9101;++ // Persistence keys+ static const _cacheKey = 'upcomingReleasesCache';+ static const _cacheTimeKey = 'upcomingReleasesCacheTime';+ static const _cacheRegionKey = 'upcomingReleasesCacheRegion';++ DateTime? _cacheTime;+ DateTime? get cacheTime => _cacheTime;++ /// Whether the cache is older than 2 weeks (suggest rescan).+ bool get isCacheStale =>+ _cacheTime != null && DateTime.now().difference(_cacheTime!).inDays >= 14;++ /// Load cached results from SharedPreferences.+ /// Returns true if valid cache was loaded (regardless of age).+ Future<bool> loadCache() async {+ try {+ final prefs = await SharedPreferences.getInstance();+ final cacheTimeMs = prefs.getInt(_cacheTimeKey) ?? 0;+ final cachedRegion = prefs.getString(_cacheRegionKey) ?? '';+ if (cacheTimeMs == 0) return false;+ if (cachedRegion != _region) return false;++ final json = prefs.getString(_cacheKey);+ if (json == null || json.isEmpty) return false;++ final list = jsonDecode(json) as List<dynamic>;+ _results.clear();+ for (final item in list) {+ _results.add(UpcomingSeriesResult.fromJson(item as Map<String, dynamic>));+ }+ _cacheTime = DateTime.fromMillisecondsSinceEpoch(cacheTimeMs);+ _hasCachedResults = true;+ _isComplete = true;+ notifyListeners();+ return true;+ } catch (e) {+ debugPrint('[Upcoming] loadCache error: $e');+ return false;+ }+ }++ /// Save current results to SharedPreferences.+ Future<void> _saveCache() async {+ try {+ final prefs = await SharedPreferences.getInstance();+ final json = jsonEncode(_results.map((r) => r.toJson()).toList());+ await prefs.setString(_cacheKey, json);+ await prefs.setInt(_cacheTimeKey, DateTime.now().millisecondsSinceEpoch);+ await prefs.setString(_cacheRegionKey, _region);+ } catch (e) {+ debugPrint('[Upcoming] saveCache error: $e');+ }+ }++ /// Start scanning all series in the library.+ Future<void> start({+ required ApiService api,+ required String libraryId,+ required String region,+ }) async {+ if (_isRunning) return;+ _generation++;+ final gen = _generation;+ _region = region;++ _isRunning = true;+ _isComplete = false;+ _processedCount = 0;+ _totalSeries = 0;+ _error = null;+ _results.clear();+ _hasCachedResults = false;+ _currentSeriesName = null;+ notifyListeners();++ await _showScanNotification('Starting scan...');++ try {+ // First page to get total count+ final firstPage = await api.getLibrarySeries(libraryId, page: 0, limit: 50);+ if (_generation != gen) return;+ if (firstPage == null) {+ _error = 'Failed to load series';+ _isRunning = false;+ await _cancelScanNotification();+ notifyListeners();+ return;+ }++ _totalSeries = (firstPage['total'] as int?) ?? 0;+ notifyListeners();++ if (_totalSeries == 0) {+ _isRunning = false;+ _isComplete = true;+ await _cancelScanNotification();+ notifyListeners();+ return;+ }++ // Process first page+ final firstResults = (firstPage['results'] as List<dynamic>?) ?? [];+ await _processBatch(api, firstResults, gen);+ if (_generation != gen) return;++ // Fetch remaining pages+ final totalPages = (_totalSeries / 50).ceil();+ for (var page = 1; page < totalPages; page++) {+ if (_generation != gen) return;+ final pageData = await api.getLibrarySeries(libraryId, page: page, limit: 50);+ if (_generation != gen) return;+ if (pageData == null) continue;+ final pageResults = (pageData['results'] as List<dynamic>?) ?? [];+ await _processBatch(api, pageResults, gen);+ }++ if (_generation != gen) return;+ _isRunning = false;+ _isComplete = true;+ _currentSeriesName = null;+ notifyListeners();++ await _saveCache();+ await _cancelScanNotification();+ await _showCompleteNotification();+ } catch (e) {+ if (_generation != gen) return;+ debugPrint('[Upcoming] scan error: $e');+ _error = 'Scan failed: $e';+ _isRunning = false;+ await _cancelScanNotification();+ notifyListeners();+ }+ }++ /// Process a batch of series from one API page.+ Future<void> _processBatch(ApiService api, List<dynamic> seriesList, int gen) async {+ for (final s in seriesList) {+ if (_generation != gen) return;+ if (s is! Map<String, dynamic>) {+ _processedCount++;+ notifyListeners();+ continue;+ }++ final seriesId = s['id'] as String? ?? '';+ final seriesName = s['name'] as String? ?? 'Unknown Series';+ final books = s['books'] as List<dynamic>? ?? [];++ _currentSeriesName = seriesName;+ notifyListeners();++ // Update scan notification periodically+ if (_processedCount % 5 == 0) {+ await _showScanNotification(+ 'Checking $seriesName... (${_processedCount + 1}/$_totalSeries)',+ );+ }++ // Try to resolve the Audible series ASIN+ String? audibleAsin;+ if (_asinCache.containsKey(seriesId)) {+ final cached = _asinCache[seriesId]!;+ audibleAsin = cached.isEmpty ? null : cached;+ debugPrint('[Upcoming] $seriesName: ASIN cache ${cached.isEmpty ? "miss (no ASIN)" : cached}');+ } else {+ audibleAsin = await _resolveSeriesAsin(books, seriesName, gen);+ if (_generation != gen) return;+ _asinCache[seriesId] = audibleAsin ?? '';+ debugPrint('[Upcoming] $seriesName: resolved ASIN=${audibleAsin ?? "NONE"} (${books.length} books checked)');+ }++ if (audibleAsin != null) {+ // Collect owned titles and ASINs from library books for ownership check+ final ownedTitles = <String>{};+ final ownedAsins = <String>{};+ for (final b in books) {+ if (b is! Map<String, dynamic>) continue;+ final media = b['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String? ?? '';+ final asin = metadata['asin'] as String? ?? '';+ if (title.isNotEmpty) ownedTitles.add(title);+ if (asin.isNotEmpty) ownedAsins.add(asin);+ }++ // Get all books in the series from Audible+ List<Map<String, dynamic>> allBooks;+ if (_discoveryCache.containsKey(audibleAsin)) {+ allBooks = _discoveryCache[audibleAsin]!;+ } else {+ allBooks = [];+ for (var attempt = 0; attempt < 3; attempt++) {+ if (_generation != gen) return;+ try {+ allBooks = await ApiService.discoverAudibleSeries(audibleAsin, region: _region);+ if (_generation != gen) return;+ _discoveryCache[audibleAsin] = allBooks;+ break;+ } catch (e) {+ debugPrint('[Upcoming] discover error for $seriesName (attempt ${attempt + 1}/3): $e');+ if (attempt < 2) await Future.delayed(const Duration(seconds: 2));+ }+ }+ }++ debugPrint('[Upcoming] $seriesName: discovered ${allBooks.length} books on Audible');++ // Filter to upcoming and recently released+ final upcoming = allBooks.where(_isUpcoming).toList();+ final recent = <Map<String, dynamic>>[];+ for (final book in allBooks) {+ if (_isRecentRelease(book)) {+ final owned = _isOwnedBook(book, ownedTitles, ownedAsins);+ recent.add({...book, '_owned': owned});+ }+ }++ if (upcoming.isNotEmpty || recent.isNotEmpty) {+ debugPrint('[Upcoming] $seriesName: ${upcoming.length} upcoming, ${recent.length} recent');+ _results.add(UpcomingSeriesResult(+ seriesId: seriesId,+ seriesName: seriesName,+ audibleAsin: audibleAsin,+ upcomingBooks: upcoming,+ recentBooks: recent,+ ));+ }+ }++ _processedCount++;+ notifyListeners();++ // Small delay between series to be nice to Audible API+ if (_generation == gen) {+ await Future.delayed(const Duration(milliseconds: 300));+ }+ }+ }++ /// Rescan a single book to refresh its release date and details.+ /// Returns the updated book data, or null on failure.+ Future<Map<String, dynamic>?> rescanBook(String asin) async {+ try {+ final details = await ApiService.getAudibleBookDetails(asin, region: _region);+ if (details == null) return null;++ final authors = (details['authors'] as List<dynamic>? ?? [])+ .map((a) => (a as Map<String, dynamic>)['name'] ?? '').join(', ');+ final narrators = (details['narrators'] as List<dynamic>? ?? [])+ .map((n) => (n as Map<String, dynamic>)['name'] ?? '').join(', ');+ final rating = details['rating'] as Map<String, dynamic>?;++ final updated = <String, dynamic>{+ 'asin': asin,+ 'title': details['title'] ?? '',+ 'subtitle': details['subtitle'] ?? '',+ 'authors': authors,+ 'narrators': narrators,+ 'releaseDate': details['release_date'] ?? '',+ 'runtimeMinutes': details['runtime_length_min'] ?? 0,+ 'rating': rating?['overall_distribution']?['display_average_rating'] ?? 0.0,+ 'numRatings': rating?['overall_distribution']?['num_ratings'] ?? 0,+ 'coverUrl': details['product_images']?['500'] ?? details['product_images']?['1024'] ?? '',+ 'sequence': '',+ 'sort': '0',+ 'publisherSummary': details['publisher_summary'] ?? '',+ };++ // Update in results (check both upcoming and recent lists)+ for (final result in _results) {+ for (var i = 0; i < result.upcomingBooks.length; i++) {+ if (result.upcomingBooks[i]['asin'] == asin) {+ updated['sequence'] = result.upcomingBooks[i]['sequence'] ?? '';+ updated['sort'] = result.upcomingBooks[i]['sort'] ?? '0';+ updated['allAsins'] = result.upcomingBooks[i]['allAsins'] ?? <String>[asin];++ if (_isUpcoming(updated)) {+ result.upcomingBooks[i] = updated;+ } else {+ result.upcomingBooks.removeAt(i);+ }+ break;+ }+ }+ for (var i = 0; i < result.recentBooks.length; i++) {+ if (result.recentBooks[i]['asin'] == asin) {+ updated['sequence'] = result.recentBooks[i]['sequence'] ?? '';+ updated['sort'] = result.recentBooks[i]['sort'] ?? '0';+ updated['allAsins'] = result.recentBooks[i]['allAsins'] ?? <String>[asin];+ updated['_owned'] = result.recentBooks[i]['_owned'] ?? false;+ result.recentBooks[i] = updated;+ break;+ }+ }+ }++ // Remove empty series results+ _results.removeWhere((r) => r.upcomingBooks.isEmpty && r.recentBooks.isEmpty);+ notifyListeners();+ await _saveCache();+ return updated;+ } catch (e) {+ debugPrint('[Upcoming] rescanBook error: $e');+ return null;+ }+ }++ /// Try to find the Audible series ASIN from the books' metadata ASINs via Audnexus.+ Future<String?> _resolveSeriesAsin(List<dynamic> books, String seriesName, int gen) async {+ int booksWithAsin = 0;+ int audnexusAttempts = 0;+ for (final book in books) {+ if (_generation != gen) return null;+ if (book is! Map<String, dynamic>) continue;++ final media = book['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final bookAsin = metadata['asin'] as String? ?? '';+ if (bookAsin.isEmpty) continue;+ booksWithAsin++;+ audnexusAttempts++;++ for (var attempt = 0; attempt < 3; attempt++) {+ if (_generation != gen) return null;+ try {+ final audnexus = await ApiService.getAudnexusBook(bookAsin, region: _region);+ if (_generation != gen) return null;+ if (audnexus == null) {+ debugPrint('[Upcoming] $seriesName: Audnexus returned null for ASIN=$bookAsin');+ break; // null response means the book isn't on Audnexus, no point retrying+ }++ final primary = audnexus['seriesPrimary'] as Map<String, dynamic>?;+ if (primary != null && primary['asin'] != null) {+ debugPrint('[Upcoming] $seriesName: found via seriesPrimary from book ASIN=$bookAsin');+ return primary['asin'] as String;+ }+ final secondary = audnexus['seriesSecondary'] as Map<String, dynamic>?;+ if (secondary != null && secondary['asin'] != null) {+ debugPrint('[Upcoming] $seriesName: found via seriesSecondary from book ASIN=$bookAsin');+ return secondary['asin'] as String;+ }+ debugPrint('[Upcoming] $seriesName: Audnexus has no series ASIN for book ASIN=$bookAsin');+ break; // got a valid response but no series info, no point retrying+ } catch (e) {+ debugPrint('[Upcoming] $seriesName: Audnexus error for $bookAsin (attempt ${attempt + 1}/3): $e');+ if (attempt < 2) {+ await Future.delayed(const Duration(seconds: 2));+ }+ }+ }+ }+ debugPrint('[Upcoming] $seriesName: no series ASIN found ($booksWithAsin books had ASINs, $audnexusAttempts checked)');+ return null;+ }++ bool _isUpcoming(Map<String, dynamic> book) {+ final dateStr = book['releaseDate'] as String? ?? '';+ if (dateStr.isEmpty) return false;+ final date = DateTime.tryParse(dateStr);+ if (date == null) return false;+ final now = DateTime.now();+ if (date.year > now.year + 5) return false;+ return date.isAfter(now);+ }++ /// Check if a book was released within the last 30 days.+ bool _isRecentRelease(Map<String, dynamic> book) {+ final dateStr = book['releaseDate'] as String? ?? '';+ if (dateStr.isEmpty) return false;+ final date = DateTime.tryParse(dateStr);+ if (date == null) return false;+ final now = DateTime.now();+ if (date.isAfter(now)) return false; // upcoming, not recent+ return now.difference(date).inDays <= 30;+ }++ static final _parenthetical = RegExp(r'\s*\([^)]*\)\s*');+ static final _nonAlphaNum = RegExp(r'[^a-z0-9 ]');+ static final _multiSpace = RegExp(r'\s+');++ String _normalizeTitle(String title) {+ return title+ .toLowerCase()+ .replaceAll(_parenthetical, ' ')+ .replaceAll(_nonAlphaNum, ' ')+ .replaceAll(_multiSpace, ' ')+ .trim();+ }++ /// Check if a discovered Audible book is owned in the library.+ bool _isOwnedBook(Map<String, dynamic> book, Set<String> ownedTitles, Set<String> ownedAsins) {+ final asin = book['asin'] as String? ?? '';+ if (ownedAsins.contains(asin)) return true;+ final allAsins = book['allAsins'] as List<dynamic>? ?? [];+ for (final a in allAsins) {+ if (ownedAsins.contains(a)) return true;+ }+ final title = _normalizeTitle(book['title'] as String? ?? '');+ if (title.isEmpty) return false;+ for (final owned in ownedTitles) {+ if (_normalizeTitle(owned) == title) return true;+ }+ return false;+ }++ /// Cancel the current scan.+ void cancel() {+ _generation++;+ _isRunning = false;+ _currentSeriesName = null;+ _cancelScanNotification();+ notifyListeners();+ }++ /// Set region (for cache loading before scan).+ void setRegion(String region) => _region = region;++ // ─── Notifications ───────────────────────────────────────────++ Future<void> _showScanNotification(String body) async {+ try {+ final plugin = FlutterLocalNotificationsPlugin();+ final androidPlugin = plugin.resolvePlatformSpecificImplementation<+ AndroidFlutterLocalNotificationsPlugin>();+ if (androidPlugin != null) {+ await androidPlugin.createNotificationChannel(+ const AndroidNotificationChannel(+ _notifChannelId,+ _notifChannelName,+ description: _notifChannelDesc,+ importance: Importance.low,+ showBadge: false,+ ),+ );+ }++ final progress = _totalSeries > 0 ? _processedCount : 0;+ final max = _totalSeries > 0 ? _totalSeries : 0;++ await plugin.show(+ _scanNotifId,+ 'Scanning for upcoming releases',+ body,+ NotificationDetails(+ android: AndroidNotificationDetails(+ _notifChannelId,+ _notifChannelName,+ channelDescription: _notifChannelDesc,+ importance: Importance.low,+ priority: Priority.low,+ ongoing: true,+ autoCancel: false,+ showProgress: max > 0,+ maxProgress: max,+ progress: progress,+ icon: 'drawable/ic_notification',+ ),+ ),+ );+ } catch (e) {+ debugPrint('[Upcoming] notification error: $e');+ }+ }++ Future<void> _cancelScanNotification() async {+ try {+ await FlutterLocalNotificationsPlugin().cancel(_scanNotifId);+ } catch (_) {}+ }++ Future<void> _showCompleteNotification() async {+ try {+ final totalBooks = _results.fold<int>(0, (sum, r) => sum + r.upcomingBooks.length);+ if (totalBooks == 0) return;++ final plugin = FlutterLocalNotificationsPlugin();+ final androidPlugin = plugin.resolvePlatformSpecificImplementation<+ AndroidFlutterLocalNotificationsPlugin>();+ if (androidPlugin != null) {+ await androidPlugin.createNotificationChannel(+ const AndroidNotificationChannel(+ _notifChannelId,+ _notifChannelName,+ description: _notifChannelDesc,+ importance: Importance.defaultImportance,+ ),+ );+ }++ final seriesCount = _results.length;+ await plugin.show(+ _completeNotifId,+ 'Upcoming releases found!',+ '$totalBooks upcoming across $seriesCount series',+ const NotificationDetails(+ android: AndroidNotificationDetails(+ _notifChannelId,+ _notifChannelName,+ channelDescription: _notifChannelDesc,+ importance: Importance.defaultImportance,+ priority: Priority.defaultPriority,+ icon: 'drawable/ic_notification',+ ),+ ),+ );+ } catch (e) {+ debugPrint('[Upcoming] complete notification error: $e');+ }+ }+}diff --git a/lib/widgets/audible_series_sheet.dart b/lib/widgets/audible_series_sheet.dartindex 198196aa..126ecb02 100644--- a/lib/widgets/audible_series_sheet.dart+++ b/lib/widgets/audible_series_sheet.dart@@ -1,7 +1,10 @@+import 'dart:io';import 'package:flutter/material.dart';import 'package:cached_network_image/cached_network_image.dart';+import 'package:url_launcher/url_launcher.dart';import '../services/api_service.dart';import '../services/player_settings.dart';+import 'overlay_toast.dart';import 'stackable_sheet.dart';/// Show a bottom sheet with Audible series discovery results.@@ -84,59 +87,13 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {}}- void _showRegionPicker() {- final cs = Theme.of(context).colorScheme;- final tt = Theme.of(context).textTheme;- showModalBottomSheet(- context: context,- backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(24)),- ),- isScrollControlled: true,- constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.6),- builder: (ctx) => SafeArea(- child: Column(mainAxisSize: MainAxisSize.min, children: [- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),- child: Column(children: [- Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),- decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),- Text('Audible Region', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),- const SizedBox(height: 12),- ]),- ),- Flexible(- child: ListView(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),- shrinkWrap: true,- children: ApiService.audibleRegions.entries.map((e) => Padding(- padding: const EdgeInsets.only(bottom: 6),- child: GestureDetector(- onTap: () {- Navigator.pop(ctx);- if (e.key != _region) {- setState(() => _region = e.key);- PlayerSettings.setAudibleRegion(e.key);- _fetchSeries();- }- },- child: Container(height: 40,- decoration: BoxDecoration(- color: e.key == _region ? cs.primary.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(14),- border: Border.all(color: e.key == _region ? cs.primary.withValues(alpha: 0.3) : cs.onSurface.withValues(alpha: 0.1)),- ),- child: Center(child: Text(e.value, style: TextStyle(- color: e.key == _region ? cs.primary : cs.onSurfaceVariant,- fontSize: 13, fontWeight: FontWeight.w500)))),- ),- )).toList(),- ),- ),- ]),- ),- );+ void _showRegionPicker() async {+ final chosen = await showAudibleRegionPicker(context, currentRegion: _region);+ if (chosen != null && chosen != _region && mounted) {+ setState(() => _region = chosen);+ PlayerSettings.setAudibleRegion(chosen);+ _fetchSeries();+ }}static final _parenthetical = RegExp(r'\s*\([^)]*\)\s*');@@ -342,7 +299,10 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {return Padding(padding: const EdgeInsets.only(bottom: 8),- child: Card(+ child: GestureDetector(+ onTap: () => showAudibleBookMenu(context,+ book: book, seriesName: widget.seriesName, region: _region),+ child: Card(elevation: 0,color: upcoming? cs.primaryContainer.withValues(alpha: 0.3)@@ -463,6 +423,7 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {]),),),+ ),);}@@ -473,3 +434,180 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {);}}++/// Shared Audible region picker bottom sheet.+/// Returns the selected region code, or null if dismissed.+Future<String?> showAudibleRegionPicker(BuildContext context, {required String currentRegion}) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ return showModalBottomSheet<String>(+ context: context,+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),+ ),+ isScrollControlled: true,+ constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.6),+ builder: (ctx) => SafeArea(+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),+ child: Column(children: [+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),+ decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),+ Text('Audible Region', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ const SizedBox(height: 12),+ ]),+ ),+ Flexible(+ child: ListView(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),+ shrinkWrap: true,+ children: ApiService.audibleRegions.entries.map((e) => Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: GestureDetector(+ onTap: () => Navigator.pop(ctx, e.key),+ child: Container(height: 40,+ decoration: BoxDecoration(+ color: e.key == currentRegion ? cs.primary.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: e.key == currentRegion ? cs.primary.withValues(alpha: 0.3) : cs.onSurface.withValues(alpha: 0.1)),+ ),+ child: Center(child: Text(e.value, style: TextStyle(+ color: e.key == currentRegion ? cs.primary : cs.onSurfaceVariant,+ fontSize: 13, fontWeight: FontWeight.w500)))),+ ),+ )).toList(),+ ),+ ),+ ]),+ ),+ );+}++/// Show a bottom sheet menu for an Audible book with Open, Calendar, etc.+void showAudibleBookMenu(BuildContext context, {+ required Map<String, dynamic> book,+ required String seriesName,+ required String region,+ List<Widget> extraActions = const [],+}) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final title = book['title'] as String? ?? '';+ final asin = book['asin'] as String? ?? '';+ final releaseDate = book['releaseDate'] as String? ?? '';++ showModalBottomSheet(+ context: context,+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),+ ),+ builder: (ctx) => SafeArea(+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(top: 8, bottom: 12),+ decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 20),+ child: Text(title, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600),+ maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center),+ ),+ if (releaseDate.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(_formatBookDate(releaseDate),+ style: tt.bodySmall?.copyWith(color: cs.primary, fontWeight: FontWeight.w600)),+ ),+ const SizedBox(height: 12),+ if (asin.isNotEmpty)+ ListTile(+ leading: Icon(Icons.open_in_new_rounded, color: cs.primary, size: 22),+ title: const Text('Open on Audible', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),+ dense: true, visualDensity: VisualDensity.compact,+ onTap: () {+ Navigator.pop(ctx);+ _openOnAudible(context, asin, region);+ },+ ),+ if (releaseDate.isNotEmpty)+ ListTile(+ leading: Icon(Icons.calendar_month_rounded, color: cs.primary, size: 22),+ title: const Text('Add to Calendar', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),+ dense: true, visualDensity: VisualDensity.compact,+ onTap: () {+ Navigator.pop(ctx);+ _addToCalendar(context, title, seriesName, releaseDate);+ },+ ),+ ...extraActions,+ const SizedBox(height: 8),+ ]),+ ),+ );+}++String _formatBookDate(String dateStr) {+ final date = DateTime.tryParse(dateStr);+ if (date == null) return dateStr;+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+ return '${months[date.month - 1]} ${date.day}, ${date.year}';+}++String _audibleTldForRegion(String region) {+ const tlds = {+ 'us': '.com', 'uk': '.co.uk', 'gb': '.co.uk', 'au': '.com.au',+ 'ca': '.ca', 'de': '.de', 'fr': '.fr', 'it': '.it', 'es': '.es',+ 'jp': '.co.jp', 'in': '.in', 'br': '.com.br',+ };+ return tlds[region] ?? '.com';+}++Future<void> _openOnAudible(BuildContext context, String asin, String region) async {+ final tld = _audibleTldForRegion(region);+ final uri = Uri.parse('https://www.audible$tld/pd/$asin');+ try {+ await launchUrl(uri, mode: LaunchMode.externalApplication);+ } catch (e) {+ if (context.mounted) showOverlayToast(context, 'Could not open Audible', icon: Icons.error_outline_rounded);+ }+}++Future<void> _addToCalendar(BuildContext context, String title, String seriesName, String dateStr) async {+ final date = DateTime.tryParse(dateStr);+ if (date == null) return;++ final eventTitle = '$title - $seriesName';+ final description = 'New audiobook release in the $seriesName series';++ if (Platform.isAndroid) {+ final begin = DateTime(date.year, date.month, date.day).millisecondsSinceEpoch;+ final end = DateTime(date.year, date.month, date.day, 23, 59).millisecondsSinceEpoch;+ final uri = Uri.parse(+ 'content://com.android.calendar/events'+ '?title=${Uri.encodeComponent(eventTitle)}'+ '&description=${Uri.encodeComponent(description)}'+ '&beginTime=$begin'+ '&endTime=$end'+ '&allDay=1',+ );+ try {+ await launchUrl(uri);+ return;+ } catch (_) {}+ }++ final dateFormatted = '${date.year}${date.month.toString().padLeft(2, '0')}${date.day.toString().padLeft(2, '0')}';+ final uri = Uri.parse(+ 'https://calendar.google.com/calendar/render?action=TEMPLATE'+ '&text=${Uri.encodeComponent(eventTitle)}'+ '&dates=$dateFormatted/$dateFormatted'+ '&details=${Uri.encodeComponent(description)}',+ );+ try {+ await launchUrl(uri, mode: LaunchMode.externalApplication);+ } catch (e) {+ if (context.mounted) showOverlayToast(context, 'Could not open calendar', icon: Icons.error_outline_rounded);+ }+}diff --git a/lib/widgets/library_sort_filter_sheet.dart b/lib/widgets/library_sort_filter_sheet.dartindex d348fb6b..8a417e5a 100644--- a/lib/widgets/library_sort_filter_sheet.dart+++ b/lib/widgets/library_sort_filter_sheet.dart@@ -25,6 +25,7 @@ class SortFilterSheet extends StatefulWidget {final ValueChanged<bool> onCollapseSeriesChanged;final bool isPodcastLibrary;final LibraryTab libraryTab;+ final VoidCallback? onUpcomingReleases;const SortFilterSheet({super.key,@@ -37,6 +38,7 @@ class SortFilterSheet extends StatefulWidget {this.collapseSeries = false, required this.onCollapseSeriesChanged,required this.isPodcastLibrary,this.libraryTab = LibraryTab.library,+ this.onUpcomingReleases,});@override@@ -114,7 +116,7 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv}double _calcHeight() {- if (widget.libraryTab == LibraryTab.series) return 230;+ if (widget.libraryTab == LibraryTab.series) return widget.onUpcomingReleases != null ? 330 : 230;if (widget.libraryTab == LibraryTab.authors) return 180;return _genreExpanded ? 420 : (widget.isPodcastLibrary ? 200 : 400);}@@ -179,6 +181,36 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv]),),),+ if (widget.libraryTab == LibraryTab.series && widget.onUpcomingReleases != null) ...[+ const Divider(height: 24),+ GestureDetector(+ onTap: widget.onUpcomingReleases,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),+ decoration: BoxDecoration(+ color: cs.primary.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),+ ),+ child: Row(children: [+ Icon(Icons.calendar_month_rounded, size: 20, color: cs.primary),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('Upcoming Releases', style: TextStyle(+ fontSize: 14, fontWeight: FontWeight.w600, color: cs.primary)),+ Text('Scan Audible for new releases in your series', style: TextStyle(+ fontSize: 11, color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.primary),+ ]),+ ),+ ),+ ],],);}