Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Meris/refactor playable playcontext #305

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
5e90864
fix: start refactor
merisbahti Mar 9, 2022
a6c0654
fix some more refactor
merisbahti Mar 9, 2022
62ba63f
fix: it compiles
merisbahti Mar 10, 2022
e43c253
More performant version done!
marioortizmanero May 25, 2022
cbc1177
Almost there
marioortizmanero May 27, 2022
0f6d439
introduce as_borrowed() for id types
eladyn May 28, 2022
e07a0ed
fix tests
eladyn May 28, 2022
b25790a
Rename as_borrowed to as_ref
marioortizmanero Jun 2, 2022
1799615
Fix part of the docs
marioortizmanero Jun 2, 2022
3f787bb
Considerably neater implementation
marioortizmanero Jun 2, 2022
ad36d6a
Fix tests & docs
marioortizmanero Jun 2, 2022
a5fbd25
Back to double-collect join_ids
marioortizmanero Jun 11, 2022
3d68efb
Better docs
marioortizmanero Jun 11, 2022
5613da3
Resolve all that was left
marioortizmanero Jun 11, 2022
eb6c1e4
Fix tests and string interpolation
marioortizmanero Jun 11, 2022
c50235b
Webapp example compiles now
marioortizmanero Jun 11, 2022
8ae1d22
Attempt at generic constructors
marioortizmanero Jun 11, 2022
2911b0f
Revert parameter to &str
marioortizmanero Jun 17, 2022
8da83af
Update CHANGELOG
marioortizmanero Jun 17, 2022
8019a54
Fix clippy
marioortizmanero Jun 17, 2022
9d15b04
Remove extra clone, as pointed out by @eladyn
marioortizmanero Jun 17, 2022
ccc0d0d
Fix tests
marioortizmanero Jun 17, 2022
8ba2739
Merge branch 'master' into meris/refactor-playable-playcontext
marioortizmanero Jun 24, 2022
8689d94
Fix typo
marioortizmanero Jul 2, 2022
05d8e56
Merge branch 'master' into meris/refactor-playable-playcontext
marioortizmanero Jul 3, 2022
2796b1e
More tests for to_owned
marioortizmanero Jul 3, 2022
a0b47e6
Fix clippy
marioortizmanero Jul 3, 2022
0b63f89
Use more string formatting capture
marioortizmanero Jul 3, 2022
a75fe44
Update CHANGELOG
marioortizmanero Jul 9, 2022
db0d7fa
Minor improvements
marioortizmanero Jul 9, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
- ([#332](https://github.com/ramsayleung/rspotify/pull/332)) Fix typo in `RestrictionReason` enum values

**Breaking changes**:
- ([#305](https://github.com/ramsayleung/rspotify/pull/305)) The `Id` types have been refactored to maximize usability. Instead of focusing on having an object-safe trait and using `dyn Id`, we now have enums to group up the IDs. This is based on how [`enum_dispatch`](https://docs.rs/enum_dispatch) works, and it's not only easier to use, but also more efficient. It makes it possible to have borrowed IDs again, so we've chosen to use `Cow` internally for flexibility. Check out the docs for more information!

Please let us know if there is anything that could be improved. Unfortunately, this breaks many methods in `BaseClient` and `OAuthClient`, but the errors should occur at compile-time only.
- ([#325](https://github.com/ramsayleung/rspotify/pull/325)) The `auth_code`, `auth_code_pkce`, `client_creds`, `clients::base` and `clients::oauth` modules have been removed from the public API; you should access the same types from their parent modules instead
- ([#326](https://github.com/ramsayleung/rspotify/pull/326)) The `rspotify::clients::mutex` module has been renamed to `rspotify::sync`
- ([#330](https://github.com/ramsayleung/rspotify/pull/330)) `search` now accepts `Option<IncludeExternal>` instead of `Option<&IncludeExternal>`
Expand Down
2 changes: 1 addition & 1 deletion examples/auth_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,5 @@ async fn main() {
.current_playing(Some(market), Some(&additional_types))
.await;

println!("Response: {:?}", artists);
println!("Response: {artists:?}");
}
4 changes: 2 additions & 2 deletions examples/auth_code_pkce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async fn main() {

// Running the requests
let history = spotify.current_playback(None, None::<Vec<_>>).await;
println!("Response: {:?}", history);
println!("Response: {history:?}");

// Token refreshing works as well, but only with the one generated in the
// previous request (they actually expire, unlike the regular code auth
Expand All @@ -51,5 +51,5 @@ async fn main() {

// Running the requests again
let history = spotify.current_playback(None, None::<Vec<_>>).await;
println!("Response after refreshing token: {:?}", history);
println!("Response after refreshing token: {history:?}");
}
4 changes: 2 additions & 2 deletions examples/client_creds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async fn main() {

// Running the requests
let birdy_uri = AlbumId::from_uri("spotify:album:0sNOF9WDwhWunNAHPD3Baj").unwrap();
let albums = spotify.album(&birdy_uri).await;
let albums = spotify.album(birdy_uri).await;

println!("Response: {:#?}", albums);
println!("Response: {albums:#?}");
}
2 changes: 1 addition & 1 deletion examples/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn main() {
let spotify = Arc::clone(&spotify);
let wr = wr.clone();
let handle = task::spawn(async move {
let albums = spotify.album(&id).await.unwrap();
let albums = spotify.album(id).await.unwrap();
wr.send(albums).unwrap();
});

Expand Down
2 changes: 1 addition & 1 deletion examples/ureq/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ fn main() {

let devices = spotify.device();

println!("Request: {:?}", devices);
println!("Request: {devices:?}");
}
2 changes: 1 addition & 1 deletion examples/ureq/me.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ fn main() {
spotify.prompt_for_token(&url).unwrap();

let user = spotify.me();
println!("Request: {:?}", user);
println!("Request: {user:?}");
}
24 changes: 12 additions & 12 deletions examples/ureq/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ fn main() {
let album_query = "album:arrival artist:abba";
let result = spotify.search(album_query, SearchType::Album, None, None, Some(10), None);
match result {
Ok(album) => println!("searched album:{:?}", album),
Err(err) => println!("search error!{:?}", err),
Ok(album) => println!("Searched album: {album:?}"),
Err(err) => println!("Search error! {err:?}"),
}

let artist_query = "tania bowra";
Expand All @@ -33,8 +33,8 @@ fn main() {
None,
);
match result {
Ok(album) => println!("searched artist:{:?}", album),
Err(err) => println!("search error!{:?}", err),
Ok(album) => println!("Searched artist: {album:?}"),
Err(err) => println!("Search error! {err:?}"),
}

let playlist_query = "\"doom metal\"";
Expand All @@ -47,8 +47,8 @@ fn main() {
None,
);
match result {
Ok(album) => println!("searched playlist:{:?}", album),
Err(err) => println!("search error!{:?}", err),
Ok(album) => println!("Searched playlist: {album:?}"),
Err(err) => println!("Search error! {err:?}"),
}

let track_query = "abba";
Expand All @@ -61,15 +61,15 @@ fn main() {
None,
);
match result {
Ok(album) => println!("searched track:{:?}", album),
Err(err) => println!("search error!{:?}", err),
Ok(album) => println!("Searched track: {album:?}"),
Err(err) => println!("Search error! {err:?}"),
}

let show_query = "love";
let result = spotify.search(show_query, SearchType::Show, None, None, Some(10), None);
match result {
Ok(show) => println!("searched show:{:?}", show),
Err(err) => println!("search error!{:?}", err),
Ok(show) => println!("Searched show: {show:?}"),
Err(err) => println!("Search error! {err:?}"),
}

let episode_query = "love";
Expand All @@ -82,7 +82,7 @@ fn main() {
None,
);
match result {
Ok(episode) => println!("searched episode:{:?}", episode),
Err(err) => println!("search error!{:?}", err),
Ok(episode) => println!("Searched episode: {episode:?}"),
Err(err) => println!("Search error! {err:?}"),
}
}
4 changes: 2 additions & 2 deletions examples/ureq/seek_track.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn main() {
spotify.prompt_for_token(&url).unwrap();

match spotify.seek_track(25000, None) {
Ok(_) => println!("change to previous playback successful"),
Err(_) => eprintln!("change to previous playback failed"),
Ok(_) => println!("Change to previous playback successful"),
Err(_) => eprintln!("Change to previous playback failed"),
}
}
2 changes: 1 addition & 1 deletion examples/ureq/threading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn main() {
let spotify = Arc::clone(&spotify);
let wr = wr.clone();
let handle = thread::spawn(move || {
let albums = spotify.album(&id).unwrap();
let albums = spotify.album(id).unwrap();
wr.send(albums).unwrap();
});

Expand Down
11 changes: 7 additions & 4 deletions examples/webapp/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
[package]
name = "webapp"
version = "0.1.0"
authors = ["Ramsay <[email protected]>"]
authors = [
"Ramsay Leung <[email protected]>",
"Mario Ortiz Manero <[email protected]>"
]
edition = "2018"

[dependencies]
rocket = "0.4.5"
rocket_contrib = { version = "0.4.5", features = ["tera_templates"] }
getrandom = "0.2.0"
rocket = "0.4.10"
rocket_contrib = { version = "0.4.10", features = ["tera_templates"] }
getrandom = "0.2.6"
# Rocket is synchronous, so this uses the `ureq` client
rspotify = { path = "../..", features = ["client-ureq", "ureq-rustls-tls"], default-features = false }
19 changes: 10 additions & 9 deletions examples/webapp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ use rocket::response::Redirect;
use rocket_contrib::json;
use rocket_contrib::json::JsonValue;
use rocket_contrib::templates::Template;
use rspotify::{scopes, AuthCodeSpotify, OAuth, Credentials, Config, prelude::*, Token};
use rspotify::{prelude::*, scopes, AuthCodeSpotify, Config, Credentials, OAuth, Token};

use std::fs;
use std::{
collections::HashMap,
env,
env, fs,
path::PathBuf,
sync::{Arc, Mutex},
};

#[derive(Debug, Responder)]
Expand Down Expand Up @@ -95,7 +95,7 @@ fn init_spotify(cookies: &Cookies) -> AuthCodeSpotify {
// Replacing client_id and client_secret with yours.
let creds = Credentials::new(
"e1dce60f1e274e20861ce5d96142a4d3",
"0e4e03b9be8d465d87fc32857a4b5aa3"
"0e4e03b9be8d465d87fc32857a4b5aa3",
);

AuthCodeSpotify::with_config(creds, oauth, config)
Expand Down Expand Up @@ -149,7 +149,7 @@ fn index(mut cookies: Cookies) -> AppResponse {
AppResponse::Template(Template::render("index", context.clone()))
}
Err(err) => {
context.insert("err_msg", format!("Failed for {}!", err));
context.insert("err_msg", format!("Failed for {err}!"));
AppResponse::Template(Template::render("error", context))
}
}
Expand All @@ -168,9 +168,10 @@ fn playlist(cookies: Cookies) -> AppResponse {
return AppResponse::Redirect(Redirect::to("/"));
}

let token = spotify.read_token_cache().unwrap();
spotify.token = Some(token);
let playlists = spotify.current_user_playlists()
let token = spotify.read_token_cache(false).unwrap();
spotify.token = Arc::new(Mutex::new(token));
let playlists = spotify
.current_user_playlists()
.take(50)
.filter_map(Result::ok)
.collect::<Vec<_>>();
Expand All @@ -189,7 +190,7 @@ fn me(cookies: Cookies) -> AppResponse {
return AppResponse::Redirect(Redirect::to("/"));
}

spotify.token = Some(spotify.read_token_cache().unwrap());
spotify.token = Arc::new(Mutex::new(spotify.read_token_cache(false).unwrap()));
match spotify.me() {
Ok(user_info) => AppResponse::Json(json!(user_info)),
Err(_) => AppResponse::Redirect(Redirect::to("/")),
Expand Down
15 changes: 8 additions & 7 deletions examples/with_auto_reauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@ use rspotify::{
// followed artists, and then unfollow the artists.
async fn auth_code_do_things(spotify: &AuthCodeSpotify) {
let artists = [
&ArtistId::from_id("3RGLhK1IP9jnYFH4BRFJBS").unwrap(), // The Clash
&ArtistId::from_id("0yNLKJebCb8Aueb54LYya3").unwrap(), // New Order
&ArtistId::from_id("2jzc5TC5TVFLXQlBNiIUzE").unwrap(), // a-ha
ArtistId::from_id("3RGLhK1IP9jnYFH4BRFJBS").unwrap(), // The Clash
ArtistId::from_id("0yNLKJebCb8Aueb54LYya3").unwrap(), // New Order
ArtistId::from_id("2jzc5TC5TVFLXQlBNiIUzE").unwrap(), // a-ha
];
let num_artists = artists.len();
spotify
.user_follow_artists(artists)
.user_follow_artists(artists.iter().map(|a| a.as_ref()))
.await
.expect("couldn't follow artists");
println!("Followed {} artists successfully.", artists.len());
println!("Followed {num_artists} artists successfully.");

// Printing the followed artists
let followed = spotify
Expand All @@ -38,13 +39,13 @@ async fn auth_code_do_things(spotify: &AuthCodeSpotify) {
.user_unfollow_artists(artists)
.await
.expect("couldn't unfollow artists");
println!("Unfollowed {} artists successfully.", artists.len());
println!("Unfollowed {num_artists} artists successfully.");
}

async fn client_creds_do_things(spotify: &ClientCredsSpotify) {
// Running the requests
let birdy_uri = AlbumId::from_uri("spotify:album:0sNOF9WDwhWunNAHPD3Baj").unwrap();
let albums = spotify.album(&birdy_uri).await;
let albums = spotify.album(birdy_uri).await;
println!("Get albums: {}", albums.unwrap().id);
}

Expand Down
13 changes: 7 additions & 6 deletions examples/with_refresh_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@ use rspotify::{model::ArtistId, prelude::*, scopes, AuthCodeSpotify, Credentials
// followed artists, and then unfollow the artists.
async fn do_things(spotify: AuthCodeSpotify) {
let artists = [
&ArtistId::from_id("3RGLhK1IP9jnYFH4BRFJBS").unwrap(), // The Clash
&ArtistId::from_id("0yNLKJebCb8Aueb54LYya3").unwrap(), // New Order
&ArtistId::from_id("2jzc5TC5TVFLXQlBNiIUzE").unwrap(), // a-ha
ArtistId::from_id("3RGLhK1IP9jnYFH4BRFJBS").unwrap(), // The Clash
ArtistId::from_id("0yNLKJebCb8Aueb54LYya3").unwrap(), // New Order
ArtistId::from_id("2jzc5TC5TVFLXQlBNiIUzE").unwrap(), // a-ha
];
let num_artists = artists.len();
spotify
.user_follow_artists(artists)
.user_follow_artists(artists.iter().map(|a| a.as_ref()))
.await
.expect("couldn't follow artists");
println!("Followed {} artists successfully.", artists.len());
println!("Followed {num_artists} artists successfully.");

// Printing the followed artists
let followed = spotify
Expand All @@ -45,7 +46,7 @@ async fn do_things(spotify: AuthCodeSpotify) {
.user_unfollow_artists(artists)
.await
.expect("couldn't unfollow artists");
println!("Unfollowed {} artists successfully.", artists.len());
println!("Unfollowed {num_artists} artists successfully.");
}

#[tokio::main]
Expand Down
2 changes: 1 addition & 1 deletion rspotify-model/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ readme = "../README.md"

[dependencies]
chrono = { version = "0.4.19", features = ["serde", "rustc-serialize"] }
enum_dispatch = "0.3.8"
serde = { version = "1.0.130", features = ["derive"] }
serde_json = "1.0.67"
strum = { version = "0.24.0", features = ["derive"] }
thiserror = "1.0.29"

4 changes: 2 additions & 2 deletions rspotify-model/src/album.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub struct SimplifiedAlbum {
pub available_markets: Vec<String>,
pub external_urls: HashMap<String, String>,
pub href: Option<String>,
pub id: Option<AlbumId>,
pub id: Option<AlbumId<'static>>,
pub images: Vec<Image>,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
Expand All @@ -43,7 +43,7 @@ pub struct FullAlbum {
pub external_urls: HashMap<String, String>,
pub genres: Vec<String>,
pub href: String,
pub id: AlbumId,
pub id: AlbumId<'static>,
pub images: Vec<Image>,
pub name: String,
pub popularity: u32,
Expand Down
4 changes: 2 additions & 2 deletions rspotify-model/src/artist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{ArtistId, CursorBasedPage, Followers, Image};
pub struct SimplifiedArtist {
pub external_urls: HashMap<String, String>,
pub href: Option<String>,
pub id: Option<ArtistId>,
pub id: Option<ArtistId<'static>>,
pub name: String,
}

Expand All @@ -22,7 +22,7 @@ pub struct FullArtist {
pub followers: Followers,
pub genres: Vec<String>,
pub href: String,
pub id: ArtistId,
pub id: ArtistId<'static>,
pub images: Vec<Image>,
pub name: String,
pub popularity: u32,
Expand Down
2 changes: 1 addition & 1 deletion rspotify-model/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct AudioFeatures {
#[serde(with = "duration_ms", rename = "duration_ms")]
pub duration: Duration,
pub energy: f32,
pub id: TrackId,
pub id: TrackId<'static>,
pub instrumentalness: f32,
pub key: i32,
pub liveness: f32,
Expand Down
Loading