From 2d7cdbb000771dc9268e7616c2bb3696ede257fa Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:28:18 +0700 Subject: [PATCH] feat(home): Recently Played and extension playlists for Mornye Top Picks follow the day's mixes with random playlists from an extension's home feed, read once a day even with the feed off. Recently Played replaces the Continue listening card. A phone's content URI now counts as absent on a computer instead of failing the whole shelf. --- lib/l10n/arb/app_en.arb | 4 + lib/providers/explore_provider.dart | 20 +- lib/providers/home_top_picks_provider.dart | 110 +++++++ lib/screens/home_tab.dart | 25 +- lib/screens/home_tab_intro.dart | 333 ++++++++++++++++++--- lib/services/listening_statistics.dart | 12 +- lib/utils/file_access.dart | 3 + lib/widgets/mornye_mix_banner.dart | 105 +++++++ test/file_access_check_test.dart | 7 + test/home_top_picks_test.dart | 45 +++ test/listening_statistics_test.dart | 11 + 11 files changed, 618 insertions(+), 57 deletions(-) create mode 100644 lib/providers/home_top_picks_provider.dart create mode 100644 test/home_top_picks_test.dart diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index b08b11f9a..a1409d11a 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -8377,6 +8377,10 @@ "@homeContinueListening": { "description": "Home section header for the track currently loaded in the player" }, + "homeRecentlyPlayed": "Recently Played", + "@homeRecentlyPlayed": { + "description": "Mornye Home: heading of the shelf of what was played lately" + }, "homeRecentlyAdded": "Recently added", "@homeRecentlyAdded": { "description": "Home section header for the newest downloaded and scanned tracks" diff --git a/lib/providers/explore_provider.dart b/lib/providers/explore_provider.dart index 9bebc5085..9660b92de 100644 --- a/lib/providers/explore_provider.dart +++ b/lib/providers/explore_provider.dart @@ -570,14 +570,32 @@ class ExploreNotifier extends Notifier { void clear() { _homeFeedRequestId++; _cacheRestoreGeneration++; + // Top Picks read the same bridge while the feed is off: only a fetch of + // this notifier's own is cancelled. + if (_activeHomeFeedRequestId != null) { + PlatformBridge.cancelExtensionHomeFeedRequests(); + } _activeHomeFeedRequestId = null; - PlatformBridge.cancelExtensionHomeFeedRequests(); state = const ExploreState(); } Future refresh() => fetchHomeFeed(forceRefresh: true); } +/// One read of [extensionId]'s home feed, null when it fails. Top Picks use it +/// apart from [exploreProvider], so the feed being off leaves them working. +Future?> readExtensionHomeFeed(String extensionId) async { + final result = await PlatformBridge.getExtensionHomeFeed(extensionId); + if (result == null || result['success'] != true) return null; + final normalized = await compute( + _normalizeExploreSectionsPayload, + result['sections'], + ); + return _buildExploreSectionsFromNormalizedPayload( + _withDefaultExploreProviderId(normalized, extensionId), + ); +} + final exploreProvider = NotifierProvider(() { return ExploreNotifier(); }); diff --git a/lib/providers/home_top_picks_provider.dart b/lib/providers/home_top_picks_provider.dart new file mode 100644 index 000000000..b6d590f10 --- /dev/null +++ b/lib/providers/home_top_picks_provider.dart @@ -0,0 +1,110 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:mornye/models/settings.dart'; +import 'package:mornye/providers/explore_provider.dart'; +import 'package:mornye/providers/extension_provider.dart'; +import 'package:mornye/providers/settings_provider.dart'; +import 'package:mornye/services/listening_statistics.dart' show listeningDay; +import 'package:mornye/utils/logger.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _log = AppLogger('HomeTopPicks'); + +const _cacheKey = 'home_top_picks_v1'; + +/// The most extension playlists Top Picks show after the mixes. +const homeTopPickPlaylists = 9; + +/// Up to [count] playlists of [sections] with a cover, each once, in an order +/// that holds for the [day] and changes with the next. +@visibleForTesting +List pickTopPickPlaylists( + List sections, + String day, { + int count = homeTopPickPlaylists, +}) { + final playlists = {}; + for (final section in sections) { + for (final item in section.items) { + if (item.type != 'playlist' || item.id.isEmpty) continue; + if (item.coverUrl?.trim().isNotEmpty != true) continue; + playlists.putIfAbsent(item.id, () => item); + } + } + final ordered = playlists.values.toList() + ..sort((a, b) => a.id.compareTo(b.id)) + ..shuffle(Random(int.tryParse(day.replaceAll('-', '')) ?? 0)); + return ordered.take(count).toList(growable: false); +} + +/// The extension Top Picks read: the one the Home feed uses, or with the feed +/// switched off the first that offers a feed. +final homeTopPicksExtensionProvider = Provider((ref) { + final preferred = ref.watch( + settingsProvider.select((settings) => settings.homeFeedProvider), + ); + final available = ref + .watch(extensionProvider.select((state) => state.extensions)) + .where((extension) => extension.enabled && extension.hasHomeFeed); + if (preferred != null && + preferred.isNotEmpty && + preferred != AppSettings.homeFeedProviderOff) { + return available.where((e) => e.id == preferred).firstOrNull?.id; + } + return available.firstOrNull?.id; +}); + +/// A day's random extension playlists, kept for that day. A failed read falls +/// back on the last day's picks and is tried again on the next launch. +final homeTopPicksProvider = FutureProvider>((ref) async { + final extensionId = ref.watch(homeTopPicksExtensionProvider); + if (extensionId == null) return const []; + final prefs = await SharedPreferences.getInstance(); + final day = listeningDay(DateTime.now()); + final cached = _decode(prefs.getString(_cacheKey)); + final usable = cached?.extensionId == extensionId ? cached : null; + if (usable != null && usable.day == day) return usable.items; + try { + final sections = await readExtensionHomeFeed(extensionId); + if (sections == null) return usable?.items ?? const []; + final items = pickTopPickPlaylists(sections, day); + await prefs.setString( + _cacheKey, + jsonEncode({ + 'day': day, + 'extensionId': extensionId, + 'items': [for (final item in items) item.toJson()], + }), + ); + return items; + } on Object catch (error, stack) { + _log.w('Could not read Top Picks playlists: $error\n$stack'); + return usable?.items ?? const []; + } +}); + +({String day, String extensionId, List items})? _decode( + String? value, +) { + if (value == null) return null; + try { + final json = jsonDecode(value); + if (json is! Map) return null; + final day = json['day'], extensionId = json['extensionId']; + final items = json['items']; + if (day is! String || extensionId is! String || items is! List) return null; + return ( + day: day, + extensionId: extensionId, + items: [ + for (final item in items) + if (item is Map) ExploreItem.fromJson(item), + ], + ); + } on FormatException { + return null; + } +} diff --git a/lib/screens/home_tab.dart b/lib/screens/home_tab.dart index 54c400352..e46070215 100644 --- a/lib/screens/home_tab.dart +++ b/lib/screens/home_tab.dart @@ -45,6 +45,7 @@ import 'package:mornye/providers/settings_provider.dart'; import 'package:mornye/providers/extension_provider.dart'; import 'package:mornye/providers/recent_access_provider.dart'; import 'package:mornye/providers/explore_provider.dart'; +import 'package:mornye/providers/home_top_picks_provider.dart'; import 'package:mornye/providers/user_profile_provider.dart'; import 'package:mornye/widgets/desktop/desktop_scroll_arrows.dart'; import 'package:mornye/widgets/explore_featured_section.dart'; @@ -1355,11 +1356,25 @@ class _HomeTabState extends ConsumerState userProfileProvider.select((p) => p.value?.name ?? ''), ); return SliverMainAxisGroup( - slivers: _buildExploreSections( - exploreSections, - showGreeting ? homeGreeting(context.l10n, name: profileName) : null, - colorScheme, - ), + slivers: [ + // Mornye opens with Top Picks whether or not the feed follows. + if (context.isMornye && _HomeTopPicksSection.hasPicks(ref)) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.only(top: 8, bottom: 12), + child: _HomeTopPicksSection( + inset: 16 + homeContentInset(context), + ), + ), + ), + ..._buildExploreSections( + exploreSections, + showGreeting + ? homeGreeting(context.l10n, name: profileName) + : null, + colorScheme, + ), + ], ); }, ); diff --git a/lib/screens/home_tab_intro.dart b/lib/screens/home_tab_intro.dart index e6b98bdd1..e516a1fef 100644 --- a/lib/screens/home_tab_intro.dart +++ b/lib/screens/home_tab_intro.dart @@ -102,6 +102,45 @@ const _homeRepeatPage = 40; final homeOnRepeatProvider = FutureProvider.autoDispose>(( ref, ) async { + final memo = ref.read(_homeShelfMemoProvider); + final tracks = await _homeReplayableTracks(ref, limit: _homeShelfLimit); + final last = memo.onRepeat; + if (last != null && _sameRepeatTracks(last, tracks)) return last; + return memo.onRepeat = tracks; +}); + +/// Mornye's Recently Played: one song of each album played lately, latest +/// day first, as Music lists what was played by its album. +final homeRecentlyPlayedProvider = + FutureProvider.autoDispose>((ref) async { + final memo = ref.read(_homeShelfMemoProvider); + final played = await _homeReplayableTracks( + ref, + limit: _homeShelfLimit * 3, + latestFirst: true, + ); + final albums = {}; + final tracks = [ + for (final entry in played) + if (albums.add( + entry.track.album.isEmpty + ? entry.track.key + : '${entry.track.artist}/${entry.track.album}', + )) + entry, + ].take(_homeShelfLimit).toList(); + final last = memo.recentlyPlayed; + if (last != null && _sameRepeatTracks(last, tracks)) return last; + return memo.recentlyPlayed = tracks; + }); + +/// Up to [limit] played songs of the last four weeks that can be played +/// again, matched to the Library. Reloads with what changes them. +Future> _homeReplayableTracks( + Ref ref, { + required int limit, + bool latestFirst = false, +}) async { // A track that ends may have just earned a play. One that starts after // none, such as a restored session's, follows no play. ref.listen(currentMediaItemProvider.select((s) => s.value?.id), ( @@ -143,15 +182,13 @@ final homeOnRepeatProvider = FutureProvider.autoDispose>(( end, limit: _homeRepeatPage, offset: offset, + latestFirst: latestFirst, ); // Matched in rounds of the songs still missing, so no more songs are // looked up than one at a time would. var next = 0; - while (tracks.length < _homeShelfLimit && next < totals.length) { - final round = totals - .skip(next) - .take(_homeShelfLimit - tracks.length) - .toList(); + while (tracks.length < limit && next < totals.length) { + final round = totals.skip(next).take(limit - tracks.length).toList(); next += round.length; tracks.addAll( await _homeRepeatTracks( @@ -162,14 +199,10 @@ final homeOnRepeatProvider = FutureProvider.autoDispose>(( ), ); } - if (tracks.length == _homeShelfLimit || totals.length < _homeRepeatPage) { - break; - } + if (tracks.length == limit || totals.length < _homeRepeatPage) break; } - final last = memo.onRepeat; - if (last != null && _sameRepeatTracks(last, tracks)) return last; - return memo.onRepeat = tracks; -}); + return tracks; +} /// A played key's Library entry: a download or a scanned file, or none. /// [hidden] is a scanned file while Local Library is off. @@ -286,6 +319,7 @@ class _HomeShelfMemo { (int, int, bool)? repeatLibrary; Map repeatMatches = {}; List? onRepeat; + List? recentlyPlayed; } final _homeShelfMemoProvider = Provider<_HomeShelfMemo>( @@ -336,19 +370,32 @@ class _HomeSections extends ConsumerWidget { final showContinue = hasMediaItem || hasResume; - final topPicks = context.isMornye; + final mornye = context.isMornye; + final recentlyPlayed = mornye + ? ref.watch(homeRecentlyPlayedProvider.select((s) => s.value)) ?? + const [] + : const []; + final hasTopPicks = mornye && _HomeTopPicksSection.hasPicks(ref); final sections = [ - if (topPicks && mixes.isNotEmpty) - _HomeSection( - title: l10n.homeTopPicks, - inset: inset, - shelf: true, - child: _HomeTopPicksShelf(mixes: mixes, inset: inset + 8), - ), + if (hasTopPicks) _HomeTopPicksSection(inset: inset), if (_homeDesktop(context)) _HomeDesktopTop(inset: inset, showContinue: showContinue) else ...[ - if (showContinue) + if (recentlyPlayed.isNotEmpty) + _HomeSection( + title: l10n.homeRecentlyPlayed, + inset: inset, + shelf: true, + onShowAll: () => pushPage( + context, + (_) => const ListeningStatisticsScreen(), + ), + child: _HomeRecentlyPlayedShelf( + tracks: recentlyPlayed, + inset: inset + 8, + ), + ) + else if (showContinue) _HomeSection( title: l10n.homeContinueListening, inset: inset, @@ -362,7 +409,7 @@ class _HomeSections extends ConsumerWidget { ], // Built after startup settles when nothing is cached: the sections' // size animation opens its space rather than letting it jump in. - if (!topPicks && mixes.isNotEmpty) + if (!mornye && mixes.isNotEmpty) _HomeSection( title: l10n.homeMixesForYou, inset: inset, @@ -490,6 +537,7 @@ class _HomeSection extends StatelessWidget { required this.inset, required this.child, this.shelf = false, + this.onShowAll, }); final String title; @@ -499,9 +547,19 @@ class _HomeSection extends StatelessWidget { /// Shelves scroll edge to edge and pad their own items. final bool shelf; + /// Makes the title a link, marked with a chevron, as in Music. + final VoidCallback? onShowAll; + @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; + final heading = Text( + title, + style: Theme.of(context).textTheme.titleMedium?.copyWith( + color: colorScheme.onSurface, + fontWeight: FontWeight.w600, + ), + ); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -509,13 +567,30 @@ class _HomeSection extends StatelessWidget { padding: EdgeInsets.fromLTRB(inset + 8, 0, inset + 8, 12), child: Semantics( header: true, - child: Text( - title, - style: Theme.of(context).textTheme.titleMedium?.copyWith( - color: colorScheme.onSurface, - fontWeight: FontWeight.w600, - ), - ), + child: onShowAll == null + ? heading + : Align( + alignment: AlignmentDirectional.centerStart, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onShowAll, + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: heading), + const SizedBox(width: 4), + Icon( + CupertinoIcons.chevron_forward, + size: 15, + color: colorScheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ), ), ), if (shelf) @@ -816,6 +891,7 @@ class _HomeShelf extends StatelessWidget { required this.itemCount, required this.itemBuilder, this.coverSize, + this.gap = 12, }); final double inset; @@ -824,6 +900,7 @@ class _HomeShelf extends StatelessWidget { /// Null for the platform's shelf cover size. final double? coverSize; + final double gap; @override Widget build(BuildContext context) { @@ -837,7 +914,7 @@ class _HomeShelf extends StatelessWidget { scrollDirection: Axis.horizontal, padding: EdgeInsets.symmetric(horizontal: inset), itemCount: itemCount, - separatorBuilder: (_, _) => const SizedBox(width: 12), + separatorBuilder: (_, _) => SizedBox(width: gap), itemBuilder: itemBuilder, ), ), @@ -853,6 +930,7 @@ class _HomeShelfTile extends StatelessWidget { required this.semanticLabel, required this.onTap, this.size, + this.radius = 20, }); final Widget cover; @@ -863,6 +941,7 @@ class _HomeShelfTile extends StatelessWidget { /// Null for the platform's shelf cover size. final double? size; + final double radius; @override Widget build(BuildContext context) { @@ -875,14 +954,14 @@ class _HomeShelfTile extends StatelessWidget { excludeSemantics: true, child: InkWell( onTap: onTap, - borderRadius: BorderRadius.circular(20), + borderRadius: BorderRadius.circular(radius), child: SizedBox( width: size, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( - borderRadius: BorderRadius.circular(20), + borderRadius: BorderRadius.circular(radius), child: SizedBox.square(dimension: size, child: cover), ), const SizedBox(height: 8), @@ -1099,24 +1178,85 @@ class _HomeOnRepeatShelf extends ConsumerWidget { cacheWidth: cacheWidth, iconSize: 32, ), - onTap: () => ref.read(musicPlayerControllerProvider).playAll([ - for (final (:track, :item) in tracks) - (item == null ? null : _homePlayableFromLibrary(item)) ?? - PlayableMedia( - id: track.key, - source: track.key, - title: track.title, - artist: track.artist, - album: track.album, - artUri: track.artwork, - ), - ], initialIndex: index), + onTap: () => _homePlayRepeatTracks(ref, tracks, index), ); }, ); } } +/// What was played lately, as Music shows it: large covers named by album. +/// Choosing one plays from that song. +class _HomeRecentlyPlayedShelf extends ConsumerWidget { + const _HomeRecentlyPlayedShelf({required this.tracks, required this.inset}); + + static const _gap = 16.0; + + final List tracks; + final double inset; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final colorScheme = Theme.of(context).colorScheme; + return LayoutBuilder( + builder: (context, constraints) { + final content = constraints.maxWidth - 2 * inset; + final coverSize = isDesktopPlatform + ? ((content + _gap) / 4.17 - _gap).clamp(160.0, 280.0) + : 160.0; + final cacheWidth = (coverSize * MediaQuery.devicePixelRatioOf(context)) + .round(); + return _HomeShelf( + inset: inset, + coverSize: coverSize, + gap: _gap, + itemCount: tracks.length, + itemBuilder: (context, index) { + final (:track, :item) = tracks[index]; + final title = track.album.isEmpty ? track.title : track.album; + return _HomeShelfTile( + size: coverSize, + radius: 10, + title: title, + subtitle: track.artist, + semanticLabel: context.l10n.a11yOpenTrackByArtist( + title, + track.artist, + ), + cover: item != null + ? _homeLibraryCover(item, colorScheme, coverSize, cacheWidth) + : PlayerArtwork( + artUri: track.artwork, + colorScheme: colorScheme, + cacheWidth: cacheWidth, + iconSize: 32, + ), + onTap: () => _homePlayRepeatTracks(ref, tracks, index), + ); + }, + ); + }, + ); + } +} + +void _homePlayRepeatTracks( + WidgetRef ref, + List tracks, + int index, +) => ref.read(musicPlayerControllerProvider).playAll([ + for (final (:track, :item) in tracks) + (item == null ? null : _homePlayableFromLibrary(item)) ?? + PlayableMedia( + id: track.key, + source: track.key, + title: track.title, + artist: track.artist, + album: track.album, + artUri: track.artwork, + ), +], initialIndex: index); + /// The day's mixes of the Library's own songs, larger than the other /// shelves' covers so the four-album collages stay legible. class _HomeMixesShelf extends StatelessWidget { @@ -1153,19 +1293,78 @@ class _HomeMixesShelf extends StatelessWidget { /// Mornye's first shelf: the day's mixes as tall banners, a little over three /// to the pane on desktop and one with its neighbor peeking on phones. class _HomeTopPicksShelf extends StatelessWidget { - const _HomeTopPicksShelf({required this.mixes, required this.inset}); + const _HomeTopPicksShelf({ + required this.mixes, + required this.playlists, + required this.inset, + }); static const _gap = 16.0; final List mixes; + final List playlists; final double inset; + Widget _playlist( + BuildContext context, + ExploreItem item, + int seed, + double width, + ) { + final subtitle = item.artists.isNotEmpty + ? item.artists + : item.description ?? ''; + final coverUrl = item.coverUrl ?? ''; + final pixelRatio = MediaQuery.devicePixelRatioOf(context); + return Semantics( + button: true, + label: subtitle.isEmpty ? item.name : '${item.name}, $subtitle', + excludeSemantics: true, + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Stack( + children: [ + MornyePlaylistBanner( + seed: seed, + title: item.name, + subtitle: subtitle, + coverUrl: coverUrl, + width: width, + cover: CachedCoverImage( + imageUrl: coverUrl, + fit: BoxFit.cover, + memCacheWidth: (width * pixelRatio).round(), + ), + ), + Positioned.fill( + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () => pushPage( + context, + (_) => ExtensionPlaylistScreen( + extensionId: item.providerId ?? '', + playlistId: item.id, + playlistName: item.name, + coverUrl: item.coverUrl, + ), + ), + ), + ), + ), + ], + ), + ), + ); + } + @override Widget build(BuildContext context) { final l10n = context.l10n; - final seeds = mornyeBannerSeeds( - mixes.map((view) => '${view.mix.kind.name}/${view.mix.key}'), - ); + final seeds = mornyeBannerSeeds([ + for (final view in mixes) '${view.mix.kind.name}/${view.mix.key}', + for (final item in playlists) 'playlist/${item.id}', + ]); return LayoutBuilder( builder: (context, constraints) { final content = constraints.maxWidth - 2 * inset; @@ -1179,9 +1378,17 @@ class _HomeTopPicksShelf extends StatelessWidget { controller: controller, scrollDirection: Axis.horizontal, padding: EdgeInsets.symmetric(horizontal: inset), - itemCount: mixes.length, + itemCount: mixes.length + playlists.length, separatorBuilder: (_, _) => const SizedBox(width: _gap), itemBuilder: (context, index) { + if (index >= mixes.length) { + return _playlist( + context, + playlists[index - mixes.length], + seeds[index], + width, + ); + } final view = mixes[index]; final title = libraryMixTitle(l10n, view.mix); final subtitle = libraryMixSubtitle(l10n, view.mix); @@ -1224,6 +1431,34 @@ class _HomeTopPicksShelf extends StatelessWidget { } } +/// Mornye's first section: the day's mixes, then random extension playlists. +class _HomeTopPicksSection extends ConsumerWidget { + const _HomeTopPicksSection({required this.inset}); + + final double inset; + + static bool hasPicks(WidgetRef ref) => + ref.watch( + libraryMixesProvider.select((s) => s.value?.isNotEmpty ?? false), + ) || + ref.watch( + homeTopPicksProvider.select((s) => s.value?.isNotEmpty ?? false), + ); + + @override + Widget build(BuildContext context, WidgetRef ref) => _HomeSection( + title: context.l10n.homeTopPicks, + inset: inset, + shelf: true, + child: _HomeTopPicksShelf( + mixes: ref.watch(libraryMixesProvider.select((s) => s.value)) ?? const [], + playlists: + ref.watch(homeTopPicksProvider.select((s) => s.value)) ?? const [], + inset: inset + 8, + ), + ); +} + enum _HomeShortcutsLayout { /// Two columns of tall tiles, on phones and tablets. grid, diff --git a/lib/services/listening_statistics.dart b/lib/services/listening_statistics.dart index 4392c548e..0b33af749 100644 --- a/lib/services/listening_statistics.dart +++ b/lib/services/listening_statistics.dart @@ -351,12 +351,14 @@ class ListeningStatisticsStore { DateTime end, { required int limit, int offset = 0, + bool latestFirst = false, }) async => readReplayableListeningTracks( await _open(), start, end, limit: limit, offset: offset, + latestFirst: latestFirst, ); /// Runs a read-only aggregate against the statistics database. @@ -421,6 +423,7 @@ Future writeListeningDeltas( String _listeningTracksSql({ String where = '', String having = '', + String order = 'totals.milliseconds DESC', String tail = '', }) => ''' @@ -437,7 +440,7 @@ String _listeningTracksSql({ AND details.day = totals.last_day LEFT JOIN listening AS covered ON covered.track_key = totals.track_key AND covered.day = totals.cover_day - ORDER BY totals.milliseconds DESC$tail + ORDER BY $order$tail '''; /// Aggregate in SQLite so an annual recap transfers one row per song, artist @@ -490,13 +493,15 @@ Future readListeningSummary( /// The tracks of [readListeningSummary] in its order, [limit] from /// [offset], that can be played again from their key: played at least once /// and not recorded under a stream URL. Equal listening times keep the -/// summary's order, by key. +/// summary's order, by key. With [latestFirst] the songs of the latest day +/// lead: days are as fine as the statistics record. Future> readReplayableListeningTracks( DatabaseExecutor db, DateTime start, DateTime end, { required int limit, int offset = 0, + bool latestFirst = false, }) async { final rows = await db.rawQuery( _listeningTracksSql( @@ -504,6 +509,9 @@ Future> readReplayableListeningTracks( " AND track_key NOT GLOB 'http://*'" " AND track_key NOT GLOB 'https://*'", having: ' HAVING SUM(plays) > 0', + order: latestFirst + ? 'totals.last_day DESC, totals.milliseconds DESC' + : 'totals.milliseconds DESC', tail: ', totals.track_key LIMIT ? OFFSET ?', ), [listeningDay(start), listeningDay(end), limit, offset], diff --git a/lib/utils/file_access.dart b/lib/utils/file_access.dart index 4b97b18b3..7dcb53c20 100644 --- a/lib/utils/file_access.dart +++ b/lib/utils/file_access.dart @@ -301,6 +301,9 @@ Future fileExists(String? path) async { if (path.startsWith('network://')) return true; final realPath = isCueVirtualPath(path) ? stripCueTrackSuffix(path) : path; if (isContentUri(realPath)) { + // A phone's content URI can arrive with synced statistics; a computer has + // no way to open one. + if (isDesktopPlatform) return false; return PlatformBridge.safExists(realPath); } return File(realPath).exists(); diff --git a/lib/widgets/mornye_mix_banner.dart b/lib/widgets/mornye_mix_banner.dart index 9d9f5c0f1..df3a609a3 100644 --- a/lib/widgets/mornye_mix_banner.dart +++ b/lib/widgets/mornye_mix_banner.dart @@ -1,6 +1,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; +import 'package:mornye/theme/cover_palette.dart'; const mornyeLockupAsset = 'assets/brand/logo/png/mornye-lockup-horizontal-white@1x.png'; @@ -199,6 +200,110 @@ class MornyeMixBanner extends StatelessWidget { } } +/// A Top Pick from outside the Library: the playlist's own cover over a strip +/// tinted from it, as Music's editorial cards are. The cover carries its own +/// mark, so no lockup is set over it. +class MornyePlaylistBanner extends StatefulWidget { + const MornyePlaylistBanner({ + super.key, + required this.seed, + required this.title, + required this.subtitle, + required this.coverUrl, + required this.cover, + required this.width, + }); + + /// The strip's color until the cover's own is known. + final int seed; + final String title; + final String subtitle; + final String coverUrl; + final Widget cover; + final double width; + + @override + State createState() => _MornyePlaylistBannerState(); +} + +class _MornyePlaylistBannerState extends State { + Color? _tint; + + @override + void initState() { + super.initState(); + _readTint(); + } + + @override + void didUpdateWidget(MornyePlaylistBanner oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.coverUrl != widget.coverUrl) _readTint(); + } + + Future _readTint() async { + final url = widget.coverUrl; + final color = await CoverPalette.resolveSourceColor(url); + if (!mounted || url != widget.coverUrl || color == null) return; + // Dark enough for the white text, however light the cover. + final hsl = HSLColor.fromColor(color); + setState(() { + _tint = hsl.withLightness(hsl.lightness.clamp(0.16, 0.32)).toColor(); + }); + } + + @override + Widget build(BuildContext context) { + final textTheme = Theme.of(context).textTheme; + final width = widget.width; + return MediaQuery.withClampedTextScaling( + maxScaleFactor: 1.2, + child: SizedBox( + width: width, + height: width / MornyeMixBanner.aspectRatio, + child: Column( + children: [ + SizedBox.square(dimension: width, child: widget.cover), + Expanded( + child: AnimatedContainer( + duration: const Duration(milliseconds: 240), + width: width, + color: _tint ?? _palettes[widget.seed % _palettes.length].depth, + padding: const EdgeInsets.symmetric(horizontal: 14), + alignment: AlignmentDirectional.centerStart, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + widget.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: textTheme.titleSmall?.copyWith( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + if (widget.subtitle.isNotEmpty) + Text( + widget.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: textTheme.bodySmall?.copyWith( + color: Colors.white.withValues(alpha: 0.78), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + class _BannerPainter extends CustomPainter { const _BannerPainter(this.seed); diff --git a/test/file_access_check_test.dart b/test/file_access_check_test.dart index ab83b1e74..d899c7250 100644 --- a/test/file_access_check_test.dart +++ b/test/file_access_check_test.dart @@ -1,9 +1,16 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mornye/services/file_access_check.dart'; +import 'package:mornye/utils/desktop_platform.dart'; import 'package:mornye/utils/file_access.dart'; void main() { + test('a computer treats a phone content URI as absent', () async { + debugDesktopPlatformOverride = true; + addTearDown(() => debugDesktopPlatformOverride = null); + expect(await fileExists('content://provider/music/track.flac'), isFalse); + }); + test('found files retain their size and modification time', () async { final stat = FileAccessStat(size: 123, modified: DateTime(2026)); final result = await checkFileAccess( diff --git a/test/home_top_picks_test.dart b/test/home_top_picks_test.dart new file mode 100644 index 000000000..9cc87f244 --- /dev/null +++ b/test/home_top_picks_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/providers/explore_provider.dart'; +import 'package:mornye/providers/home_top_picks_provider.dart'; + +ExploreItem _item(String id, {String type = 'playlist', String? cover = 'c'}) => + ExploreItem( + id: id, + uri: id, + type: type, + name: id, + artists: '', + coverUrl: cover, + ); + +void main() { + final sections = [ + ExploreSection( + uri: 'a', + title: 'A', + items: [ + for (var i = 0; i < 12; i++) _item('p$i'), + _item('album', type: 'album'), + _item('coverless', cover: null), + ], + ), + ExploreSection(uri: 'b', title: 'B', items: [_item('p0')]), + ]; + + test('picks covered playlists once and leaves the rest out', () { + final picks = pickTopPickPlaylists(sections, '2026-11-04', count: 20); + expect(picks.map((item) => item.id).toSet(), { + for (var i = 0; i < 12; i++) 'p$i', + }); + expect(picks, hasLength(12)); + }); + + test('holds for the day, changes with the next and caps the count', () { + List ids(String day) => [ + for (final item in pickTopPickPlaylists(sections, day, count: 5)) item.id, + ]; + expect(ids('2026-11-04'), hasLength(5)); + expect(ids('2026-11-04'), ids('2026-11-04')); + expect(ids('2026-11-05'), isNot(ids('2026-11-04'))); + }); +} diff --git a/test/listening_statistics_test.dart b/test/listening_statistics_test.dart index 26846348b..d905f025a 100644 --- a/test/listening_statistics_test.dart +++ b/test/listening_statistics_test.dart @@ -316,6 +316,17 @@ void main() { if (page.length < 7) break; } expect(describe(pages), expected); + + final latest = await readReplayableListeningTracks( + db, + start, + end, + limit: 1000, + latestFirst: true, + ); + expect(latest.map((total) => total.track.key).toSet(), { + for (final total in pages) total.track.key, + }); }); test(