Skip to content

Commit

Permalink
feat(playlist): improve retrieval logic with better error handling an…
Browse files Browse the repository at this point in the history
…d caching (fixes #510)
  • Loading branch information
gokadzev committed Feb 25, 2025
1 parent 32c6ee0 commit 917dd57
Showing 1 changed file with 42 additions and 27 deletions.
69 changes: 42 additions & 27 deletions lib/API/musify.dart
Original file line number Diff line number Diff line change
Expand Up @@ -591,40 +591,55 @@ Future<Map?> getPlaylistInfoForWidget(
dynamic id, {
bool isArtist = false,
}) async {
if (!isArtist) {
Map? playlist = playlists.firstWhere(
(list) => list['ytid'] == id,
orElse: () => null,
);
if (isArtist) {
return {'title': id, 'list': await fetchSongsList(id)};
}

if (playlist == null) {
final usPlaylists = await getUserPlaylists();
playlist = usPlaylists.firstWhere(
(list) => list['ytid'] == id,
orElse: () => null,
);
}
Map? playlist;

playlist ??= onlinePlaylists.firstWhere(
(list) => list['ytid'] == id,
orElse: () => null,
);
// Check in local playlists.
playlist = playlists.firstWhere((p) => p['ytid'] == id, orElse: () => null);

if (playlist != null && playlist['list'].isEmpty) {
playlist['list'] = await getSongsFromPlaylist(playlist['ytid']);
if (!playlists.contains(playlist)) {
playlists.add(playlist);
}
}
// Check in user playlists if not found.
if (playlist == null) {
final userPl = await getUserPlaylists();
playlist = userPl.firstWhere((p) => p['ytid'] == id, orElse: () => null);
}

return playlist;
} else {
final playlist = <String, dynamic>{'title': id};
// Check in cached online playlists if still not found.
playlist ??= onlinePlaylists.firstWhere(
(p) => p['ytid'] == id,
orElse: () => null,
);

playlist['list'] = await fetchSongsList(id);
// If still not found, attempt to fetch playlist info.
if (playlist == null) {
try {
final ytPlaylist = await _yt.playlists.get(id);
playlist = {
'ytid': ytPlaylist.id.toString(),
'title': ytPlaylist.title,
'image': null,
'source': 'user-youtube',
'list': [],
};
onlinePlaylists.add(playlist);
} catch (e, stackTrace) {
logger.log('Failed to fetch playlist info for id $id', e, stackTrace);
return null;
}
}

return playlist;
// If the playlist exists but its song list is empty, fetch and cache the songs.
if (playlist['list'] == null ||
(playlist['list'] is List && (playlist['list'] as List).isEmpty)) {
playlist['list'] = await getSongsFromPlaylist(playlist['ytid']);
if (!playlists.contains(playlist)) {
playlists.add(playlist);
}
}

return playlist;
}

final clients = {
Expand Down

0 comments on commit 917dd57

Please sign in to comment.