Compare commits

...

6 Commits

Author SHA1 Message Date
Gustavo Moreno
aecf36d2f9
Merge 9163f1abe0 into 0ec9f3535b 2025-03-17 13:24:49 +05:30
Kingkor Roy Tirtho
0ec9f3535b chore: bump to 4.0.2 and generate changelog 2025-03-16 23:52:08 +06:00
Kingkor Roy Tirtho
df72ba6960 chore: convert all spotify calls to invoke signature to capture invalid access token exception 2025-03-16 21:22:29 +06:00
Kingkor Roy Tirtho
d9057dae57 fix: invalid access token exception #2525 2025-03-16 10:32:41 +06:00
Gustavo Moreno
9163f1abe0 bug 2344: Bottom Overflow in Browse & Local Library on Desktop
- Wrapped `Wrap` in `Flexible` to prevent overflow issues inside `Stack`
- Now the folder path text adapts better to different screen sizes
- Improved overall UI consistency and responsiveness

Tested visually only on **Linux Desktop**

Fixes #2344
https://github.com/KRTirtho/spotube/issues/2344
2025-02-26 16:14:55 +01:00
Gustavo Moreno
227909787d bug #2344: Bottom Overflow in Browse
- Added a width adjustment (`w`) for desktop screens
- Limited the number of lines for the genre name to 1 (`maxLines: 1`) to prevent overflow

This commit only fixes the issue in Browse. The overflow in Local Library is not addressed here.

Partially fixes #2344
2025-02-26 15:03:33 +01:00
38 changed files with 401 additions and 280 deletions

View File

