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

Polish Token and OAuth #185

Merged
merged 28 commits into from
Feb 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
387bf33
Change expires_at from u64 to DateTime
ramsayleung Feb 14, 2021
3bdffd6
Update comment
ramsayleung Feb 14, 2021
2f685c7
Change expire_in from u32 to Duration
ramsayleung Feb 14, 2021
37f133d
Add test to check token.is_expired
ramsayleung Feb 14, 2021
34f4423
Update CHANGELOG.md
ramsayleung Feb 14, 2021
72e7c12
Change scope from string to hashset
ramsayleung Feb 14, 2021
defad50
Use customized module to deserialize/serialize duration
ramsayleung Feb 14, 2021
48b5488
Fix cargo clippy error.
ramsayleung Feb 14, 2021
1b98a3b
Update CHANGELOG
ramsayleung Feb 14, 2021
ed9f341
Fix failed exampls
ramsayleung Feb 14, 2021
1a92869
no need for collect
marioortizmanero Feb 14, 2021
21a5e5e
a bit of spacing
marioortizmanero Feb 14, 2021
9dd6742
neater serialization
marioortizmanero Feb 14, 2021
c37d6f3
fix serialize problem.
ramsayleung Feb 15, 2021
351c54d
Merge branch 'ramsay_optimize_expire_field' of github.com:ramsayleung…
ramsayleung Feb 15, 2021
8a59bdc
Fix clippy lint error.
ramsayleung Feb 15, 2021
4ee8a84
Merge branch 'master' into ramsay_optimize_expire_field
ramsayleung Feb 15, 2021
2b46530
Super neat collects
marioortizmanero Feb 15, 2021
1de59b0
fix test
marioortizmanero Feb 15, 2021
6884af5
Delete util.rs, move generate_random_string to root
ramsayleung Feb 15, 2021
c33c125
Change SimplifiedPlaylist::tracks from HashMap to PlaylistTracksRef
ramsayleung Feb 15, 2021
134ecff
Update CHANGELOG.md
ramsayleung Feb 15, 2021
1c6f610
Optimize webapp example, remove unnecessary from_iter
ramsayleung Feb 15, 2021
758cf84
Add test for function get_authorize_url()
ramsayleung Feb 15, 2021
4013ab8
Fix failed test
ramsayleung Feb 15, 2021
d9487c7
fix cargo fmt error
ramsayleung Feb 15, 2021
5893ed7
Change expires_in to chrono::Duration, optimize doc
ramsayleung Feb 17, 2021
b7eb72c
Update CHANGELOG
ramsayleung Feb 17, 2021
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ If we missed any change or there's something you'd like to discuss about this ve
+ Remove `SimplifiedPlayingContext`, since it's useless.
- ([#177](https://github.com/ramsayleung/rspotify/pull/157)) Change `mode` from `f32` to `enum Modality`:
+ Change `AudioAnalysisSection::mode`, `AudioAnalysisTrack::mode` and `AudioFeatures::mode` from `f32` to `enum Modality`.
- ([#185](https://github.com/ramsayleung/rspotify/pull/185)) Polish the `Token.expires_at`, `Token.expires_in` fields
+ Change `Token.expires_in` from u32 to `chrono::Duration`
+ Change `Token.expires_at` from i64 to `chrono::DateTime<Utc>`
+ Change `Token.scope` from `String` to `HashSet`.
+ Change `OAuth.scope` from `String` to `HashSet`.
+ Change `SimplifiedPlaylist::tracks` from `HashMap` to `PlaylistTracksRef`

## 0.10 (2020/07/01)

Expand Down
9 changes: 5 additions & 4 deletions examples/current_user_recently_played.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use rspotify::client::SpotifyBuilder;
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder};

use std::collections::HashSet;

#[tokio::main]
async fn main() {
// You can use any logger for debugging.
Expand Down Expand Up @@ -29,10 +31,9 @@ async fn main() {
// .redirect_uri("http://localhost:8888/callback")
// .build()
// .unwrap();
let oauth = OAuthBuilder::from_env()
.scope("user-read-recently-played")
.build()
.unwrap();
let mut scopes = HashSet::new();
scopes.insert("user-read-recently-played".to_owned());
let oauth = OAuthBuilder::from_env().scope(scopes).build().unwrap();

let mut spotify = SpotifyBuilder::default()
.credentials(creds)
Expand Down
17 changes: 8 additions & 9 deletions examples/oauth_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ async fn main() {
let creds = CredentialsBuilder::from_env().build().unwrap();

// Using every possible scope
let scope = "user-read-email user-read-private user-top-read \
user-read-recently-played user-follow-read user-library-read \
user-read-currently-playing user-read-playback-state \
user-read-playback-position playlist-read-collaborative \
playlist-read-private user-follow-modify user-library-modify \
user-modify-playback-state playlist-modify-public \
playlist-modify-private ugc-image-upload";
let oauth = OAuthBuilder::from_env()
.scope(
"user-read-email user-read-private user-top-read \
user-read-recently-played user-follow-read user-library-read \
user-read-currently-playing user-read-playback-state \
user-read-playback-position playlist-read-collaborative \
playlist-read-private user-follow-modify user-library-modify \
user-modify-playback-state playlist-modify-public \
playlist-modify-private ugc-image-upload",
)
.scope(scope.split_whitespace().map(|x| x.to_owned()).collect())
.build()
.unwrap();

Expand Down
9 changes: 5 additions & 4 deletions examples/ureq/device.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use rspotify::client::SpotifyBuilder;
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder};

use std::collections::HashSet;

fn main() {
// You can use any logger for debugging.
env_logger::init();
Expand Down Expand Up @@ -28,10 +30,9 @@ fn main() {
// .redirect_uri("http://localhost:8888/callback")
// .build()
// .unwrap();
let oauth = OAuthBuilder::from_env()
.scope("user-read-playback-state")
.build()
.unwrap();
let mut scope = HashSet::new();
scope.insert("user-read-playback-state".to_owned());
let oauth = OAuthBuilder::from_env().scope(scope).build().unwrap();

let mut spotify = SpotifyBuilder::default()
.credentials(creds)
Expand Down
9 changes: 5 additions & 4 deletions examples/ureq/me.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use rspotify::client::SpotifyBuilder;
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder};

use std::collections::HashSet;

fn main() {
// You can use any logger for debugging.
env_logger::init();
Expand Down Expand Up @@ -28,10 +30,9 @@ fn main() {
// .redirect_uri("http://localhost:8888/callback")
// .build()
// .unwrap();
let oauth = OAuthBuilder::from_env()
.scope("user-read-playback-state")
.build()
.unwrap();
let mut scope = HashSet::new();
scope.insert("user-read-playback-state".to_owned());
let oauth = OAuthBuilder::from_env().scope(scope).build().unwrap();

let mut spotify = SpotifyBuilder::default()
.credentials(creds)
Expand Down
17 changes: 9 additions & 8 deletions examples/ureq/search.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use rspotify::client::SpotifyBuilder;
use rspotify::model::{Country, SearchType};
use rspotify::model::{Country, Market, SearchType};
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder};

use std::collections::HashSet;

fn main() {
// You can use any logger for debugging.
env_logger::init();
Expand Down Expand Up @@ -29,10 +31,9 @@ fn main() {
// .redirect_uri("http://localhost:8888/callback")
// .build()
// .unwrap();
let oauth = OAuthBuilder::from_env()
.scope("user-read-playback-state")
.build()
.unwrap();
let mut scope = HashSet::new();
scope.insert("user-read-playback-state".to_owned());
let oauth = OAuthBuilder::from_env().scope(scope).build().unwrap();

let mut spotify = SpotifyBuilder::default()
.credentials(creds)
Expand All @@ -56,7 +57,7 @@ fn main() {
SearchType::Artist,
10,
0,
Some(Country::UnitedStates),
Some(Market::Country(Country::UnitedStates)),
None,
);
match result {
Expand All @@ -70,7 +71,7 @@ fn main() {
SearchType::Playlist,
10,
0,
Some(Country::UnitedStates),
Some(Market::Country(Country::UnitedStates)),
None,
);
match result {
Expand All @@ -84,7 +85,7 @@ fn main() {
SearchType::Track,
10,
0,
Some(Country::UnitedStates),
Some(Market::Country(Country::UnitedStates)),
None,
);
match result {
Expand Down
9 changes: 5 additions & 4 deletions examples/ureq/seek_track.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use rspotify::client::SpotifyBuilder;
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder};

use std::collections::HashSet;

fn main() {
// You can use any logger for debugging.
env_logger::init();
Expand Down Expand Up @@ -28,10 +30,9 @@ fn main() {
// .redirect_uri("http://localhost:8888/callback")
// .build()
// .unwrap();
let oauth = OAuthBuilder::from_env()
.scope("user-read-playback-state")
.build()
.unwrap();
let mut scope = HashSet::new();
scope.insert("user-read-playback-state".to_owned());
let oauth = OAuthBuilder::from_env().scope(scope).build().unwrap();

let mut spotify = SpotifyBuilder::default()
.credentials(creds)
Expand Down
13 changes: 8 additions & 5 deletions examples/webapp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ use rocket_contrib::templates::Template;
use rspotify::client::{ClientError, SpotifyBuilder};
use rspotify::oauth2::{CredentialsBuilder, OAuthBuilder, TokenBuilder};

use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::{
collections::{HashMap, HashSet},
env,
path::PathBuf,
};

#[derive(Debug, Responder)]
pub enum AppResponse {
Expand Down Expand Up @@ -51,7 +53,7 @@ fn create_cache_path_if_absent(cookies: &Cookies) -> PathBuf {
path.pop();
fs::create_dir_all(path).unwrap();
}
cache_path.clone()
cache_path
}

fn remove_cache_path(mut cookies: Cookies) {
Expand All @@ -73,9 +75,10 @@ fn check_cache_path_exists(cookies: &Cookies) -> (bool, PathBuf) {
fn init_spotify() -> SpotifyBuilder {
// Please notice that protocol of redirect_uri, make sure it's http
// (or https). It will fail if you mix them up.
let scope = "user-read-currently-playing playlist-modify-private";
let oauth = OAuthBuilder::default()
.redirect_uri("http://localhost:8000/callback")
.scope("user-read-currently-playing playlist-modify-private")
.scope(scope.split_whitespace().map(|x| x.to_owned()).collect())
.build()
.unwrap();

Expand Down
3 changes: 2 additions & 1 deletion examples/with_refresh_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@ async fn main() {

// The default credentials from the `.env` file will be used by default.
let creds = CredentialsBuilder::from_env().build().unwrap();
let scope = "user-follow-read user-follow-modify";
let oauth = OAuthBuilder::from_env()
.scope("user-follow-read user-follow-modify")
.scope(scope.split_whitespace().map(|x| x.to_owned()).collect())
.build()
.unwrap();
let mut spotify = SpotifyBuilder::default()
Expand Down
17 changes: 15 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@
//! ](https://github.com/ramsayleung/rspotify/tree/master/examples)
//! which can serve as a learning tool.

use getrandom::getrandom;

// disable all modules when both client features are enabled,
// this way only the compile error below gets show
// instead of showing a whole list of confusing errors
Expand All @@ -164,8 +166,6 @@ mod http;
pub mod model;
#[cfg(not(all(feature = "client-reqwest", feature = "client-ureq")))]
pub mod oauth2;
#[cfg(not(all(feature = "client-reqwest", feature = "client-ureq")))]
pub mod util;

#[cfg(all(feature = "client-reqwest", feature = "client-ureq"))]
compile_error!(
Expand All @@ -186,3 +186,16 @@ mod macros {
};
}
}

/// Generate `length` random chars
pub(in crate) fn generate_random_string(length: usize) -> String {
let alphanum: &[u8] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".as_bytes();
let mut buf = vec![0u8; length];
getrandom(&mut buf).unwrap();
let range = alphanum.len();

buf.iter()
.map(|byte| alphanum[*byte as usize % range] as char)
.collect()
}
12 changes: 10 additions & 2 deletions src/model/playlist.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! All kinds of playlists objects
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use super::image::Image;
Expand All @@ -18,6 +17,15 @@ pub struct PlaylistResult {
pub snapshot_id: String,
}

/// Playlist Track Reference Object
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#object-playlisttracksrefobject)
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlaylistTracksRef {
pub href: String,
pub total: u32,
}

/// Simplified playlist object
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#object-simplifiedplaylistobject)
Expand All @@ -32,7 +40,7 @@ pub struct SimplifiedPlaylist {
pub owner: PublicUser,
pub public: Option<bool>,
pub snapshot_id: String,
pub tracks: HashMap<String, Value>,
pub tracks: PlaylistTracksRef,
#[serde(rename = "type")]
pub _type: Type,
pub uri: String,
Expand Down
Loading