spotify_dl/
session.rs

1use anyhow::Result;
2use librespot::core::cache::Cache;
3use librespot::core::config::SessionConfig;
4use librespot::core::session::Session;
5use librespot::discovery::Credentials;
6use librespot::oauth::get_access_token;
7
8const SPOTIFY_CLIENT_ID: &str = "65b708073fc0480ea92a077233ca87bd";
9const SPOTIFY_REDIRECT_URI: &str = "http://127.0.0.1:8898/login";
10
11pub async fn create_session() -> Result<Session> {
12    let credentials_store = dirs::home_dir().map(|p| p.join(".spotify-dl"));
13    let cache = Cache::new(credentials_store, None, None, None)?;
14
15    let session_config = SessionConfig::default();
16
17    let credentials = match cache.credentials() {
18        Some(creds) => creds,
19        None => match load_credentials() {
20            Ok(creds) => creds,
21            Err(e) => return Err(e),
22        },
23    };
24
25    cache.save_credentials(&credentials);
26
27    let session = Session::new(session_config, Some(cache));
28    session.connect(credentials, true).await?;
29    Ok(session)
30}
31
32pub fn load_credentials() -> Result<Credentials> {
33    let token = match get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_REDIRECT_URI, vec!["streaming"]) {
34        Ok(token) => token,
35        Err(e) => return Err(e.into()),
36    };
37    Ok(Credentials::with_access_token(token.access_token))
38}