Add song.link (Odesli) sharing integration
- Create share module with SongLinkClient for Odesli API - Support for tracks via ISRC and albums via UPC - In-memory cache with 1-hour TTL - Commands: share_track_songlink, share_album_songlink - Qobuz URL generators for tracks, albums, artists - Proper error handling for missing identifiers
This commit is contained in:
1 parent
7e2740d297
commit
ff7b598522
7 files changed
+453
No files matched your search
@@ -11,6 +11,7 @@ pub mod playback;
|
||||
pub mod playlist;
|
||||
pub mod queue;
|
||||
pub mod search;
|
||||
pub mod share;
|
||||
|
||||
pub use auth::*;
|
||||
pub use cache::*;
|
||||
@@ -21,3 +22,4 @@ pub use playback::*;
|
||||
pub use playlist::*;
|
||||
pub use queue::*;
|
||||
pub use search::*;
|
||||
pub use share::*;
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Share-related Tauri commands
|
||||
|
||||
use tauri::State;
|
||||
|
||||
use crate::share::{ShareError, SongLinkClient, SongLinkResponse};
|
||||
use crate::AppState;
|
||||
|
||||
/// Get song.link URL for a track
|
||||
/// Requires ISRC to be present in the track metadata
|
||||
#[tauri::command]
|
||||
pub async fn share_track_songlink(
|
||||
isrc: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<SongLinkResponse, String> {
|
||||
let isrc = isrc.ok_or_else(|| {
|
||||
ShareError::MissingIsrc.to_string()
|
||||
})?;
|
||||
|
||||
if isrc.is_empty() {
|
||||
return Err(ShareError::MissingIsrc.to_string());
|
||||
}
|
||||
|
||||
log::info!("Command: share_track_songlink ISRC={}", isrc);
|
||||
|
||||
state
|
||||
.songlink
|
||||
.get_by_isrc(&isrc)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Get song.link URL for an album
|
||||
/// Requires UPC to be present in the album metadata
|
||||
#[tauri::command]
|
||||
pub async fn share_album_songlink(
|
||||
upc: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<SongLinkResponse, String> {
|
||||
let upc = upc.ok_or_else(|| {
|
||||
ShareError::MissingUpc.to_string()
|
||||
})?;
|
||||
|
||||
if upc.is_empty() {
|
||||
return Err(ShareError::MissingUpc.to_string());
|
||||
}
|
||||
|
||||
log::info!("Command: share_album_songlink UPC={}", upc);
|
||||
|
||||
state
|
||||
.songlink
|
||||
.get_by_upc(&upc)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Generate a Qobuz share URL for a track
|
||||
#[tauri::command]
|
||||
pub fn get_qobuz_track_url(track_id: u64) -> String {
|
||||
format!("https://www.qobuz.com/track/{}", track_id)
|
||||
}
|
||||
|
||||
/// Generate a Qobuz share URL for an album
|
||||
#[tauri::command]
|
||||
pub fn get_qobuz_album_url(album_id: String) -> String {
|
||||
format!("https://open.qobuz.com/album/{}", album_id)
|
||||
}
|
||||
|
||||
/// Generate a Qobuz share URL for an artist
|
||||
#[tauri::command]
|
||||
pub fn get_qobuz_artist_url(artist_id: u64) -> String {
|
||||
format!("https://www.qobuz.com/artist/{}", artist_id)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod lastfm;
|
||||
pub mod media_controls;
|
||||
pub mod player;
|
||||
pub mod queue;
|
||||
pub mod share;
|
||||
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
@@ -21,6 +22,7 @@ use lastfm::LastFmClient;
|
||||
use media_controls::{MediaControlsManager, TrackInfo};
|
||||
use player::Player;
|
||||
use queue::QueueManager;
|
||||
use share::SongLinkClient;
|
||||
|
||||
/// Application state shared across commands
|
||||
pub struct AppState {
|
||||
@@ -30,6 +32,7 @@ pub struct AppState {
|
||||
pub media_controls: MediaControlsManager,
|
||||
pub audio_cache: Arc<AudioCache>,
|
||||
pub lastfm: Arc<Mutex<LastFmClient>>,
|
||||
pub songlink: SongLinkClient,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -41,6 +44,7 @@ impl AppState {
|
||||
media_controls: MediaControlsManager::new(),
|
||||
audio_cache: Arc::new(AudioCache::default()),
|
||||
lastfm: Arc::new(Mutex::new(LastFmClient::default())),
|
||||
songlink: SongLinkClient::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,6 +149,12 @@ pub fn run() {
|
||||
commands::lastfm_disconnect,
|
||||
commands::lastfm_scrobble,
|
||||
commands::lastfm_now_playing,
|
||||
// Share commands
|
||||
commands::share_track_songlink,
|
||||
commands::share_album_songlink,
|
||||
commands::get_qobuz_track_url,
|
||||
commands::get_qobuz_album_url,
|
||||
commands::get_qobuz_artist_url,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Error types for the share module
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ShareError {
|
||||
#[error("Missing ISRC for track")]
|
||||
MissingIsrc,
|
||||
|
||||
#[error("Missing UPC for album")]
|
||||
MissingUpc,
|
||||
|
||||
#[error("Network error: {0}")]
|
||||
NetworkError(#[from] reqwest::Error),
|
||||
|
||||
#[error("Odesli API error: {0}")]
|
||||
OdesliError(String),
|
||||
|
||||
#[error("No matches found on Odesli")]
|
||||
NoMatches,
|
||||
|
||||
#[error("Invalid content type: {0}")]
|
||||
InvalidContentType(String),
|
||||
|
||||
#[error("Request timeout")]
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl serde::Serialize for ShareError {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Share module for generating universal song links
|
||||
//!
|
||||
//! This module provides functionality to generate shareable links
|
||||
//! that work across multiple music streaming platforms using Odesli/song.link.
|
||||
|
||||
pub mod errors;
|
||||
pub mod models;
|
||||
pub mod songlink;
|
||||
|
||||
pub use errors::ShareError;
|
||||
pub use models::SongLinkResponse;
|
||||
pub use songlink::SongLinkClient;
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Data models for Odesli/song.link integration
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Response from Odesli API
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OdesliResponse {
|
||||
/// The unique ID for the input entity that was supplied in the request
|
||||
pub entity_unique_id: Option<String>,
|
||||
|
||||
/// The userCountry query param that was supplied in the request
|
||||
pub user_country: Option<String>,
|
||||
|
||||
/// The main song.link page URL
|
||||
pub page_url: String,
|
||||
|
||||
/// A map of platform names to their link info
|
||||
#[serde(default)]
|
||||
pub links_by_platform: HashMap<String, PlatformLink>,
|
||||
|
||||
/// A map of entity unique IDs to entity info
|
||||
#[serde(default)]
|
||||
pub entities_by_unique_id: HashMap<String, Entity>,
|
||||
}
|
||||
|
||||
/// Link info for a specific platform
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlatformLink {
|
||||
/// The country code for this link
|
||||
pub country: Option<String>,
|
||||
|
||||
/// The URL to this entity on the platform
|
||||
pub url: String,
|
||||
|
||||
/// The native app URI
|
||||
pub native_app_uri_mobile: Option<String>,
|
||||
pub native_app_uri_desktop: Option<String>,
|
||||
|
||||
/// The unique ID for this entity
|
||||
pub entity_unique_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Entity info from Odesli
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Entity {
|
||||
/// The unique ID
|
||||
pub id: String,
|
||||
|
||||
/// Type: "song", "album"
|
||||
#[serde(rename = "type")]
|
||||
pub entity_type: Option<String>,
|
||||
|
||||
/// Title
|
||||
pub title: Option<String>,
|
||||
|
||||
/// Artist name
|
||||
pub artist_name: Option<String>,
|
||||
|
||||
/// Thumbnail URL
|
||||
pub thumbnail_url: Option<String>,
|
||||
|
||||
/// Thumbnail dimensions
|
||||
pub thumbnail_width: Option<u32>,
|
||||
pub thumbnail_height: Option<u32>,
|
||||
|
||||
/// API provider
|
||||
pub api_provider: Option<String>,
|
||||
|
||||
/// Platforms this entity is available on
|
||||
pub platforms: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Simplified response for frontend consumption
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SongLinkResponse {
|
||||
/// The main song.link URL to share
|
||||
pub page_url: String,
|
||||
|
||||
/// Title of the content (if available)
|
||||
pub title: Option<String>,
|
||||
|
||||
/// Artist name (if available)
|
||||
pub artist: Option<String>,
|
||||
|
||||
/// Thumbnail URL (if available)
|
||||
pub thumbnail_url: Option<String>,
|
||||
|
||||
/// Map of platform names to their direct URLs
|
||||
pub platforms: HashMap<String, String>,
|
||||
|
||||
/// The identifier used (ISRC or UPC)
|
||||
pub identifier: String,
|
||||
|
||||
/// Type of content: "track" or "album"
|
||||
pub content_type: String,
|
||||
}
|
||||
|
||||
/// Content type for sharing
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ContentType {
|
||||
Track,
|
||||
Album,
|
||||
}
|
||||
|
||||
impl ContentType {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ContentType::Track => "track",
|
||||
ContentType::Album => "album",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Odesli/song.link API client
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use reqwest::Client;
|
||||
|
||||
use super::errors::ShareError;
|
||||
use super::models::{ContentType, OdesliResponse, SongLinkResponse};
|
||||
|
||||
const ODESLI_API_URL: &str = "https://api.song.link/v1-alpha.1/links";
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(3600); // 1 hour
|
||||
|
||||
/// Cached entry with TTL
|
||||
struct CacheEntry {
|
||||
response: SongLinkResponse,
|
||||
created_at: Instant,
|
||||
}
|
||||
|
||||
impl CacheEntry {
|
||||
fn is_expired(&self) -> bool {
|
||||
self.created_at.elapsed() > CACHE_TTL
|
||||
}
|
||||
}
|
||||
|
||||
/// Odesli/song.link client with caching
|
||||
pub struct SongLinkClient {
|
||||
client: Client,
|
||||
cache: Mutex<HashMap<String, CacheEntry>>,
|
||||
}
|
||||
|
||||
impl Default for SongLinkClient {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl SongLinkClient {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
client: Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.build()
|
||||
.unwrap_or_default(),
|
||||
cache: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get song.link URL for a track by ISRC
|
||||
pub async fn get_by_isrc(&self, isrc: &str) -> Result<SongLinkResponse, ShareError> {
|
||||
let cache_key = format!("isrc:{}", isrc);
|
||||
|
||||
// Check cache first
|
||||
if let Some(cached) = self.get_from_cache(&cache_key) {
|
||||
log::debug!("Cache hit for ISRC: {}", isrc);
|
||||
return Ok(cached);
|
||||
}
|
||||
|
||||
log::info!("Fetching song.link for ISRC: {}", isrc);
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.get(ODESLI_API_URL)
|
||||
.query(&[("isrc", isrc), ("userCountry", "US")])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
return Err(ShareError::OdesliError(format!(
|
||||
"HTTP {}: {}",
|
||||
status, text
|
||||
)));
|
||||
}
|
||||
|
||||
let odesli: OdesliResponse = response.json().await?;
|
||||
let result = self.convert_response(odesli, isrc.to_string(), ContentType::Track)?;
|
||||
|
||||
// Cache the result
|
||||
self.store_in_cache(cache_key, result.clone());
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Get song.link URL for an album by UPC
|
||||
pub async fn get_by_upc(&self, upc: &str) -> Result<SongLinkResponse, ShareError> {
|
||||
let cache_key = format!("upc:{}", upc);
|
||||
|
||||
// Check cache first
|
||||
if let Some(cached) = self.get_from_cache(&cache_key) {
|
||||
log::debug!("Cache hit for UPC: {}", upc);
|
||||
return Ok(cached);
|
||||
}
|
||||
|
||||
log::info!("Fetching song.link for UPC: {}", upc);
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.get(ODESLI_API_URL)
|
||||
.query(&[("upc", upc), ("userCountry", "US")])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
return Err(ShareError::OdesliError(format!(
|
||||
"HTTP {}: {}",
|
||||
status, text
|
||||
)));
|
||||
}
|
||||
|
||||
let odesli: OdesliResponse = response.json().await?;
|
||||
let result = self.convert_response(odesli, upc.to_string(), ContentType::Album)?;
|
||||
|
||||
// Cache the result
|
||||
self.store_in_cache(cache_key, result.clone());
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Convert Odesli response to our simplified format
|
||||
fn convert_response(
|
||||
&self,
|
||||
response: OdesliResponse,
|
||||
identifier: String,
|
||||
content_type: ContentType,
|
||||
) -> Result<SongLinkResponse, ShareError> {
|
||||
// Extract title and artist from the first entity
|
||||
let (title, artist, thumbnail_url) = response
|
||||
.entities_by_unique_id
|
||||
.values()
|
||||
.next()
|
||||
.map(|e| {
|
||||
(
|
||||
e.title.clone(),
|
||||
e.artist_name.clone(),
|
||||
e.thumbnail_url.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap_or((None, None, None));
|
||||
|
||||
// Extract platform URLs
|
||||
let platforms: HashMap<String, String> = response
|
||||
.links_by_platform
|
||||
.into_iter()
|
||||
.map(|(platform, link)| (platform, link.url))
|
||||
.collect();
|
||||
|
||||
if platforms.is_empty() {
|
||||
return Err(ShareError::NoMatches);
|
||||
}
|
||||
|
||||
Ok(SongLinkResponse {
|
||||
page_url: response.page_url,
|
||||
title,
|
||||
artist,
|
||||
thumbnail_url,
|
||||
platforms,
|
||||
identifier,
|
||||
content_type: content_type.as_str().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Get from cache if not expired
|
||||
fn get_from_cache(&self, key: &str) -> Option<SongLinkResponse> {
|
||||
let cache = self.cache.lock().ok()?;
|
||||
let entry = cache.get(key)?;
|
||||
|
||||
if entry.is_expired() {
|
||||
None
|
||||
} else {
|
||||
Some(entry.response.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Store in cache
|
||||
fn store_in_cache(&self, key: String, response: SongLinkResponse) {
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
// Clean up expired entries occasionally
|
||||
if cache.len() > 100 {
|
||||
cache.retain(|_, entry| !entry.is_expired());
|
||||
}
|
||||
|
||||
cache.insert(
|
||||
key,
|
||||
CacheEntry {
|
||||
response,
|
||||
created_at: Instant::now(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the cache
|
||||
pub fn clear_cache(&self) {
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user