Skip to content

Commit

Permalink
cleanup rspotify::model imports
Browse files Browse the repository at this point in the history
  • Loading branch information
aome510 committed Nov 30, 2024
1 parent 6c1a5cc commit bedc83d
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 46 deletions.
29 changes: 13 additions & 16 deletions spotify_player/src/cli/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,12 @@ use crate::{
cli::Request,
client::{Client, PlayerRequest},
config::get_cache_folder_path,
state::{Context, ContextId, Playback, PlaybackMetadata, SharedState},
};
use rspotify::{
model::{
AlbumId, ArtistId, CurrentPlaybackContext, Id, PlayableId, PlaylistId, SearchResult,
SearchType, TrackId,
state::{
AlbumId, ArtistId, Context, ContextId, Id, PlayableId, Playback, PlaybackMetadata,
PlaylistId, SharedState, TrackId,
},
prelude::{BaseClient, OAuthClient},
};
use rspotify::prelude::{BaseClient, OAuthClient};

use super::{
Command, Deserialize, GetRequest, IdOrName, ItemId, ItemType, Key, PlaylistCommand, Response,
Expand Down Expand Up @@ -96,7 +93,7 @@ async fn send_response(
async fn current_playback(
client: &Client,
state: Option<&SharedState>,
) -> Result<Option<CurrentPlaybackContext>> {
) -> Result<Option<rspotify::model::CurrentPlaybackContext>> {
// get current playback from the application's state, if exists, or by making an API request
match state {
Some(state) => Ok(state.player.read().current_playback()),
Expand Down Expand Up @@ -230,11 +227,11 @@ async fn get_spotify_id(client: &Client, typ: ItemType, id_or_name: IdOrName) ->
IdOrName::Id(id) => ItemId::Playlist(PlaylistId::from_id(id)?),
IdOrName::Name(name) => {
let results = client
.search_specific_type(&name, SearchType::Playlist)
.search_specific_type(&name, rspotify::model::SearchType::Playlist)
.await?;

match results {
SearchResult::Playlists(page) => {
rspotify::model::SearchResult::Playlists(page) => {
if page.items.is_empty() {
anyhow::bail!("Cannot find playlist with name='{name}'");
}
Expand All @@ -248,11 +245,11 @@ async fn get_spotify_id(client: &Client, typ: ItemType, id_or_name: IdOrName) ->
IdOrName::Id(id) => ItemId::Album(AlbumId::from_id(id)?),
IdOrName::Name(name) => {
let results = client
.search_specific_type(&name, SearchType::Album)
.search_specific_type(&name, rspotify::model::SearchType::Album)
.await?;

match results {
SearchResult::Albums(page) => {
rspotify::model::SearchResult::Albums(page) => {
if !page.items.is_empty() && page.items[0].id.is_some() {
ItemId::Album(page.items[0].id.clone().unwrap())
} else {
Expand All @@ -267,11 +264,11 @@ async fn get_spotify_id(client: &Client, typ: ItemType, id_or_name: IdOrName) ->
IdOrName::Id(id) => ItemId::Artist(ArtistId::from_id(id)?),
IdOrName::Name(name) => {
let results = client
.search_specific_type(&name, SearchType::Artist)
.search_specific_type(&name, rspotify::model::SearchType::Artist)
.await?;

match results {
SearchResult::Artists(page) => {
rspotify::model::SearchResult::Artists(page) => {
if page.items.is_empty() {
anyhow::bail!("Cannot find artist with name='{name}'");
}
Expand All @@ -285,11 +282,11 @@ async fn get_spotify_id(client: &Client, typ: ItemType, id_or_name: IdOrName) ->
IdOrName::Id(id) => ItemId::Track(TrackId::from_id(id)?),
IdOrName::Name(name) => {
let results = client
.search_specific_type(&name, SearchType::Track)
.search_specific_type(&name, rspotify::model::SearchType::Track)
.await?;

match results {
SearchResult::Tracks(page) => {
rspotify::model::SearchResult::Tracks(page) => {
if !page.items.is_empty() && page.items[0].id.is_some() {
ItemId::Track(page.items[0].id.clone().unwrap())
} else {
Expand Down
5 changes: 2 additions & 3 deletions spotify_player/src/client/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use anyhow::Context;
use rspotify::model::PlayableItem;
use tracing::Instrument;

use crate::{
Expand Down Expand Up @@ -53,13 +52,13 @@ fn handle_playback_change_event(
player.buffered_playback.as_ref(),
player.currently_playing(),
) {
(Some(playback), Some(PlayableItem::Track(track))) => (
(Some(playback), Some(rspotify::model::PlayableItem::Track(track))) => (
playback,
PlayableId::Track(track.id.clone().expect("null track_id")),
&track.name,
track.duration,
),
(Some(playback), Some(PlayableItem::Episode(episode))) => (
(Some(playback), Some(rspotify::model::PlayableItem::Episode(episode))) => (
playback,
PlayableId::Episode(episode.id.clone()),
&episode.name,
Expand Down
50 changes: 31 additions & 19 deletions spotify_player/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,7 @@ use anyhow::Result;
use parking_lot::Mutex;

use reqwest::StatusCode;
use rspotify::model::{AdditionalType, CurrentPlaybackContext};
use rspotify::{
http::Query,
model::{FullPlaylist, Market, Page, SimplifiedPlaylist},
prelude::*,
};
use rspotify::{http::Query, prelude::*};

mod handlers;
mod request;
Expand All @@ -38,7 +33,10 @@ pub use request::*;
use serde::Deserialize;

const SPOTIFY_API_ENDPOINT: &str = "https://api.spotify.com/v1";
const PLAYBACK_TYPES: [&AdditionalType; 2] = [&AdditionalType::Track, &AdditionalType::Episode];
const PLAYBACK_TYPES: [&rspotify::model::AdditionalType; 2] = [
&rspotify::model::AdditionalType::Track,
&rspotify::model::AdditionalType::Episode,
];

/// The application's Spotify client
#[derive(Clone)]
Expand Down Expand Up @@ -721,7 +719,11 @@ impl Client {
/// Get the saved (liked) tracks of the current user
pub async fn current_user_saved_tracks(&self) -> Result<Vec<Track>> {
let first_page = self
.current_user_saved_tracks_manual(Some(Market::FromToken), Some(50), None)
.current_user_saved_tracks_manual(
Some(rspotify::model::Market::FromToken),
Some(50),
None,
)
.await?;
let tracks = self.all_paging_items(first_page, &market_query()).await?;
Ok(tracks
Expand Down Expand Up @@ -766,7 +768,7 @@ impl Client {
// TODO: this should use `rspotify::current_user_playlists_manual` API instead of `internal_call`
// See: https://github.com/ramsayleung/rspotify/issues/459
let first_page = self
.http_get::<Page<SimplifiedPlaylist>>(
.http_get::<rspotify::model::Page<rspotify::model::SimplifiedPlaylist>>(
&format!("{SPOTIFY_API_ENDPOINT}/me/playlists"),
&Query::from([("limit", "50")]),
false,
Expand Down Expand Up @@ -810,7 +812,11 @@ impl Client {
/// Get all saved albums of the current user
pub async fn current_user_saved_albums(&self) -> Result<Vec<Album>> {
let first_page = self
.current_user_saved_albums_manual(Some(Market::FromToken), Some(50), None)
.current_user_saved_albums_manual(
Some(rspotify::model::Market::FromToken),
Some(50),
None,
)
.await?;

let albums = self.all_paging_items(first_page, &Query::new()).await?;
Expand All @@ -835,7 +841,7 @@ impl Client {
.artist_albums_manual(
artist_id.as_ref(),
Some(rspotify::model::AlbumType::Single),
Some(Market::FromToken),
Some(rspotify::model::Market::FromToken),
Some(50),
None,
)
Expand All @@ -847,7 +853,7 @@ impl Client {
.artist_albums_manual(
artist_id.as_ref(),
Some(rspotify::model::AlbumType::Album),
Some(Market::FromToken),
Some(rspotify::model::Market::FromToken),
Some(50),
None,
)
Expand Down Expand Up @@ -946,7 +952,9 @@ impl Client {
.filter_map(|t| TrackId::from_id(t.original_gid).ok());

// Retrieve tracks based on IDs
let tracks = self.tracks(track_ids, Some(Market::FromToken)).await?;
let tracks = self
.tracks(track_ids, Some(rspotify::model::Market::FromToken))
.await?;
let tracks = tracks
.into_iter()
.filter_map(Track::try_from_full_track)
Expand Down Expand Up @@ -1258,7 +1266,7 @@ impl Client {
.user_data
.saved_shows
.retain(|s| s.id != id);
self.remove_users_saved_shows([id], Some(Market::FromToken))
self.remove_users_saved_shows([id], Some(rspotify::model::Market::FromToken))
.await?;
}
}
Expand All @@ -1269,7 +1277,7 @@ impl Client {
pub async fn track(&self, track_id: TrackId<'_>) -> Result<Track> {
Track::try_from_full_track(
self.spotify
.track(track_id, Some(Market::FromToken))
.track(track_id, Some(rspotify::model::Market::FromToken))
.await?,
)
.context("convert FullTrack into Track")
Expand All @@ -1286,7 +1294,7 @@ impl Client {
// .playlist(playlist_id, None, Some(Market::FromToken))
// .await?;
let playlist = self
.http_get::<FullPlaylist>(
.http_get::<rspotify::model::FullPlaylist>(
&format!("{SPOTIFY_API_ENDPOINT}/playlists/{}", playlist_id.id()),
&market_query(),
false,
Expand Down Expand Up @@ -1318,7 +1326,9 @@ impl Client {
let album_uri = album_id.uri();
tracing::info!("Get album context: {}", album_uri);

let album = self.album(album_id, Some(Market::FromToken)).await?;
let album = self
.album(album_id, Some(rspotify::model::Market::FromToken))
.await?;
let first_page = album.tracks.clone();

// converts `rspotify::model::FullAlbum` into `state::Album`
Expand Down Expand Up @@ -1357,7 +1367,7 @@ impl Client {
.into();

let top_tracks = self
.artist_top_tracks(artist_id.as_ref(), Some(Market::FromToken))
.artist_top_tracks(artist_id.as_ref(), Some(rspotify::model::Market::FromToken))
.await
.context("get artist's top tracks")?;
let top_tracks = top_tracks
Expand Down Expand Up @@ -1507,7 +1517,9 @@ impl Client {
Ok(items)
}

pub async fn current_playback2(&self) -> Result<Option<CurrentPlaybackContext>> {
pub async fn current_playback2(
&self,
) -> Result<Option<rspotify::model::CurrentPlaybackContext>> {
Ok(self.current_playback(None, PLAYBACK_TYPES.into()).await?)
}

Expand Down
15 changes: 7 additions & 8 deletions spotify_player/src/state/model.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
pub use rspotify::model::{
AlbumId, AlbumType, ArtistId, CurrentPlaybackContext, EpisodeId, Id, PlayableId, PlaylistId,
ShowId, TrackId, UserId,
AlbumId, ArtistId, EpisodeId, Id, PlayableId, PlaylistId, ShowId, TrackId, UserId,
};

use crate::utils::map_join;
Expand Down Expand Up @@ -147,7 +146,7 @@ pub struct Album {
pub release_date: String,
pub name: String,
pub artists: Vec<Artist>,
pub album_type: Option<AlbumType>,
pub album_type: Option<rspotify::model::AlbumType>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
Expand Down Expand Up @@ -384,10 +383,10 @@ impl Album {
album_type: album
.album_type
.and_then(|t| match t.to_ascii_lowercase().as_str() {
"album" => Some(AlbumType::Album),
"single" => Some(AlbumType::Single),
"appears_on" => Some(AlbumType::AppearsOn),
"compilation" => Some(AlbumType::Compilation),
"album" => Some(rspotify::model::AlbumType::Album),
"single" => Some(rspotify::model::AlbumType::Single),
"appears_on" => Some(rspotify::model::AlbumType::AppearsOn),
"compilation" => Some(rspotify::model::AlbumType::Compilation),
_ => None,
}),
})
Expand Down Expand Up @@ -648,7 +647,7 @@ impl Playback {
}

impl PlaybackMetadata {
pub fn from_playback(p: &CurrentPlaybackContext) -> Self {
pub fn from_playback(p: &rspotify::model::CurrentPlaybackContext) -> Self {
Self {
device_name: p.device.name.clone(),
device_id: p.device.id.clone(),
Expand Down

0 comments on commit bedc83d

Please sign in to comment.