@ -1,6 +1,10 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [4.0.2](https://github.com/krtirtho/spotube/compare/v4.0.1...v4.0.2) (2025-03-16)
### Bug Fixes
- invalid access token exception #2525
## [4.0.1](https://github.com/krtirtho/spotube/compare/v4.0.0...v4.0.1) (2025-03-15)

View File

@ -30,7 +30,6 @@ import 'package:spotube/provider/download_manager_provider.dart';
import 'package:spotube/provider/local_tracks/local_tracks_provider.dart';
import 'package:spotube/provider/audio_player/audio_player.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
@ -122,8 +121,9 @@ class TrackOptions extends HookConsumerWidget {
final playlist = ref.read(audioPlayerProvider);
final spotify = ref.read(spotifyProvider);
final query = "${track.name} Radio";
final pages =
await spotify.search.get(query, types: [SearchType.playlist]).first();
final pages = await spotify.invoke(
(api) => api.search.get(query, types: [SearchType.playlist]).first(),
);
final radios = pages
.expand((e) => e.items?.cast<PlaylistSimple>().toList() ?? [])
@ -165,8 +165,9 @@ class TrackOptions extends HookConsumerWidget {
await playback.addTrack(track);
}
final tracks =
await spotify.playlists.getTracksByPlaylistId(radio.id!).all();
final tracks = await spotify.invoke(
(api) => api.playlists.getTracksByPlaylistId(radio.id!).all(),
);
await playback.addTracks(
tracks.toList()

View File

@ -191,8 +191,7 @@ class TrackTile extends HookConsumerWidget {
const SizedBox(
width: 26,
height: 26,
child:
CircularProgressIndicator(size: 1.5),
child: CircularProgressIndicator(),
),
(_, _, true, _, _) => Icon(
SpotubeIcons.pause,

View File

@ -5,7 +5,7 @@ import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:spotube/collections/routes.dart';
import 'package:spotube/collections/routes.gr.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:flutter_sharing_intent/flutter_sharing_intent.dart';
import 'package:flutter_sharing_intent/model/sharing_file.dart';
import 'package:spotube/services/logger/logger.dart';
@ -27,7 +27,9 @@ void useDeepLinking(WidgetRef ref, AppRouter router) {
switch (url.pathSegments.first) {
case "album":
final album = await spotify.albums.get(url.pathSegments.last);
final album = await spotify.invoke((api) {
return api.albums.get(url.pathSegments.last);
});
router.navigate(
AlbumRoute(id: album.id!, album: album),
);
@ -36,7 +38,9 @@ void useDeepLinking(WidgetRef ref, AppRouter router) {
router.navigate(ArtistRoute(artistId: url.pathSegments.last));
break;
case "playlist":
final playlist = await spotify.playlists.get(url.pathSegments.last);
final playlist = await spotify.invoke((api) {
return api.playlists.get(url.pathSegments.last);
});
router
.navigate(PlaylistRoute(id: playlist.id!, playlist: playlist));
break;
@ -65,7 +69,9 @@ void useDeepLinking(WidgetRef ref, AppRouter router) {
switch (startSegment) {
case "spotify:album":
final album = await spotify.albums.get(endSegment);
final album = await spotify.invoke((api) {
return api.albums.get(endSegment);
});
await router.navigate(
AlbumRoute(id: album.id!, album: album),
);
@ -77,7 +83,9 @@ void useDeepLinking(WidgetRef ref, AppRouter router) {
await router.navigate(TrackRoute(trackId: endSegment));
break;
case "spotify:playlist":
final playlist = await spotify.playlists.get(endSegment);
final playlist = await spotify.invoke((api) {
return api.playlists.get(endSegment);
});
await router.navigate(
PlaylistRoute(id: playlist.id!, playlist: playlist),
);

View File

@ -4,7 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:spotify/spotify.dart';
import 'package:spotube/provider/authentication/authentication.dart';
import 'package:spotube/provider/audio_player/audio_player.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/provider/user_preferences/user_preferences_provider.dart';
import 'package:spotube/services/audio_player/audio_player.dart';
@ -28,8 +28,8 @@ void useEndlessPlayback(WidgetRef ref) {
final track = playlist.tracks.last;
final query = "${track.name} Radio";
final pages = await spotify.search
.get(query, types: [SearchType.playlist]).first();
final pages = await spotify.invoke((api) =>
api.search.get(query, types: [SearchType.playlist]).first());
final radios = pages
.expand((e) => e.items?.toList() ?? <PlaylistSimple>[])
@ -50,8 +50,8 @@ void useEndlessPlayback(WidgetRef ref) {
orElse: () => radios.first,
);
final tracks =
await spotify.playlists.getTracksByPlaylistId(radio.id!).all();
final tracks = await spotify.invoke(
(api) => api.playlists.getTracksByPlaylistId(radio.id!).all());
await playback.addTracks(
tracks.toList()

View File

@ -8,7 +8,7 @@ import 'package:spotube/collections/routes.gr.dart';
import 'package:spotube/collections/spotube_icons.dart';
import 'package:spotube/components/image/universal_image.dart';
import 'package:spotube/models/spotify_friends.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/spotify/spotify.dart';
class FriendItem extends HookConsumerWidget {
final SpotifyFriendActivity friend;
@ -95,8 +95,9 @@ class FriendItem extends HookConsumerWidget {
text: " ${friend.track.album.name}",
recognizer: TapGestureRecognizer()
..onTap = () async {
final album =
await spotify.albums.get(friend.track.album.id);
final album = await spotify.invoke(
(api) => api.albums.get(friend.track.album.id),
);
if (context.mounted) {
context.navigateTo(
AlbumRoute(id: album.id!, album: album),

View File

@ -8,6 +8,7 @@ import 'package:spotube/components/image/universal_image.dart';
import 'package:spotube/extensions/image.dart';
import 'package:spotube/extensions/string.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/utils/platform.dart';
import 'package:stroke_text/stroke_text.dart';
class GenreSectionCardPlaylistCard extends HookConsumerWidget {
@ -21,8 +22,10 @@ class GenreSectionCardPlaylistCard extends HookConsumerWidget {
Widget build(BuildContext context, ref) {
final theme = Theme.of(context);
final w = kIsDesktop ? 20 : 0;
return Container(
width: 115 * theme.scaling,
width: (115 + w) * theme.scaling,
decoration: BoxDecoration(
color: theme.colorScheme.background.withAlpha(75),
borderRadius: theme.borderRadiusMd,
@ -65,7 +68,7 @@ class GenreSectionCardPlaylistCard extends HookConsumerWidget {
ref.watch(playlistImageProvider(playlist.id!));
return SizedBox(
height: 100 * theme.scaling,
width: 100 * theme.scaling,
width: (100 + w) * theme.scaling,
child: Stack(
children: [
Positioned.fill(
@ -107,14 +110,14 @@ class GenreSectionCardPlaylistCard extends HookConsumerWidget {
),
fit: BoxFit.cover,
height: 100 * theme.scaling,
width: 100 * theme.scaling,
width: (100 + w) * theme.scaling,
),
),
Text(
playlist.name!,
maxLines: 2,
maxLines: 1,
overflow: TextOverflow.ellipsis,
).semiBold().small(),
).xSmall().bold(),
if (playlist.description != null)
Text(
playlist.description?.unescapeHtml().cleanHtml() ?? "",

View File

@ -99,91 +99,99 @@ class LocalFolderItem extends HookConsumerWidget {
itemCount: tracks.length,
itemBuilder: (context, index) {
final track = tracks[index];
return UniversalImage(
path: (track.album?.images).asUrlString(
placeholder: ImagePlaceholder.albumArt,
return Expanded(
child: UniversalImage(
path: (track.album?.images).asUrlString(
placeholder: ImagePlaceholder.albumArt,
),
fit: BoxFit.cover,
),
fit: BoxFit.cover,
);
},
),
),
const Gap(8),
Stack(
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Center(
child: Text(
isDownloadFolder
? context.l10n.downloads
: isCacheFolder
? context.l10n.cache_folder.capitalize()
: basename(folder),
style: const TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
Expanded(
child: Stack(
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Center(
child: Flexible(
child: Text(
isDownloadFolder
? context.l10n.downloads
: isCacheFolder
? context.l10n.cache_folder.capitalize()
: basename(folder),
style: const TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
Flexible(
child: Wrap(
spacing: 2,
runSpacing: 2,
children: [
for (final MapEntry(key: index, value: segment)
in segments.asMap().entries)
Text.rich(
TextSpan(
children: [
if (index != 0) const TextSpan(text: "/ "),
TextSpan(text: segment)
],
),
maxLines: 2,
).xSmall().muted(),
],
),
),
],
),
if (!isDownloadFolder && !isCacheFolder)
Align(
alignment: Alignment.topRight,
child: IconButton.ghost(
icon: const Icon(Icons.more_vert),
size: ButtonSize.small,
onPressed: () {
showDropdown(
context: context,
builder: (context) {
return DropdownMenu(
children: [
MenuButton(
leading: Icon(SpotubeIcons.folderRemove,
color: colorScheme.destructive),
child: Text(
context.l10n.remove_library_location),
onPressed: (context) {
final libraryLocations = ref
.read(userPreferencesProvider)
.localLibraryLocation;
ref
.read(userPreferencesProvider.notifier)
.setLocalLibraryLocation(
libraryLocations
.where((e) => e != folder)
.toList(),
);
},
)
],
);
},
);
},
),
),
Wrap(
spacing: 2,
runSpacing: 2,
children: [
for (final MapEntry(key: index, value: segment)
in segments.asMap().entries)
Text.rich(
TextSpan(
children: [
if (index != 0) const TextSpan(text: "/ "),
TextSpan(text: segment),
],
),
maxLines: 2,
).xSmall().muted(),
],
),
],
),
if (!isDownloadFolder && !isCacheFolder)
Align(
alignment: Alignment.topRight,
child: IconButton.ghost(
icon: const Icon(Icons.more_vert),
size: ButtonSize.small,
onPressed: () {
showDropdown(
context: context,
builder: (context) {
return DropdownMenu(
children: [
MenuButton(
leading: Icon(SpotubeIcons.folderRemove,
color: colorScheme.destructive),
child:
Text(context.l10n.remove_library_location),
onPressed: (context) {
final libraryLocations = ref
.read(userPreferencesProvider)
.localLibraryLocation;
ref
.read(userPreferencesProvider.notifier)
.setLocalLibraryLocation(
libraryLocations
.where((e) => e != folder)
.toList(),
);
},
)
],
);
},
);
},
),
),
],
],
),
),
const Spacer(),
],

View File

@ -19,7 +19,6 @@ import 'package:spotube/components/image/universal_image.dart';
import 'package:spotube/extensions/context.dart';
import 'package:spotube/extensions/image.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/provider/spotify_provider.dart';
class PlaylistCreateDialog extends HookConsumerWidget {
/// Track ids to add to the playlist
@ -260,7 +259,7 @@ class PlaylistCreateDialog extends HookConsumerWidget {
class PlaylistCreateDialogButton extends HookConsumerWidget {
const PlaylistCreateDialogButton({super.key});
showPlaylistDialog(BuildContext context, SpotifyApi spotify) {
showPlaylistDialog(BuildContext context, SpotifyApiWrapper spotify) {
showDialog(
context: context,
alignment: Alignment.center,

View File

@ -22,7 +22,6 @@ import 'package:spotube/extensions/context.dart';
import 'package:spotube/extensions/image.dart';
import 'package:spotube/models/spotify/recommendation_seeds.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/user_preferences/user_preferences_provider.dart';
import 'package:auto_route/auto_route.dart';
@ -70,22 +69,24 @@ class PlaylistGeneratorPage extends HookConsumerWidget {
leftSeedCount,
context.l10n.artists,
)),
fetchSeeds: (textEditingValue) => spotify.search
.get(
textEditingValue.text,
types: [SearchType.artist],
)
.first(6)
.then(
(v) => List.castFrom<dynamic, Artist>(
v.expand((e) => e.items ?? []).toList(),
fetchSeeds: (textEditingValue) => spotify.invoke(
(api) => api.search
.get(
textEditingValue.text,
types: [SearchType.artist],
)
.where(
(element) =>
artists.value.none((artist) => element.id == artist.id),
)
.toList(),
),
.first(6)
.then(
(v) => List.castFrom<dynamic, Artist>(
v.expand((e) => e.items ?? []).toList(),
)
.where(
(element) =>
artists.value.none((artist) => element.id == artist.id),
)
.toList(),
),
),
autocompleteOptionBuilder: (option, onSelected) => ButtonTile(
leading: Avatar(
initials: "O",
@ -146,22 +147,24 @@ class PlaylistGeneratorPage extends HookConsumerWidget {
leftSeedCount,
context.l10n.tracks,
)),
fetchSeeds: (textEditingValue) => spotify.search
.get(
textEditingValue.text,
types: [SearchType.track],
)
.first(6)
.then(
(v) => List.castFrom<dynamic, Track>(
v.expand((e) => e.items ?? []).toList(),
fetchSeeds: (textEditingValue) => spotify.invoke(
(api) => api.search
.get(
textEditingValue.text,
types: [SearchType.track],
)
.where(
(element) =>
tracks.value.none((track) => element.id == track.id),
)
.toList(),
),
.first(6)
.then(
(v) => List.castFrom<dynamic, Track>(
v.expand((e) => e.items ?? []).toList(),
)
.where(
(element) =>
tracks.value.none((track) => element.id == track.id),
)
.toList(),
),
),
autocompleteOptionBuilder: (option, onSelected) => ButtonTile(
leading: Avatar(
initials: option.name!.substring(0, 1),

View File

@ -1,6 +1,6 @@
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:spotube/provider/authentication/authentication.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/spotify/spotify.dart';
import 'package:spotube/services/custom_spotify_endpoints/spotify_endpoints.dart';
final customSpotifyEndpointProvider = Provider<CustomSpotifyEndpoints>((ref) {

View File

@ -22,11 +22,14 @@ class FavoriteAlbumState extends PaginatedState<AlbumSimple> {
class FavoriteAlbumNotifier
extends PaginatedAsyncNotifier<AlbumSimple, FavoriteAlbumState> {
@override
Future<List<AlbumSimple>> fetch(int offset, int limit) {
return spotify.me
.savedAlbums()
.getPage(limit, offset)
.then((value) => value.items?.toList() ?? []);
Future<List<AlbumSimple>> fetch(int offset, int limit) async {
return await spotify
.invoke(
(api) => api.me.savedAlbums().getPage(limit, offset),
)
.then(
(value) => value.items?.toList() ?? <AlbumSimple>[],
);
}
@override
@ -45,8 +48,10 @@ class FavoriteAlbumNotifier
if (state.value == null) return;
state = await AsyncValue.guard(() async {
await spotify.me.saveAlbums(ids);
final albums = await spotify.albums.list(ids);
await spotify.invoke((api) => api.me.saveAlbums(ids));
final albums = await spotify.invoke(
(api) => api.albums.list(ids),
);
return state.value!.copyWith(
items: [
@ -65,7 +70,7 @@ class FavoriteAlbumNotifier
if (state.value == null) return;
state = await AsyncValue.guard(() async {
await spotify.me.removeAlbums(ids);
await spotify.invoke((api) => api.me.removeAlbums(ids));
return state.value!.copyWith(
items: state.value!.items

View File

@ -3,8 +3,10 @@ part of '../spotify.dart';
final albumsIsSavedProvider = FutureProvider.autoDispose.family<bool, String>(
(ref, albumId) async {
final spotify = ref.watch(spotifyProvider);
return spotify.me.containsSavedAlbums([albumId]).then(
(value) => value[albumId] ?? false,
return spotify.invoke(
(api) => api.me.containsSavedAlbums([albumId]).then(
(value) => value[albumId] ?? false,
),
);
},
);

View File

@ -32,9 +32,9 @@ class AlbumReleasesNotifier
fetch(int offset, int limit) async {
final market = ref.read(userPreferencesProvider).market;
final albums = await spotify.browse
.newReleases(country: market)
.getPage(limit, offset);
final albums = await spotify.invoke(
(api) => api.browse.newReleases(country: market).getPage(limit, offset),
);
return albums.items?.map((album) => album.toAlbum()).toList() ?? [];
}

View File

@ -30,7 +30,9 @@ class AlbumTracksNotifier extends AutoDisposeFamilyPaginatedAsyncNotifier<Track,
@override
fetch(arg, offset, limit) async {
final tracks = await spotify.albums.tracks(arg.id!).getPage(limit, offset);
final tracks = await spotify.invoke(
(api) => api.albums.tracks(arg.id!).getPage(limit, offset),
);
final items = tracks.items?.map((e) => e.asTrack(arg)).toList() ?? [];
return (

View File

@ -31,9 +31,9 @@ class ArtistAlbumsNotifier extends AutoDisposeFamilyPaginatedAsyncNotifier<
@override
fetch(arg, offset, limit) async {
final market = ref.read(userPreferencesProvider).market;
final albums = await spotify.artists
.albums(arg, country: market)
.getPage(limit, offset);
final albums = await spotify.invoke(
(api) => api.artists.albums(arg, country: market).getPage(limit, offset),
);
final items = albums.items?.toList() ?? [];

View File

@ -6,5 +6,5 @@ final artistProvider =
final spotify = ref.watch(spotifyProvider);
return spotify.artists.get(artistId);
return spotify.invoke((api) => api.artists.get(artistId));
});

View File

@ -33,10 +33,12 @@ class FollowedArtistsNotifier
@override
fetch(offset, limit) async {
final artists = await spotify.me.following(FollowingType.artist).getPage(
limit,
offset ?? '',
);
final artists = await spotify.invoke(
(api) => api.me.following(FollowingType.artist).getPage(
limit,
offset ?? '',
),
);
return (artists.items?.toList() ?? [], artists.after);
}
@ -55,7 +57,9 @@ class FollowedArtistsNotifier
Future<void> _followArtists(List<String> artistIds) async {
try {
final creds = await spotify.getCredentials();
final creds = await spotify.invoke(
(api) => api.getCredentials(),
);
await dio.post(
"https://api-partner.spotify.com/pathfinder/v1/query",
@ -93,7 +97,9 @@ class FollowedArtistsNotifier
await _followArtists(artistIds);
state = await AsyncValue.guard(() async {
final artists = await spotify.artists.list(artistIds);
final artists = await spotify.invoke(
(api) => api.artists.list(artistIds),
);
return state.value!.copyWith(
items: [
@ -110,7 +116,9 @@ class FollowedArtistsNotifier
Future<void> removeArtists(List<String> artistIds) async {
if (state.value == null) return;
await spotify.me.unfollow(FollowingType.artist, artistIds);
await spotify.invoke(
(api) => api.me.unfollow(FollowingType.artist, artistIds),
);
state = await AsyncValue.guard(() async {
final artists = state.value!.items.where((artist) {
@ -136,7 +144,9 @@ final followedArtistsProvider =
final allFollowedArtistsProvider = FutureProvider<List<Artist>>(
(ref) async {
final spotify = ref.watch(spotifyProvider);
final artists = await spotify.me.following(FollowingType.artist).all();
final artists = await spotify.invoke(
(api) => api.me.following(FollowingType.artist).all(),
);
return artists.toList();
},
);

View File

@ -3,8 +3,10 @@ part of '../spotify.dart';
final artistIsFollowingProvider = FutureProvider.family(
(ref, String artistId) async {
final spotify = ref.watch(spotifyProvider);
return spotify.me.checkFollowing(FollowingType.artist, [artistId]).then(
(value) => value[artistId] ?? false,
return spotify.invoke(
(api) => api.me.checkFollowing(FollowingType.artist, [artistId]).then(
(value) => value[artistId] ?? false,
),
);
},
);

View File

@ -5,7 +5,9 @@ final relatedArtistsProvider = FutureProvider.autoDispose
ref.cacheFor();
final spotify = ref.watch(spotifyProvider);
final artists = await spotify.artists.relatedArtists(artistId);
final artists = await spotify.invoke(
(api) => api.artists.relatedArtists(artistId),
);
return artists.toList();
});

View File

@ -7,7 +7,9 @@ final artistTopTracksProvider =
final spotify = ref.watch(spotifyProvider);
final market = ref.watch(userPreferencesProvider.select((s) => s.market));
final tracks = await spotify.artists.topTracks(artistId, market);
final tracks = await spotify.invoke(
(api) => api.artists.topTracks(artistId, market),
);
return tracks.toList();
},

View File

@ -5,14 +5,16 @@ final categoriesProvider = FutureProvider(
final spotify = ref.watch(spotifyProvider);
final market = ref.watch(userPreferencesProvider.select((s) => s.market));
final locale = ref.watch(userPreferencesProvider.select((s) => s.locale));
final categories = await spotify.categories
.list(
country: market,
locale: Intl.canonicalizedLocale(
locale.toString(),
),
)
.all();
final categories = await spotify.invoke(
(api) => api.categories
.list(
country: market,
locale: Intl.canonicalizedLocale(
locale.toString(),
),
)
.all(),
);
return categories.toList()..shuffle();
},

View File

@ -32,7 +32,7 @@ class CategoryPlaylistsNotifier extends AutoDisposeFamilyPaginatedAsyncNotifier<
fetch(arg, offset, limit) async {
final preferences = ref.read(userPreferencesProvider);
final playlists = await Pages<PlaylistSimple?>(
spotify,
spotify.api,
"v1/browse/categories/$arg/playlists?country=${preferences.market.name}&locale=${preferences.locale}",
(json) => json == null ? null : PlaylistSimple.fromJson(json),
'playlists',

View File

@ -138,7 +138,7 @@ class SyncedLyricsNotifier extends FamilyAsyncNotifier<SubtitleSimple, Track?> {
SubtitleSimple? lyrics = cachedLyrics;
final token = await spotify.getCredentials();
final token = await spotify.invoke((api) => api.getCredentials());
if ((lyrics == null || lyrics.lyrics.isEmpty) && auth != null) {
lyrics = await getSpotifyLyrics(token.accessToken);

View File

@ -30,9 +30,11 @@ class FavoritePlaylistsNotifier
@override
fetch(int offset, int limit) async {
final playlists = await spotify.playlists.me.getPage(
limit,
offset,
final playlists = await spotify.invoke(
(api) => api.playlists.me.getPage(
limit,
offset,
),
);
return playlists.items?.toList() ?? [];
@ -67,7 +69,9 @@ class FavoritePlaylistsNotifier
Future<void> addFavorite(PlaylistSimple playlist) async {
await update((state) async {
await spotify.playlists.followPlaylist(playlist.id!);
await spotify.invoke(
(api) => api.playlists.followPlaylist(playlist.id!),
);
return state.copyWith(
items: [...state.items, playlist],
);
@ -78,7 +82,9 @@ class FavoritePlaylistsNotifier
Future<void> removeFavorite(PlaylistSimple playlist) async {
await update((state) async {
await spotify.playlists.unfollowPlaylist(playlist.id!);
await spotify.invoke(
(api) => api.playlists.unfollowPlaylist(playlist.id!),
);
return state.copyWith(
items: state.items.where((e) => e.id != playlist.id).toList(),
);
@ -92,9 +98,11 @@ class FavoritePlaylistsNotifier
final spotify = ref.read(spotifyProvider);
await spotify.playlists.addTracks(
trackIds.map((id) => 'spotify:track:$id').toList(),
playlistId,
await spotify.invoke(
(api) => api.playlists.addTracks(
trackIds.map((id) => 'spotify:track:$id').toList(),
playlistId,
),
);
ref.invalidate(playlistTracksProvider(playlistId));
@ -105,9 +113,11 @@ class FavoritePlaylistsNotifier
final spotify = ref.read(spotifyProvider);
await spotify.playlists.removeTracks(
trackIds.map((id) => 'spotify:track:$id').toList(),
playlistId,
await spotify.invoke(
(api) => api.playlists.removeTracks(
trackIds.map((id) => 'spotify:track:$id').toList(),
playlistId,
),
);
ref.invalidate(playlistTracksProvider(playlistId));
@ -128,8 +138,8 @@ final isFavoritePlaylistProvider = FutureProvider.family<bool, String>(
return false;
}
final follows =
await spotify.playlists.followedByUsers(id, [me.value!.id!]);
final follows = await spotify
.invoke((api) => api.playlists.followedByUsers(id, [me.value!.id!]));
return follows[me.value!.id!] ?? false;
},

View File

@ -30,9 +30,8 @@ class FeaturedPlaylistsNotifier
@override
fetch(int offset, int limit) async {
final playlists = await spotify.playlists.featured.getPage(
limit,
offset,
final playlists = await spotify.invoke(
(api) => api.playlists.featured.getPage(limit, offset),
);
return playlists.items?.toList() ?? [];

View File

@ -8,32 +8,36 @@ final generatePlaylistProvider = FutureProvider.autoDispose
userPreferencesProvider.select((s) => s.market),
);
final recommendation = await spotify.recommendations
.get(
limit: input.limit,
seedArtists: input.seedArtists?.toList(),
seedGenres: input.seedGenres?.toList(),
seedTracks: input.seedTracks?.toList(),
market: market,
max: (input.max?.toJson()?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
min: (input.min?.toJson()?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
target: (input.target?.toJson()
?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
)
.catchError((e, stackTrace) {
AppLogger.reportError(e, stackTrace);
return Recommendations();
});
final recommendation = await spotify.invoke(
(api) => api.recommendations
.get(
limit: input.limit,
seedArtists: input.seedArtists?.toList(),
seedGenres: input.seedGenres?.toList(),
seedTracks: input.seedTracks?.toList(),
market: market,
max: (input.max?.toJson()?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
min: (input.min?.toJson()?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
target: (input.target?.toJson()
?..removeWhere((key, value) => value == null))
?.cast<String, num>(),
)
.catchError((e, stackTrace) {
AppLogger.reportError(e, stackTrace);
return Recommendations();
}),
);
if (recommendation.tracks?.isEmpty ?? true) {
return [];
}
final tracks = await spotify.tracks
.list(recommendation.tracks!.map((e) => e.id!).toList());
final tracks = await spotify.invoke(
(api) =>
api.tracks.list(recommendation.tracks!.map((e) => e.id!).toList()),
);
return tracks.toList();
},

View File

@ -4,7 +4,9 @@ class LikedTracksNotifier extends AsyncNotifier<List<Track>> {
@override
FutureOr<List<Track>> build() async {
final spotify = ref.watch(spotifyProvider);
final savedTracked = await spotify.tracks.me.saved.all();
final savedTracked = await spotify.invoke(
(api) => api.tracks.me.saved.all(),
);
return savedTracked.map((e) => e.track!).toList();
}
@ -17,10 +19,14 @@ class LikedTracksNotifier extends AsyncNotifier<List<Track>> {
final isLiked = tracks.map((e) => e.id).contains(track.id);
if (isLiked) {
await spotify.tracks.me.removeOne(track.id!);
await spotify.invoke(
(api) => api.tracks.me.removeOne(track.id!),
);
return tracks.where((e) => e.id != track.id).toList();
} else {
await spotify.tracks.me.saveOne(track.id!);
await spotify.invoke(
(api) => api.tracks.me.saveOne(track.id!),
);
return [track, ...tracks];
}
});

View File

@ -12,7 +12,9 @@ class PlaylistNotifier extends FamilyAsyncNotifier<Playlist, String> {
@override
FutureOr<Playlist> build(String arg) {
final spotify = ref.watch(spotifyProvider);
return spotify.playlists.get(arg);
return spotify.invoke(
(api) => api.playlists.get(arg),
);
}
Future<void> create(PlaylistInput input, [ValueChanged? onError]) async {
@ -26,18 +28,22 @@ class PlaylistNotifier extends FamilyAsyncNotifier<Playlist, String> {
state = await AsyncValue.guard(() async {
try {
final playlist = await spotify.playlists.createPlaylist(
me.value!.id!,
input.playlistName,
collaborative: input.collaborative,
description: input.description,
public: input.public,
final playlist = await spotify.invoke(
(api) => api.playlists.createPlaylist(
me.value!.id!,
input.playlistName,
collaborative: input.collaborative,
description: input.description,
public: input.public,
),
);
if (input.base64Image != null) {
await spotify.playlists.updatePlaylistImage(
playlist.id!,
input.base64Image!,
await spotify.invoke(
(api) => api.playlists.updatePlaylistImage(
playlist.id!,
input.base64Image!,
),
);
}
@ -58,21 +64,27 @@ class PlaylistNotifier extends FamilyAsyncNotifier<Playlist, String> {
await update((state) async {
try {
await spotify.playlists.updatePlaylist(
state.id!,
input.playlistName,
collaborative: input.collaborative,
description: input.description,
public: input.public,
await spotify.invoke(
(api) => api.playlists.updatePlaylist(
state.id!,
input.playlistName,
collaborative: input.collaborative,
description: input.description,
public: input.public,
),
);
if (input.base64Image != null) {
await spotify.playlists.updatePlaylistImage(
state.id!,
input.base64Image!,
await spotify.invoke(
(api) => api.playlists.updatePlaylistImage(
state.id!,
input.base64Image!,
),
);
final playlist = await spotify.playlists.get(state.id!);
final playlist = await spotify.invoke(
(api) => api.playlists.get(state.id!),
);
ref.read(favoritePlaylistsProvider.notifier).updatePlaylist(playlist);
return playlist;
@ -105,9 +117,11 @@ class PlaylistNotifier extends FamilyAsyncNotifier<Playlist, String> {
final spotify = ref.read(spotifyProvider);
await spotify.playlists.addTracks(
trackIds.map((id) => "spotify:track:$id").toList(),
state.value!.id!,
await spotify.invoke(
(api) => api.playlists.addTracks(
trackIds.map((id) => "spotify:track:$id").toList(),
state.value!.id!,
),
);
} catch (e, stack) {
onError?.call(e);

View File

@ -30,9 +30,9 @@ class PlaylistTracksNotifier extends AutoDisposeFamilyPaginatedAsyncNotifier<
@override
fetch(arg, offset, limit) async {
final tracks = await spotify.playlists
.getTracksByPlaylistId(arg)
.getPage(limit, offset);
final tracks = await spotify.invoke(
(api) => api.playlists.getTracksByPlaylistId(arg).getPage(limit, offset),
);
/// Filter out tracks with null id because some personal playlists
/// may contain local tracks that are not available in the Spotify catalog

View File

@ -44,13 +44,15 @@ class SearchNotifier<Y> extends AutoDisposeFamilyPaginatedAsyncNotifier<Y,
nextOffset: 0,
);
}
final results = await spotify.search
.get(
ref.read(searchTermStateProvider),
types: [arg],
market: ref.read(userPreferencesProvider).market,
)
.getPage(limit, offset);
final results = await spotify.invoke(
(api) => api.search
.get(
ref.read(searchTermStateProvider),
types: [arg],
market: ref.read(userPreferencesProvider).market,
)
.getPage(limit, offset),
);
final items = results.expand((e) => e.items ?? <Y>[]).toList().cast<Y>();

View File

@ -5,6 +5,7 @@ import 'dart:math';
import 'package:drift/drift.dart';
import 'package:spotube/collections/assets.gen.dart';
import 'package:spotube/collections/env.dart';
import 'package:spotube/models/database/database.dart';
import 'package:spotube/provider/authentication/authentication.dart';
import 'package:spotube/provider/database/database.dart';
@ -25,10 +26,10 @@ import 'package:spotube/models/lyrics.dart';
import 'package:spotube/models/spotify/recommendation_seeds.dart';
import 'package:spotube/models/spotify_friends.dart';
import 'package:spotube/provider/custom_spotify_endpoint_provider.dart';
import 'package:spotube/provider/spotify_provider.dart';
import 'package:spotube/provider/user_preferences/user_preferences_provider.dart';
import 'package:spotube/services/dio/dio.dart';
import 'package:spotube/services/wikipedia/wikipedia.dart';
import 'package:spotube/utils/primitive_utils.dart';
import 'package:wikipedia_api/wikipedia_api.dart';
@ -76,3 +77,57 @@ part 'utils/provider/paginated.dart';
part 'utils/provider/cursor.dart';
part 'utils/provider/paginated_family.dart';
part 'utils/provider/cursor_family.dart';
class SpotifyApiWrapper {
final SpotifyApi api;
final Ref ref;
SpotifyApiWrapper(
this.ref,
this.api,
);
bool _isRefreshing = false;
FutureOr<T> invoke<T>(
FutureOr<T> Function(SpotifyApi api) fn,
) async {
try {
return await fn(api);
} catch (e) {
if (((e is AuthorizationException && e.error == 'invalid_token') ||
e is ExpirationException) &&
!_isRefreshing) {
_isRefreshing = true;
await ref.read(authenticationProvider.notifier).refreshCredentials();
_isRefreshing = false;
return await fn(api);
}
rethrow;
}
}
}
final spotifyProvider = Provider<SpotifyApiWrapper>(
(ref) {
final authState = ref.watch(authenticationProvider);
final anonCred = PrimitiveUtils.getRandomElement(Env.spotifySecrets);
final wrapper = SpotifyApiWrapper(
ref,
authState.asData?.value == null
? SpotifyApi(
SpotifyApiCredentials(
anonCred["clientId"],
anonCred["clientSecret"],
),
)
: SpotifyApi.withAccessToken(
authState.asData!.value!.accessToken.value,
),
);
return wrapper;
},
);

View File

@ -6,5 +6,5 @@ final trackProvider =
final spotify = ref.watch(spotifyProvider);
return spotify.tracks.get(id);
return spotify.invoke((api) => api.tracks.get(id));
});

View File

@ -2,5 +2,5 @@ part of '../spotify.dart';
final meProvider = FutureProvider<User>((ref) async {
final spotify = ref.watch(spotifyProvider);
return spotify.me.get();
return spotify.invoke((api) => api.me.get());
});

View File

@ -2,7 +2,7 @@ part of '../spotify.dart';
// ignore: invalid_use_of_internal_member
mixin SpotifyMixin<T> on AsyncNotifierBase<T> {
SpotifyApi get spotify => ref.read(spotifyProvider);
SpotifyApiWrapper get spotify => ref.read(spotifyProvider);
}
extension on AutoDisposeAsyncNotifierProviderRef {

View File

@ -1,22 +0,0 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:spotify/spotify.dart';
import 'package:spotube/collections/env.dart';
import 'package:spotube/provider/authentication/authentication.dart';
import 'package:spotube/utils/primitive_utils.dart';
final spotifyProvider = Provider<SpotifyApi>((ref) {
final authState = ref.watch(authenticationProvider);
final anonCred = PrimitiveUtils.getRandomElement(Env.spotifySecrets);
if (authState.asData?.value == null) {
return SpotifyApi(
SpotifyApiCredentials(
anonCred["clientId"],
anonCred["clientSecret"],
),
);
}
return SpotifyApi.withAccessToken(authState.asData!.value!.accessToken.value);
});

View File

@ -42,10 +42,10 @@ packages:
dependency: "direct main"
description:
name: app_links
sha256: ad1a6d598e7e39b46a34f746f9a8b011ee147e4c275d407fa457e7a62f84dd99
sha256: "85ed8fc1d25a76475914fff28cc994653bd900bc2c26e4b57a49e097febb54ba"
url: "https://pub.dev"
source: hosted
version: "6.3.2"
version: "6.4.0"
app_links_linux:
dependency: transitive
description:

View File

@ -3,7 +3,7 @@ description: Open source Spotify client that doesn't require Premium nor uses El
publish_to: "none"
version: 4.0.1+40
version: 4.0.2+41
homepage: https://spotube.krtirtho.dev
repository: https://github.com/KRTirtho/spotube
@ -13,7 +13,7 @@ environment:
flutter: ">=3.29.0"
dependencies:
app_links: ^6.3.2
app_links: ^6.4.0
args: ^2.5.0
async: ^2.11.0
audio_service: ^0.18.13