use itertools::Itertools;
use url::Url;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Scope {
UgcImageUpload,
UserReadPlaybackState,
UserModifyPlaybackState,
UserReadCurrentlyPlaying,
Streaming,
AppRemoteControl,
UserReadEmail,
UserReadPrivate,
PlaylistReadCollaborative,
PlaylistModifyPublic,
PlaylistReadPrivate,
PlaylistModifyPrivate,
UserLibraryModify,
UserLibraryRead,
UserTopRead,
UserReadRecentlyPlayed,
UserReadPlaybackPosition,
UserFollowRead,
UserFollowModify,
}
impl Scope {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::UgcImageUpload => "ugc-image-upload",
Self::UserReadPlaybackState => "user-read-playback-state",
Self::UserModifyPlaybackState => "user-modify-playback-state",
Self::UserReadCurrentlyPlaying => "user-read-currently-playing",
Self::Streaming => "streaming",
Self::AppRemoteControl => "app-remote-control",
Self::UserReadEmail => "user-read-email",
Self::UserReadPrivate => "user-read-private",
Self::PlaylistReadCollaborative => "playlist-read-collaborative",
Self::PlaylistModifyPublic => "playlist-modify-public",
Self::PlaylistReadPrivate => "playlist-read-private",
Self::PlaylistModifyPrivate => "playlist-modify-private",
Self::UserLibraryModify => "user-library-modify",
Self::UserLibraryRead => "user-library-read",
Self::UserTopRead => "user-top-read",
Self::UserReadRecentlyPlayed => "user-read-recently-played",
Self::UserReadPlaybackPosition => "user-read-playback-position",
Self::UserFollowRead => "user-follow-read",
Self::UserFollowModify => "user-follow-modify",
}
}
}
pub fn authorization_url_with_state(
client_id: &str,
scopes: impl IntoIterator<Item = Scope>,
force_approve: bool,
redirect_uri: &str,
state: &str,
) -> String {
Url::parse_with_params(
"https://accounts.spotify.com/authorize",
&[
("response_type", "code"),
("state", &state),
("client_id", client_id),
("scope", &scopes.into_iter().map(Scope::as_str).join(" ")),
("show_dialog", if force_approve { "true" } else { "false" }),
("redirect_uri", redirect_uri),
],
)
.unwrap()
.into_string()
}
#[cfg(feature = "rand")]
pub fn authorization_url(
client_id: &str,
scopes: impl IntoIterator<Item = Scope>,
force_approve: bool,
redirect_uri: &str,
) -> (String, String) {
use rand::Rng as _;
const STATE_LEN: usize = 16;
const STATE_CHARS: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
let mut rng = rand::thread_rng();
let mut state = String::with_capacity(STATE_LEN);
for _ in 0..STATE_LEN {
state.push(STATE_CHARS[rng.gen_range(0..STATE_CHARS.len())].into());
}
(
authorization_url_with_state(client_id, scopes, force_approve, redirect_uri, &state),
state,
)
}