Add language setting and Last.fm integration
Settings: - Add language dropdown (Auto, English, Español, etc.) with persistence Last.fm: - Create lastfm module with API client for authentication and scrobbling - Add commands for auth flow, now playing, and scrobbling - Full OAuth-style authentication with token exchange - UI for entering API credentials and authorizing - Automatic scrobbling after 50% of track or 4 minutes - Update 'now playing' when tracks start - Session persistence in localStorage
This commit is contained in:
1 parent
9d040fee55
commit
c7145e889b
6 files changed
+838
-13
No files matched your search
@@ -0,0 +1,112 @@
|
||||
//! Last.fm integration commands
|
||||
|
||||
use tauri::State;
|
||||
|
||||
use crate::lastfm::LastFmSession;
|
||||
use crate::AppState;
|
||||
|
||||
/// Check if Last.fm has API credentials configured
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_has_credentials(state: State<'_, AppState>) -> Result<bool, String> {
|
||||
let client = state.lastfm.lock().await;
|
||||
Ok(client.has_credentials())
|
||||
}
|
||||
|
||||
/// Set Last.fm API credentials
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_set_credentials(
|
||||
api_key: String,
|
||||
api_secret: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: lastfm_set_credentials");
|
||||
let mut client = state.lastfm.lock().await;
|
||||
client.set_credentials(api_key, api_secret);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if Last.fm is authenticated
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_is_authenticated(state: State<'_, AppState>) -> Result<bool, String> {
|
||||
let client = state.lastfm.lock().await;
|
||||
Ok(client.is_authenticated())
|
||||
}
|
||||
|
||||
/// Get Last.fm authentication token and URL
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_get_auth_url(state: State<'_, AppState>) -> Result<(String, String), String> {
|
||||
log::info!("Command: lastfm_get_auth_url");
|
||||
let client = state.lastfm.lock().await;
|
||||
|
||||
if !client.has_credentials() {
|
||||
return Err("Last.fm API credentials not configured. Please set API key and secret in settings.".to_string());
|
||||
}
|
||||
|
||||
let token = client.get_token().await?;
|
||||
let url = client.get_auth_url(&token);
|
||||
Ok((token, url))
|
||||
}
|
||||
|
||||
/// Complete Last.fm authentication with token
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_authenticate(
|
||||
token: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<LastFmSession, String> {
|
||||
log::info!("Command: lastfm_authenticate");
|
||||
let mut client = state.lastfm.lock().await;
|
||||
client.get_session(&token).await
|
||||
}
|
||||
|
||||
/// Set Last.fm session key (for restoring saved session)
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_set_session(
|
||||
session_key: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: lastfm_set_session");
|
||||
let mut client = state.lastfm.lock().await;
|
||||
client.set_session_key(session_key);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Disconnect from Last.fm
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_disconnect(state: State<'_, AppState>) -> Result<(), String> {
|
||||
log::info!("Command: lastfm_disconnect");
|
||||
let mut client = state.lastfm.lock().await;
|
||||
// Reset to default (clears session key)
|
||||
*client = crate::lastfm::LastFmClient::default();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scrobble a track to Last.fm
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_scrobble(
|
||||
artist: String,
|
||||
track: String,
|
||||
album: Option<String>,
|
||||
timestamp: u64,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: lastfm_scrobble - {} - {}", artist, track);
|
||||
let client = state.lastfm.lock().await;
|
||||
client
|
||||
.scrobble(&artist, &track, album.as_deref(), timestamp)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Update "now playing" on Last.fm
|
||||
#[tauri::command]
|
||||
pub async fn lastfm_now_playing(
|
||||
artist: String,
|
||||
track: String,
|
||||
album: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: lastfm_now_playing - {} - {}", artist, track);
|
||||
let client = state.lastfm.lock().await;
|
||||
client
|
||||
.update_now_playing(&artist, &track, album.as_deref())
|
||||
.await
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
pub mod auth;
|
||||
pub mod cache;
|
||||
pub mod favorites;
|
||||
pub mod lastfm;
|
||||
pub mod notification;
|
||||
pub mod playback;
|
||||
pub mod playlist;
|
||||
@@ -14,6 +15,7 @@ pub mod search;
|
||||
pub use auth::*;
|
||||
pub use cache::*;
|
||||
pub use favorites::*;
|
||||
pub use lastfm::*;
|
||||
pub use notification::*;
|
||||
pub use playback::*;
|
||||
pub use playlist::*;
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//! Last.fm integration module
|
||||
//!
|
||||
//! Handles Last.fm authentication and scrobbling
|
||||
|
||||
use md5::{Digest, Md5};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const LASTFM_API_URL: &str = "https://ws.audioscrobbler.com/2.0/";
|
||||
|
||||
// Last.fm API credentials - users need to create their own app at https://www.last.fm/api/account/create
|
||||
// For now using placeholder - in production this should be configurable or use OAuth
|
||||
const API_KEY: &str = ""; // User must set this
|
||||
const API_SECRET: &str = ""; // User must set this
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LastFmSession {
|
||||
pub name: String,
|
||||
pub key: String,
|
||||
pub subscriber: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AuthGetSessionResponse {
|
||||
session: LastFmSession,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AuthGetTokenResponse {
|
||||
token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum LastFmResponse<T> {
|
||||
Success(T),
|
||||
Error { error: u32, message: String },
|
||||
}
|
||||
|
||||
/// Last.fm API client
|
||||
pub struct LastFmClient {
|
||||
client: Client,
|
||||
api_key: String,
|
||||
api_secret: String,
|
||||
session_key: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for LastFmClient {
|
||||
fn default() -> Self {
|
||||
Self::new(API_KEY.to_string(), API_SECRET.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl LastFmClient {
|
||||
pub fn new(api_key: String, api_secret: String) -> Self {
|
||||
Self {
|
||||
client: Client::new(),
|
||||
api_key,
|
||||
api_secret,
|
||||
session_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_session_key(&mut self, key: String) {
|
||||
self.session_key = Some(key);
|
||||
}
|
||||
|
||||
pub fn is_authenticated(&self) -> bool {
|
||||
self.session_key.is_some() && !self.api_key.is_empty()
|
||||
}
|
||||
|
||||
pub fn has_credentials(&self) -> bool {
|
||||
!self.api_key.is_empty() && !self.api_secret.is_empty()
|
||||
}
|
||||
|
||||
pub fn set_credentials(&mut self, api_key: String, api_secret: String) {
|
||||
self.api_key = api_key;
|
||||
self.api_secret = api_secret;
|
||||
}
|
||||
|
||||
/// Generate API signature for authenticated requests
|
||||
fn generate_signature(&self, params: &BTreeMap<&str, &str>) -> String {
|
||||
let mut sig_string = String::new();
|
||||
for (key, value) in params {
|
||||
sig_string.push_str(key);
|
||||
sig_string.push_str(value);
|
||||
}
|
||||
sig_string.push_str(&self.api_secret);
|
||||
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(sig_string.as_bytes());
|
||||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
/// Get authorization URL for user to visit
|
||||
pub fn get_auth_url(&self, token: &str) -> String {
|
||||
format!(
|
||||
"https://www.last.fm/api/auth/?api_key={}&token={}",
|
||||
self.api_key, token
|
||||
)
|
||||
}
|
||||
|
||||
/// Get a request token for authentication
|
||||
pub async fn get_token(&self) -> Result<String, String> {
|
||||
if !self.has_credentials() {
|
||||
return Err("Last.fm API credentials not configured".to_string());
|
||||
}
|
||||
|
||||
let mut params = BTreeMap::new();
|
||||
params.insert("method", "auth.getToken");
|
||||
params.insert("api_key", &self.api_key);
|
||||
|
||||
let sig = self.generate_signature(¶ms);
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.get(LASTFM_API_URL)
|
||||
.query(&[
|
||||
("method", "auth.getToken"),
|
||||
("api_key", &self.api_key),
|
||||
("api_sig", &sig),
|
||||
("format", "json"),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to get token: {}", e))?;
|
||||
|
||||
let data: LastFmResponse<AuthGetTokenResponse> = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse response: {}", e))?;
|
||||
|
||||
match data {
|
||||
LastFmResponse::Success(r) => Ok(r.token),
|
||||
LastFmResponse::Error { message, .. } => Err(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get session key after user has authorized
|
||||
pub async fn get_session(&mut self, token: &str) -> Result<LastFmSession, String> {
|
||||
if !self.has_credentials() {
|
||||
return Err("Last.fm API credentials not configured".to_string());
|
||||
}
|
||||
|
||||
let mut params = BTreeMap::new();
|
||||
params.insert("method", "auth.getSession");
|
||||
params.insert("api_key", &self.api_key);
|
||||
params.insert("token", token);
|
||||
|
||||
let sig = self.generate_signature(¶ms);
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.get(LASTFM_API_URL)
|
||||
.query(&[
|
||||
("method", "auth.getSession"),
|
||||
("api_key", &self.api_key),
|
||||
("token", token),
|
||||
("api_sig", &sig),
|
||||
("format", "json"),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to get session: {}", e))?;
|
||||
|
||||
let data: LastFmResponse<AuthGetSessionResponse> = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse response: {}", e))?;
|
||||
|
||||
match data {
|
||||
LastFmResponse::Success(r) => {
|
||||
self.session_key = Some(r.session.key.clone());
|
||||
Ok(r.session)
|
||||
}
|
||||
LastFmResponse::Error { message, .. } => Err(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrobble a track (mark as played)
|
||||
pub async fn scrobble(
|
||||
&self,
|
||||
artist: &str,
|
||||
track: &str,
|
||||
album: Option<&str>,
|
||||
timestamp: u64,
|
||||
) -> Result<(), String> {
|
||||
let session_key = self
|
||||
.session_key
|
||||
.as_ref()
|
||||
.ok_or("Not authenticated with Last.fm")?;
|
||||
|
||||
let timestamp_str = timestamp.to_string();
|
||||
let api_key = &self.api_key;
|
||||
|
||||
let mut params = BTreeMap::new();
|
||||
params.insert("method", "track.scrobble");
|
||||
params.insert("api_key", api_key.as_str());
|
||||
params.insert("sk", session_key.as_str());
|
||||
params.insert("artist", artist);
|
||||
params.insert("track", track);
|
||||
params.insert("timestamp", ×tamp_str);
|
||||
if let Some(album_name) = album {
|
||||
params.insert("album", album_name);
|
||||
}
|
||||
|
||||
let sig = self.generate_signature(¶ms);
|
||||
|
||||
let mut form_params = vec![
|
||||
("method", "track.scrobble"),
|
||||
("api_key", api_key.as_str()),
|
||||
("sk", session_key.as_str()),
|
||||
("artist", artist),
|
||||
("track", track),
|
||||
("timestamp", ×tamp_str),
|
||||
("api_sig", &sig),
|
||||
("format", "json"),
|
||||
];
|
||||
if let Some(album_name) = album {
|
||||
form_params.push(("album", album_name));
|
||||
}
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.post(LASTFM_API_URL)
|
||||
.form(&form_params)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to scrobble: {}", e))?;
|
||||
|
||||
if response.status().is_success() {
|
||||
log::info!("Scrobbled: {} - {}", artist, track);
|
||||
Ok(())
|
||||
} else {
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
Err(format!("Scrobble failed: {}", text))
|
||||
}
|
||||
}
|
||||
|
||||
/// Update "now playing" status
|
||||
pub async fn update_now_playing(
|
||||
&self,
|
||||
artist: &str,
|
||||
track: &str,
|
||||
album: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let session_key = self
|
||||
.session_key
|
||||
.as_ref()
|
||||
.ok_or("Not authenticated with Last.fm")?;
|
||||
|
||||
let api_key = &self.api_key;
|
||||
|
||||
let mut params = BTreeMap::new();
|
||||
params.insert("method", "track.updateNowPlaying");
|
||||
params.insert("api_key", api_key.as_str());
|
||||
params.insert("sk", session_key.as_str());
|
||||
params.insert("artist", artist);
|
||||
params.insert("track", track);
|
||||
if let Some(album_name) = album {
|
||||
params.insert("album", album_name);
|
||||
}
|
||||
|
||||
let sig = self.generate_signature(¶ms);
|
||||
|
||||
let mut form_params = vec![
|
||||
("method", "track.updateNowPlaying"),
|
||||
("api_key", api_key.as_str()),
|
||||
("sk", session_key.as_str()),
|
||||
("artist", artist),
|
||||
("track", track),
|
||||
("api_sig", &sig),
|
||||
("format", "json"),
|
||||
];
|
||||
if let Some(album_name) = album {
|
||||
form_params.push(("album", album_name));
|
||||
}
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.post(LASTFM_API_URL)
|
||||
.form(&form_params)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to update now playing: {}", e))?;
|
||||
|
||||
if response.status().is_success() {
|
||||
log::debug!("Updated now playing: {} - {}", artist, track);
|
||||
Ok(())
|
||||
} else {
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
Err(format!("Update now playing failed: {}", text))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ pub mod api;
|
||||
pub mod cache;
|
||||
pub mod commands;
|
||||
pub mod config;
|
||||
pub mod lastfm;
|
||||
pub mod media_controls;
|
||||
pub mod player;
|
||||
pub mod queue;
|
||||
@@ -16,6 +17,7 @@ use tokio::sync::Mutex;
|
||||
|
||||
use api::QobuzClient;
|
||||
use cache::AudioCache;
|
||||
use lastfm::LastFmClient;
|
||||
use media_controls::{MediaControlsManager, TrackInfo};
|
||||
use player::Player;
|
||||
use queue::QueueManager;
|
||||
@@ -27,6 +29,7 @@ pub struct AppState {
|
||||
pub queue: QueueManager,
|
||||
pub media_controls: MediaControlsManager,
|
||||
pub audio_cache: Arc<AudioCache>,
|
||||
pub lastfm: Arc<Mutex<LastFmClient>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -37,6 +40,7 @@ impl AppState {
|
||||
queue: QueueManager::new(),
|
||||
media_controls: MediaControlsManager::new(),
|
||||
audio_cache: Arc::new(AudioCache::default()),
|
||||
lastfm: Arc::new(Mutex::new(LastFmClient::default())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +135,16 @@ pub fn run() {
|
||||
// Cache commands
|
||||
commands::get_cache_stats,
|
||||
commands::clear_cache,
|
||||
// Last.fm commands
|
||||
commands::lastfm_has_credentials,
|
||||
commands::lastfm_set_credentials,
|
||||
commands::lastfm_is_authenticated,
|
||||
commands::lastfm_get_auth_url,
|
||||
commands::lastfm_authenticate,
|
||||
commands::lastfm_set_session,
|
||||
commands::lastfm_disconnect,
|
||||
commands::lastfm_scrobble,
|
||||
commands::lastfm_now_playing,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
|
||||
Reference in new issue
Block a user