diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c6dc7ee..c77c173 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v4.3.0 hooks: - id: end-of-file-fixer diff --git a/crates/downloader/Cargo.toml b/crates/downloader/Cargo.toml index d00c9eb..438e6b0 100644 --- a/crates/downloader/Cargo.toml +++ b/crates/downloader/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "spotifyio-downloader" description = "CLI for downloading music from Spotify" -version = "0.5.0" +version = "0.3.1" edition.workspace = true authors.workspace = true license.workspace = true diff --git a/crates/downloader/src/lib.rs b/crates/downloader/src/lib.rs index 1462fc5..b1bc9ae 100644 --- a/crates/downloader/src/lib.rs +++ b/crates/downloader/src/lib.rs @@ -17,24 +17,17 @@ use aes::cipher::{KeyIvInit, StreamCipher}; use futures_util::{stream, StreamExt, TryStreamExt}; use indicatif::{MultiProgress, ProgressBar}; use itertools::Itertools; -use lofty::{ - config::WriteOptions, - prelude::*, - tag::{ItemValue, Tag, TagItem}, -}; +use lofty::{config::WriteOptions, prelude::*, tag::Tag}; use model::{ album_type_str, convert_date, date_to_string, get_covers, parse_country_codes, - AlternativeTrack, ArtistItem, ArtistRole, ArtistWithRole, AudioFiles, AudioItem, DlAudioItem, - EpisodeUniqueFields, TrackUniqueFields, UnavailabilityReason, UniqueFields, + AlternativeTrack, ArtistItem, ArtistWithRole, AudioFiles, AudioItem, EpisodeUniqueFields, + TrackUniqueFields, UnavailabilityReason, UniqueFields, }; use once_cell::sync::Lazy; use path_macro::path; use serde::Serialize; use spotifyio::{ - model::{ - AlbumId, ArtistId, EpisodeId, FileId, Id, IdConstruct, IdError, PlayableId, PlaylistId, - TrackId, - }, + model::{AlbumId, ArtistId, EpisodeId, FileId, Id, IdConstruct, IdError, PlayableId, TrackId}, pb::AudioFileFormat, AudioKey, CdnUrl, Error as SpotifyError, NormalisationData, NotModifiedRes, PoolConfig, PoolError, Quota, Session, SessionConfig, SpotifyIoPool, @@ -50,8 +43,6 @@ pub mod model; type Aes128Ctr = ctr::Ctr128BE; -const DOT_SEPARATOR: &str = " • "; - #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Spotify: {0}")] @@ -654,7 +645,8 @@ impl SpotifyDownloader { let mut first = true; let mut cipher: Aes128Ctr = - Aes128Ctr::new(&audio_key.0.into(), &spotifyio::util::AUDIO_AESIV.into()); + Aes128Ctr::new_from_slices(&audio_key.0, &spotifyio::util::AUDIO_AESIV) + .unwrap(); let mut spotify_header = None; while let Some(item) = stream.next().await { @@ -670,8 +662,8 @@ impl SpotifyDownloader { drop(file); std::fs::rename(&tpath_tmp, dest)?; - let h = spotify_header.ok_or(SpotifyError::failed_precondition("no header"))?; - norm_data = Some(NormalisationData::parse_from_ogg(&mut Cursor::new(&h))?); + norm_data = spotify_header + .and_then(|h| NormalisationData::parse_from_ogg(Cursor::new(&h)).ok()); } AudioKeyVariant::Widevine(key) => { let decryptor = self @@ -698,7 +690,7 @@ impl SpotifyDownloader { &self, track_id: TrackId<'_>, force: bool, - ) -> Result, Error> { + ) -> Result, Error> { let pid = PlayableId::Track(track_id.as_ref()); let input_id_str = track_id.id().to_owned(); // Check if track was already downloaded @@ -824,7 +816,7 @@ impl SpotifyDownloader { &track_fields.album_name, track_fields.number, track_fields.disc_number, - &track_fields.artists, + &artist.name, &artists_json, album_id_str, Some(&album_artist.id), @@ -910,11 +902,7 @@ impl SpotifyDownloader { .execute(&self.i.pool) .await?; } - Ok(Some(DlAudioItem { - item: sp_item, - subdir_path: subpath, - dl_path: tpath, - })) + Ok(Some(sp_item)) } /// Download a Spotify track and log the error if one occurs @@ -923,19 +911,15 @@ impl SpotifyDownloader { /// This is the case if the download is either /// - successful /// - unavailable - pub async fn download_track_log( - &self, - track_id: TrackId<'_>, - force: bool, - ) -> (bool, Option) { + pub async fn download_track_log(&self, track_id: TrackId<'_>, force: bool) -> bool { for _ in 0..3 { match self.download_track(track_id.as_ref(), force).await { Ok(sp_item) => { if let Some(sp_item) = &sp_item { - if let UniqueFields::Track(sp_track) = &sp_item.item.unique_fields { + if let UniqueFields::Track(sp_track) = &sp_item.unique_fields { self.i.dl_tracks.write().unwrap().tracks.push(format!( "{} - {}", - sp_item.item.name, + sp_item.name, sp_track .artists .first() @@ -944,7 +928,7 @@ impl SpotifyDownloader { )); } } - return (true, sp_item); + return true; } Err(e) => { tracing::error!("[{track_id}] {e}"); @@ -956,14 +940,14 @@ impl SpotifyDownloader { .push(format!("[{track_id}]: {e}")); if matches!(e, Error::Unavailable(_)) { self.mark_track_unavailable(track_id).await.unwrap(); - return (true, None); + return true; } else if !matches!(e, Error::AudioKey(_)) { - return (false, None); + return false; } } } } - (false, None) + false } pub async fn download_artist( @@ -1064,7 +1048,7 @@ impl SpotifyDownloader { .for_each_concurrent(4, |id| { let success = success.clone(); async move { - let ok = self.download_track_log(id.as_ref(), false).await.0; + let ok = self.download_track_log(id.as_ref(), false).await; if !ok { success.store(false, Ordering::SeqCst); } @@ -1085,80 +1069,6 @@ impl SpotifyDownloader { Ok(success) } - pub async fn download_playlist(&self, playlist_id: PlaylistId<'_>) -> Result<(), Error> { - let playlist_id_str = playlist_id.id(); - let playlist = self - .i - .sp - .spclient()? - .pb_playlist(playlist_id.as_ref(), None) - .await? - .data; - - let track_ids = playlist - .contents - .items - .iter() - .filter_map(|itm| TrackId::from_uri(itm.uri()).ok()) - .collect::>(); - - let success = Arc::new(AtomicBool::new(true)); - - let playlist_data = stream::iter(track_ids.iter()) - .map(|id| { - let success = success.clone(); - let id_str = id.id(); - async move { - let (ok, item) = self.download_track_log(id.as_ref(), false).await; - if ok { - if let Some(item) = item { - return Ok(Some(item.subdir_path)); - } else { - let row = sqlx::query!("select path from tracks where id=$1", id_str) - .fetch_optional(&self.i.pool) - .await?; - if let Some(subdir_path) = row.and_then(|r| r.path) { - let audio_path = path!(self.i.base_dir / subdir_path); - if audio_path.is_file() { - return Ok(Some(path!(subdir_path))); - } else { - tracing::error!( - "[{id}] audio file not found: {}", - audio_path.to_string_lossy() - ); - success.store(false, Ordering::SeqCst); - } - } else { - tracing::error!("[{id}] audio file not found in db"); - success.store(false, Ordering::SeqCst); - } - } - } else { - success.store(false, Ordering::SeqCst); - } - Ok::<_, Error>(None) - } - }) - .buffered(4) - .try_collect::>() - .await? - .into_iter() - .filter_map(|x| x.and_then(|x| path!(".." / x).to_str().map(str::to_owned))) - .join("\n"); - - let pl_dir = path!(self.i.base_dir / "__Playlists"); - std::fs::create_dir_all(&pl_dir)?; - let pl_path = path!( - pl_dir - / better_filenamify( - playlist.attributes.name(), - Some(&format!(" [{playlist_id_str}].m3u")) - ) - ); - std::fs::write(pl_path, playlist_data)?; - Ok(()) - } - pub async fn download_new(&self, update_age_h: u32) -> Result<(), Error> { let date_thr = (OffsetDateTime::now_utc() - time::Duration::hours(update_age_h.into())) .unix_timestamp(); @@ -1405,7 +1315,7 @@ fn tag_file( album: &str, track_nr: u32, disc_nr: u32, - artists: &[ArtistWithRole], + artist: &str, artists_json: &str, album_id: &str, album_artist_id: Option<&str>, @@ -1431,35 +1341,7 @@ fn tag_file( tag.set_title(name.to_owned()); tag.set_album(album.to_owned()); tag.set_track(track_nr); - - let mut artist_names = Vec::new(); - let mut feat_names = Vec::new(); - - for artist in artists { - match artist.role { - ArtistRole::ArtistRoleFeaturedArtist => feat_names.push(artist.name.to_owned()), - ArtistRole::ArtistRoleComposer - | ArtistRole::ArtistRoleConductor - | ArtistRole::ArtistRoleRemixer => {} - _ => artist_names.push(artist.name.to_owned()), - } - - let k = match artist.role { - ArtistRole::ArtistRoleRemixer => ItemKey::Remixer, - ArtistRole::ArtistRoleComposer => ItemKey::Composer, - ArtistRole::ArtistRoleConductor => ItemKey::Conductor, - _ => ItemKey::TrackArtists, - }; - tag.push(TagItem::new(k, ItemValue::Text(artist.name.to_owned()))); - } - - let mut artist_names_str = artist_names.join(DOT_SEPARATOR); - if !feat_names.is_empty() { - artist_names_str += " feat. "; - artist_names_str += &feat_names.join(DOT_SEPARATOR); - } - - tag.set_artist(artist_names_str); + tag.set_artist(artist.to_owned()); tag.insert_text(ItemKey::AlbumArtist, album_artist.to_owned()); if let Some(date) = release_date { tag.insert_text(ItemKey::RecordingDate, fix_release_date(date)); diff --git a/crates/downloader/src/main.rs b/crates/downloader/src/main.rs index 274e347..0cf0a85 100644 --- a/crates/downloader/src/main.rs +++ b/crates/downloader/src/main.rs @@ -13,7 +13,7 @@ use clap::{Parser, Subcommand}; use futures_util::{stream, StreamExt, TryStreamExt}; use indicatif::{MultiProgress, ProgressBar}; use spotifyio::{ - model::{AlbumId, ArtistId, Id, IdConstruct, PlaylistId, SearchResult, SearchType, TrackId}, + model::{AlbumId, ArtistId, Id, IdConstruct, SearchResult, SearchType, TrackId}, ApplicationCache, AuthCredentials, AuthenticationType, Quota, Session, SessionConfig, }; use spotifyio_downloader::{Error, SpotifyDownloader, SpotifyDownloaderConfig}; @@ -113,10 +113,6 @@ enum Commands { #[clap(long)] force: bool, }, - /// Download a playlist - DlPlaylist { - playlist: Vec, - }, ScrapeAudioFeatures, } @@ -341,7 +337,7 @@ async fn download(cli: Cli, multi: MultiProgress) -> Result<(), Error> { let dl = dl.clone(); let success = success.clone(); async move { - let ok = dl.download_track_log(id.as_ref(), force).await.0; + let ok = dl.download_track_log(id.as_ref(), force).await; if !ok { success.store(false, Ordering::SeqCst); } @@ -354,29 +350,6 @@ async fn download(cli: Cli, multi: MultiProgress) -> Result<(), Error> { )); } } - Commands::DlPlaylist { playlist } => { - let playlist_ids = parse_url_ids::(&playlist)?; - let success = Arc::new(AtomicBool::new(true)); - stream::iter(playlist_ids) - .map(Ok::<_, Error>) - .try_for_each_concurrent(8, |id| { - let dl = dl.clone(); - let success = success.clone(); - async move { - if let Err(e) = dl.download_playlist(id.as_ref()).await { - tracing::error!("Error downloading playlist [{id}]: {e}"); - success.store(false, Ordering::SeqCst); - } - Ok(()) - } - }) - .await?; - if !success.load(Ordering::SeqCst) { - return Err(Error::Other( - "not all playlists downloaded successfully".into(), - )); - } - } Commands::ScrapeAudioFeatures => { let n = sqlx::query_scalar!(r#"select count(*) from tracks where audio_features is null"#) diff --git a/crates/downloader/src/model/mod.rs b/crates/downloader/src/model/mod.rs index fd08077..074e15f 100644 --- a/crates/downloader/src/model/mod.rs +++ b/crates/downloader/src/model/mod.rs @@ -1,5 +1,3 @@ -use std::path::PathBuf; - use serde::Serialize; use spotifyio::{ model::{AlbumId, ArtistId, FileId, IdConstruct, PlayableId, TrackId}, @@ -42,12 +40,6 @@ pub struct AudioItem { pub unique_fields: UniqueFields, } -pub struct DlAudioItem { - pub item: AudioItem, - pub subdir_path: PathBuf, - pub dl_path: PathBuf, -} - #[derive(Debug, Clone)] pub struct TrackUniqueFields { pub artists: Vec, diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index 7dddc6f..ae1a727 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -16,7 +16,7 @@ categories.workspace = true enum_dispatch = "0.3.8" serde = { version = "1", features = ["derive"] } serde_json = "1" -strum = { version = "0.27", features = ["derive"] } +strum = { version = "0.26.1", features = ["derive"] } thiserror = "2" time = { version = "0.3.21", features = ["serde-well-known"] } data-encoding = "2.5" diff --git a/crates/model/src/idtypes.rs b/crates/model/src/idtypes.rs index ec705b4..708ce69 100644 --- a/crates/model/src/idtypes.rs +++ b/crates/model/src/idtypes.rs @@ -843,115 +843,6 @@ impl<'de> Deserialize<'de> for PlayableId<'static> { } } -#[enum_dispatch(Id)] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub enum UserlikeId<'a> { - User(UserId<'a>), - Artist(ArtistId<'a>), -} -impl IdBase62 for UserlikeId<'_> {} - -// These don't work with `enum_dispatch`, unfortunately. -impl<'a> UserlikeId<'a> { - #[must_use] - pub fn as_ref(&'a self) -> Self { - match self { - UserlikeId::User(x) => UserlikeId::User(x.as_ref()), - UserlikeId::Artist(x) => UserlikeId::Artist(x.as_ref()), - } - } - - #[must_use] - pub fn into_static(self) -> UserlikeId<'static> { - match self { - UserlikeId::User(x) => UserlikeId::User(x.into_static()), - UserlikeId::Artist(x) => UserlikeId::Artist(x.into_static()), - } - } - - #[must_use] - pub fn clone_static(&'a self) -> UserlikeId<'static> { - match self { - UserlikeId::User(x) => UserlikeId::User(x.clone_static()), - UserlikeId::Artist(x) => UserlikeId::Artist(x.clone_static()), - } - } - - /// Parse Spotify URI from string slice - /// - /// Spotify URI must be in one of the following formats: - /// `spotify:{type}:{id}` or `spotify/{type}/{id}`. - /// Where `{type}` is one of `artist`, `album`, `track`, - /// `playlist`, `user`, `show`, or `episode`, and `{id}` is a - /// non-empty valid string. - /// - /// Examples: `spotify:album:6IcGNaXFRf5Y1jc7QsE9O2`, - /// `spotify/track/4y4VO05kYgUTo2bzbox1an`. - /// - /// # Errors - /// - /// - `IdError::InvalidPrefix` - if `uri` is not started with - /// `spotify:` or `spotify/`, - /// - `IdError::InvalidType` - if type part of an `uri` is not a - /// valid Spotify type `T`, - /// - `IdError::InvalidId` - if id part of an `uri` is not a - /// valid id, - /// - `IdError::InvalidFormat` - if it can't be splitted into - /// type and id parts. - pub fn from_uri(uri: &'a str) -> Result { - let (tpe, id) = parse_uri(uri)?; - match tpe { - SpotifyType::User => Ok(Self::User(UserId::from_id(id)?)), - SpotifyType::Artist => Ok(Self::Artist(ArtistId::from_id(id)?)), - _ => Err(IdError::InvalidType), - } - } -} - -/// Displaying the ID shows its URI -impl std::fmt::Display for UserlikeId<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.uri()) - } -} - -impl Serialize for UserlikeId<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - serializer.serialize_str(&self.uri()) - } -} - -impl<'de> Deserialize<'de> for UserlikeId<'static> { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - struct UriVisitor; - - impl serde::de::Visitor<'_> for UriVisitor { - type Value = UserlikeId<'static>; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("URI for PlayableId") - } - - fn visit_str(self, v: &str) -> Result - where - E: serde::de::Error, - { - UserlikeId::from_uri(v) - .map(UserlikeId::into_static) - .map_err(serde::de::Error::custom) - } - } - - deserializer.deserialize_str(UriVisitor) - } -} - #[cfg(test)] mod test { use super::*; diff --git a/crates/spotifyio/Cargo.toml b/crates/spotifyio/Cargo.toml index 71bdfec..447125b 100644 --- a/crates/spotifyio/Cargo.toml +++ b/crates/spotifyio/Cargo.toml @@ -62,20 +62,19 @@ rand = "0.8" rsa = "0.9.2" httparse = "1.7" base64 = "0.22" -oauth2 = { version = "5.0.0", default-features = false, features = [ +oauth2 = { version = "5.0.0-rc.1", default-features = false, features = [ "reqwest", ], optional = true } pin-project-lite = "0.2" quick-xml = "0.37" urlencoding = "2.1.0" parking_lot = "0.12.0" -governor = { version = "0.10", default-features = false, features = [ +governor = { version = "0.8", default-features = false, features = [ "std", "quanta", "jitter", ] } async-stream = "0.3.0" -ogg_pager = "0.7.0" protobuf.workspace = true spotifyio-protocol.workspace = true diff --git a/crates/spotifyio/src/connection/proxytunnel.rs b/crates/spotifyio/src/connection/proxytunnel.rs index 9e8cd3b..af51bbb 100644 --- a/crates/spotifyio/src/connection/proxytunnel.rs +++ b/crates/spotifyio/src/connection/proxytunnel.rs @@ -22,7 +22,7 @@ pub async fn proxy_connect( loop { let bytes_read = proxy_connection.read(&mut buffer[offset..]).await?; if bytes_read == 0 { - return Err(io::Error::other("Early EOF from proxy")); + return Err(io::Error::new(io::ErrorKind::Other, "Early EOF from proxy")); } offset += bytes_read; @@ -31,7 +31,7 @@ pub async fn proxy_connect( let status = response .parse(&buffer[..offset]) - .map_err(io::Error::other)?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; if status.is_complete() { return match response.code { @@ -39,9 +39,12 @@ pub async fn proxy_connect( Some(code) => { let reason = response.reason.unwrap_or("no reason"); let msg = format!("Proxy responded with {code}: {reason}"); - Err(io::Error::other(msg)) + Err(io::Error::new(io::ErrorKind::Other, msg)) } - None => Err(io::Error::other("Malformed response from proxy")), + None => Err(io::Error::new( + io::ErrorKind::Other, + "Malformed response from proxy", + )), }; } diff --git a/crates/spotifyio/src/gql_model.rs b/crates/spotifyio/src/gql_model.rs index 699df29..35292e9 100644 --- a/crates/spotifyio/src/gql_model.rs +++ b/crates/spotifyio/src/gql_model.rs @@ -8,7 +8,6 @@ use time::OffsetDateTime; use spotifyio_model::{ AlbumId, ArtistId, ConcertId, PlaylistId, PrereleaseId, SongwriterId, TrackId, UserId, - UserlikeId, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -527,8 +526,8 @@ pub struct PublicPlaylistItem { } #[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct UserProfilesWrap { - pub profiles: Vec, +pub(crate) struct UserProfilesWrap { + pub profiles: Vec, } /// May be an artist or an user @@ -541,16 +540,6 @@ pub struct FollowerItem { pub image_url: Option, } -/// May be an artist or an user -#[derive(Debug, Clone, Serialize, Deserialize)] -#[non_exhaustive] -pub(crate) struct FollowerItemUserlike { - pub uri: UserlikeId<'static>, - pub name: Option, - pub followers_count: Option, - pub image_url: Option, -} - /// Seektable for AAC tracks #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Seektable { @@ -632,20 +621,3 @@ impl From> for Option { value.data.into_option() } } - -impl TryFrom for FollowerItem { - type Error = (); - - fn try_from(value: FollowerItemUserlike) -> Result { - if let UserlikeId::User(uri) = value.uri { - Ok(Self { - uri, - name: value.name, - followers_count: value.followers_count, - image_url: value.image_url, - }) - } else { - Err(()) - } - } -} diff --git a/crates/spotifyio/src/normalisation.rs b/crates/spotifyio/src/normalisation.rs index f8744ca..f65fbb3 100644 --- a/crates/spotifyio/src/normalisation.rs +++ b/crates/spotifyio/src/normalisation.rs @@ -1,4 +1,4 @@ -use std::io::{Cursor, Read, Seek}; +use std::io::{Read, Seek, SeekFrom}; use byteorder::{LittleEndian, ReadBytesExt}; @@ -6,34 +6,34 @@ use crate::Error; /// Audio metadata for volume normalization /// +/// Spotify provides these as `f32`, but audio metadata can contain up to `f64`. +/// Also, this negates the need for casting during sample processing. +/// /// More information about ReplayGain and how to apply this infomation to audio files /// can be found here: . #[derive(Clone, Copy, Debug)] pub struct NormalisationData { - pub track_gain_db: f32, - pub track_peak: f32, - pub album_gain_db: f32, - pub album_peak: f32, + pub track_gain_db: f64, + pub track_peak: f64, + pub album_gain_db: f64, + pub album_peak: f64, } impl NormalisationData { - /// Parse normalisation data from a Spotify OGG header (first 167 bytes) - pub fn parse_from_ogg(file: &mut R) -> Result { - let packets = ogg_pager::Packets::read_count(file, 1) - .map_err(|e| Error::failed_precondition(format!("invalid ogg file: {e}")))?; - let packet = packets.get(0).unwrap(); - if packet.len() != 139 { + pub fn parse_from_ogg(mut file: T) -> Result { + const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144; + let newpos = file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET))?; + if newpos != SPOTIFY_NORMALIZATION_HEADER_START_OFFSET { return Err(Error::failed_precondition(format!( - "ogg header len={}, expected=139", - packet.len() + "NormalisationData::parse_from_ogg seeking to {} but position is now {}", + SPOTIFY_NORMALIZATION_HEADER_START_OFFSET, newpos ))); } - let mut rdr = Cursor::new(&packet[116..]); - let track_gain_db = rdr.read_f32::()?; - let track_peak = rdr.read_f32::()?; - let album_gain_db = rdr.read_f32::()?; - let album_peak = rdr.read_f32::()?; + let track_gain_db = file.read_f32::()? as f64; + let track_peak = file.read_f32::()? as f64; + let album_gain_db = file.read_f32::()? as f64; + let album_peak = file.read_f32::()? as f64; Ok(Self { track_gain_db, diff --git a/crates/spotifyio/src/pool.rs b/crates/spotifyio/src/pool.rs index 783225b..b46b636 100644 --- a/crates/spotifyio/src/pool.rs +++ b/crates/spotifyio/src/pool.rs @@ -86,7 +86,7 @@ impl ClientPool { fn next_pos(&self, timeout: Option) -> Result<(usize, Duration), PoolError> { let mut robin = self.robin.lock(); let mut i = *robin; - let mut min_to = Duration::MAX; + let mut max_to = Duration::ZERO; for _ in 0..((self.len() - 1).max(1)) { let entry = &self.entries[i]; @@ -100,7 +100,7 @@ impl ClientPool { Err(not_until) => { let wait_time = not_until.wait_time_from(entry.limiter.clock().now()); if timeout.is_some_and(|to| wait_time > to) { - min_to = min_to.min(wait_time); + max_to = max_to.max(wait_time); } else { *robin = self.wrapping_inc(i); return Ok((i, wait_time)); @@ -111,10 +111,10 @@ impl ClientPool { i = self.wrapping_inc(i); } // If the pool is empty or all entries were skipped - Err(if min_to == Duration::MAX { + Err(if max_to == Duration::ZERO { PoolError::Empty } else { - PoolError::Timeout(min_to) + PoolError::Timeout(max_to) }) } @@ -151,11 +151,7 @@ impl ClientPool { let entry = &self.entries[i]; if !wait_time.is_zero() { let wait_with_jitter = self.jitter + wait_time; - if wait_with_jitter > Duration::from_secs(10) { - tracing::info!("waiting for {}s", wait_with_jitter.as_secs()); - } else { - tracing::debug!("waiting for {}s", wait_with_jitter.as_secs()); - }; + tracing::debug!("pool: waiting for {wait_with_jitter:?}"); tokio::time::sleep(wait_with_jitter).await; } Ok(&entry.entry) diff --git a/crates/spotifyio/src/spclient.rs b/crates/spotifyio/src/spclient.rs index 14b226d..74dd472 100644 --- a/crates/spotifyio/src/spclient.rs +++ b/crates/spotifyio/src/spclient.rs @@ -33,9 +33,9 @@ use crate::{ error::ErrorKind, gql_model::{ ArtistGql, ArtistGqlWrap, Concert, ConcertGql, ConcertGqlWrap, ConcertOption, FollowerItem, - FollowerItemUserlike, GqlPlaylistItem, GqlSearchResult, GqlWrap, Lyrics, LyricsWrap, - PlaylistWrap, PrereleaseItem, PrereleaseLookup, SearchItemType, SearchResultWrap, - Seektable, TrackCredits, UserPlaylists, UserProfile, UserProfilesWrap, + GqlPlaylistItem, GqlSearchResult, GqlWrap, Lyrics, LyricsWrap, PlaylistWrap, + PrereleaseItem, PrereleaseLookup, SearchItemType, SearchResultWrap, Seektable, + TrackCredits, UserPlaylists, UserProfile, UserProfilesWrap, }, model::{ AlbumId, AlbumType, ArtistId, AudioAnalysis, AudioFeatures, AudioFeaturesPayload, Category, @@ -1200,31 +1200,23 @@ impl SpClient { pub async fn get_user_followers(&self, id: UserId<'_>) -> Result, Error> { debug!("getting user followers {id}"); let res = self - .request_get_json::>(&format!( + .request_get_json::(&format!( "/user-profile-view/v3/profile/{}/followers?market=from_token", id.id() )) .await?; - Ok(res - .profiles - .into_iter() - .filter_map(|p| p.try_into().ok()) - .collect()) + Ok(res.profiles) } pub async fn get_user_following(&self, id: UserId<'_>) -> Result, Error> { debug!("getting user following {id}"); let res = self - .request_get_json::>(&format!( + .request_get_json::(&format!( "/user-profile-view/v3/profile/{}/following?market=from_token", id.id() )) .await?; - Ok(res - .profiles - .into_iter() - .filter_map(|p| p.try_into().ok()) - .collect()) + Ok(res.profiles) } // PUBLIC SPOTIFY API - FROM RSPOTIFY