Skip to content

Commit

Permalink
Implement timeout mechanism for getting authentication token
Browse files Browse the repository at this point in the history
  • Loading branch information
aome510 committed Jun 25, 2023
1 parent 230aa60 commit 01376ea
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions spotify_player/src/token.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashSet;

use anyhow::{anyhow, Result};
use anyhow::Result;
use chrono::{Duration, Utc};
use librespot_core::{keymaster, session::Session};
use rspotify::Token;
Expand All @@ -24,13 +24,20 @@ const SCOPES: [&str; 15] = [
"user-library-modify",
];

const TIMEOUT_IN_SECS: u64 = 5;

/// gets an authentication token with pre-defined permission scopes
pub async fn get_token(session: &Session, client_id: &str) -> Result<Token> {
tracing::info!("Getting new authentication token...");

let token = keymaster::get_token(session, client_id, &SCOPES.join(","))
.await
.map_err(|err| anyhow!(format!("failed to get token: {err:#?}")))?;
let scopes = SCOPES.join(",");
let fut = keymaster::get_token(session, client_id, &scopes);
let token =
match tokio::time::timeout(std::time::Duration::from_secs(TIMEOUT_IN_SECS), fut).await {
Ok(Ok(token)) => token,
Ok(Err(err)) => anyhow::bail!("failed to get the token: {:?}", err),
Err(_) => anyhow::bail!("timeout when getting the token"),
};

// converts the token returned by librespot `get_token` function to a `rspotify::Token`

Expand Down

0 comments on commit 01376ea

Please sign in to comment.