Compare commits
1 Commits
f6b363c40f
...
51bcf26482
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51bcf26482 |
@@ -98,6 +98,11 @@ pub async fn delete_user(id: i32) -> Result<(), ApiError> {
|
||||
delete(&format!("{BASE}/auth/users/{id}")).await
|
||||
}
|
||||
|
||||
// --- Lyrics ---
|
||||
pub async fn get_lyrics(artist: &str, title: &str) -> Result<LyricsResult, ApiError> {
|
||||
get_json(&format!("{BASE}/lyrics?artist={artist}&title={title}")).await
|
||||
}
|
||||
|
||||
// --- Status ---
|
||||
pub async fn get_status() -> Result<Status, ApiError> {
|
||||
get_json(&format!("{BASE}/status")).await
|
||||
@@ -108,7 +113,11 @@ pub async fn search_artist(query: &str, limit: u32) -> Result<Vec<ArtistResult>,
|
||||
get_json(&format!("{BASE}/search/artist?q={query}&limit={limit}")).await
|
||||
}
|
||||
|
||||
pub async fn search_album(query: &str, artist: Option<&str>, limit: u32) -> Result<Vec<AlbumResult>, ApiError> {
|
||||
pub async fn search_album(
|
||||
query: &str,
|
||||
artist: Option<&str>,
|
||||
limit: u32,
|
||||
) -> Result<Vec<AlbumResult>, ApiError> {
|
||||
let mut url = format!("{BASE}/search/album?q={query}&limit={limit}");
|
||||
if let Some(a) = artist {
|
||||
url.push_str(&format!("&artist={a}"));
|
||||
@@ -116,7 +125,11 @@ pub async fn search_album(query: &str, artist: Option<&str>, limit: u32) -> Resu
|
||||
get_json(&url).await
|
||||
}
|
||||
|
||||
pub async fn search_track(query: &str, artist: Option<&str>, limit: u32) -> Result<Vec<TrackResult>, ApiError> {
|
||||
pub async fn search_track(
|
||||
query: &str,
|
||||
artist: Option<&str>,
|
||||
limit: u32,
|
||||
) -> Result<Vec<TrackResult>, ApiError> {
|
||||
let mut url = format!("{BASE}/search/track?q={query}&limit={limit}");
|
||||
if let Some(a) = artist {
|
||||
url.push_str(&format!("&artist={a}"));
|
||||
@@ -158,7 +171,11 @@ pub async fn add_artist(name: &str, mbid: Option<&str>) -> Result<AddSummary, Ap
|
||||
post_json(&format!("{BASE}/artists"), &body).await
|
||||
}
|
||||
|
||||
pub async fn add_album(artist: &str, album: &str, mbid: Option<&str>) -> Result<AddSummary, ApiError> {
|
||||
pub async fn add_album(
|
||||
artist: &str,
|
||||
album: &str,
|
||||
mbid: Option<&str>,
|
||||
) -> Result<AddSummary, ApiError> {
|
||||
let body = match mbid {
|
||||
Some(m) => format!(r#"{{"artist":"{artist}","album":"{album}","mbid":"{m}"}}"#),
|
||||
None => format!(r#"{{"artist":"{artist}","album":"{album}"}}"#),
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
use yew::prelude::*;
|
||||
|
||||
use crate::api;
|
||||
use crate::components::status_badge::StatusBadge;
|
||||
use crate::types::MbAlbumDetail;
|
||||
use crate::types::{LyricsResult, MbAlbumDetail};
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct Props {
|
||||
@@ -14,6 +15,8 @@ pub fn album_page(props: &Props) -> Html {
|
||||
let detail = use_state(|| None::<MbAlbumDetail>);
|
||||
let error = use_state(|| None::<String>);
|
||||
let mbid = props.mbid.clone();
|
||||
let lyrics_cache: UseStateHandle<HashMap<String, LyricsResult>> = use_state(HashMap::new);
|
||||
let active_lyrics = use_state(|| None::<String>);
|
||||
|
||||
{
|
||||
let detail = detail.clone();
|
||||
@@ -37,7 +40,6 @@ pub fn album_page(props: &Props) -> Html {
|
||||
return html! { <p class="loading">{ "Loading album from MusicBrainz..." }</p> };
|
||||
};
|
||||
|
||||
// Format duration from ms
|
||||
let fmt_duration = |ms: u64| -> String {
|
||||
let secs = ms / 1000;
|
||||
let mins = secs / 60;
|
||||
@@ -45,11 +47,22 @@ pub fn album_page(props: &Props) -> Html {
|
||||
format!("{mins}:{remaining:02}")
|
||||
};
|
||||
|
||||
let cover_url = format!("https://coverartarchive.org/release/{}/front-250", d.mbid);
|
||||
|
||||
html! {
|
||||
<div>
|
||||
<div class="page-header">
|
||||
<h2>{ format!("Album") }</h2>
|
||||
<p class="text-muted text-sm">{ format!("MBID: {}", d.mbid) }</p>
|
||||
<div class="album-header">
|
||||
<img class="album-art-lg" src={cover_url}
|
||||
loading="lazy"
|
||||
onerror={Callback::from(|e: web_sys::Event| {
|
||||
if let Some(el) = e.target_dyn_into::<web_sys::HtmlElement>() {
|
||||
el.set_attribute("style", "display:none").ok();
|
||||
}
|
||||
})} />
|
||||
<div>
|
||||
<h2>{ "Album" }</h2>
|
||||
<p class="text-muted text-sm">{ format!("MBID: {}", d.mbid) }</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="mb-1">{ format!("Tracks ({})", d.tracks.len()) }</h3>
|
||||
@@ -63,6 +76,7 @@ pub fn album_page(props: &Props) -> Html {
|
||||
<th>{ "Title" }</th>
|
||||
<th>{ "Duration" }</th>
|
||||
<th>{ "Status" }</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -71,7 +85,40 @@ pub fn album_page(props: &Props) -> Html {
|
||||
.map(|ms| fmt_duration(ms))
|
||||
.unwrap_or_default();
|
||||
|
||||
let track_key = t.recording_mbid.clone();
|
||||
let is_active = active_lyrics.as_ref() == Some(&track_key);
|
||||
let cached = lyrics_cache.get(&track_key).cloned();
|
||||
|
||||
let on_lyrics_click = {
|
||||
let active = active_lyrics.clone();
|
||||
let cache = lyrics_cache.clone();
|
||||
let title = t.title.clone();
|
||||
let key = track_key.clone();
|
||||
Callback::from(move |_: MouseEvent| {
|
||||
let active = active.clone();
|
||||
let cache = cache.clone();
|
||||
let title = title.clone();
|
||||
let key = key.clone();
|
||||
if active.as_ref() == Some(&key) {
|
||||
active.set(None);
|
||||
return;
|
||||
}
|
||||
active.set(Some(key.clone()));
|
||||
if cache.contains_key(&key) {
|
||||
return;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
if let Ok(result) = api::get_lyrics("", &title).await {
|
||||
let mut map = (*cache).clone();
|
||||
map.insert(key, result);
|
||||
cache.set(map);
|
||||
}
|
||||
});
|
||||
})
|
||||
};
|
||||
|
||||
html! {
|
||||
<>
|
||||
<tr>
|
||||
<td>{ t.track_number.map(|n| n.to_string()).unwrap_or_default() }</td>
|
||||
<td>{ &t.title }</td>
|
||||
@@ -80,10 +127,34 @@ pub fn album_page(props: &Props) -> Html {
|
||||
if let Some(ref status) = t.status {
|
||||
<StatusBadge status={status.clone()} />
|
||||
} else {
|
||||
<span class="text-muted text-sm">{ "—" }</span>
|
||||
<span class="text-muted text-sm">{ "\u{2014}" }</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-secondary"
|
||||
onclick={on_lyrics_click}>
|
||||
{ if is_active { "Hide" } else { "Lyrics" } }
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
if is_active {
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
{ match cached {
|
||||
Some(ref lr) if lr.found => html! {
|
||||
<pre class="lyrics">{ lr.synced_lyrics.as_deref().or(lr.lyrics.as_deref()).unwrap_or("") }</pre>
|
||||
},
|
||||
Some(_) => html! {
|
||||
<p class="text-muted text-sm">{ "No lyrics found." }</p>
|
||||
},
|
||||
None => html! {
|
||||
<p class="text-sm loading">{ "Loading lyrics..." }</p>
|
||||
},
|
||||
}}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</>
|
||||
}
|
||||
})}
|
||||
</tbody>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::rc::Rc;
|
||||
use std::cell::Cell;
|
||||
use gloo_timers::callback::Interval;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use yew::prelude::*;
|
||||
use yew_router::prelude::*;
|
||||
|
||||
@@ -152,9 +152,53 @@ pub fn artist_page(props: &Props) -> Html {
|
||||
<div>
|
||||
<div class="page-header">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2>{ &d.artist.name }</h2>
|
||||
<div class="flex gap-2 items-center">
|
||||
if let Some(ref photo) = d.artist_photo {
|
||||
<img class="artist-photo" src={photo.clone()} loading="lazy" />
|
||||
}
|
||||
<div>
|
||||
<h2>{ &d.artist.name }</h2>
|
||||
if let Some(ref info) = d.artist_info {
|
||||
<div class="artist-meta">
|
||||
if let Some(ref country) = info.country {
|
||||
<span class="tag">{ country }</span>
|
||||
}
|
||||
if let Some(ref atype) = info.artist_type {
|
||||
<span class="tag">{ atype }</span>
|
||||
}
|
||||
if let Some(ref year) = info.begin_year {
|
||||
<span class="text-sm text-muted">{ format!("est. {year}") }</span>
|
||||
}
|
||||
if let Some(ref dis) = info.disambiguation {
|
||||
<span class="text-sm text-muted">{ format!("({dis})") }</span>
|
||||
}
|
||||
</div>
|
||||
if !info.urls.is_empty() {
|
||||
<div class="artist-links">
|
||||
{ for info.urls.iter().filter(|u|
|
||||
["wikipedia", "official homepage", "discogs", "wikidata"].contains(&u.link_type.as_str())
|
||||
).map(|u| {
|
||||
let label = match u.link_type.as_str() {
|
||||
"wikipedia" => "Wikipedia",
|
||||
"official homepage" => "Official Site",
|
||||
"discogs" => "Discogs",
|
||||
"wikidata" => "Wikidata",
|
||||
other => other,
|
||||
};
|
||||
html! {
|
||||
<a href={u.url.clone()} target="_blank" rel="noopener">{ label }</a>
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
{ watch_all_btn }
|
||||
</div>
|
||||
if let Some(ref bio) = d.artist_bio {
|
||||
<p class="artist-bio text-sm">{ bio }</p>
|
||||
}
|
||||
if d.enriched {
|
||||
<p class="text-sm">
|
||||
<span style="color: var(--accent);">
|
||||
@@ -194,6 +238,7 @@ pub fn artist_page(props: &Props) -> Html {
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 60px;"></th>
|
||||
<th>{ "Title" }</th>
|
||||
<th>{ "Date" }</th>
|
||||
<th>{ "Owned" }</th>
|
||||
@@ -206,6 +251,7 @@ pub fn artist_page(props: &Props) -> Html {
|
||||
let is_unwatched = album.status == "unwatched";
|
||||
let row_style = if is_unwatched { "opacity: 0.6;" } else { "" };
|
||||
|
||||
let cover_url = format!("https://coverartarchive.org/release/{}/front-250", album.mbid);
|
||||
let album_link = html! {
|
||||
<Link<Route> to={Route::Album { mbid: album.mbid.clone() }}>
|
||||
{ &album.title }
|
||||
@@ -255,6 +301,15 @@ pub fn artist_page(props: &Props) -> Html {
|
||||
|
||||
html! {
|
||||
<tr style={row_style}>
|
||||
<td>
|
||||
<img class="album-art" src={cover_url}
|
||||
loading="lazy"
|
||||
onerror={Callback::from(|e: web_sys::Event| {
|
||||
if let Some(el) = e.target_dyn_into::<web_sys::HtmlElement>() {
|
||||
el.set_attribute("style", "display:none").ok();
|
||||
}
|
||||
})} />
|
||||
</td>
|
||||
<td>{ album_link }</td>
|
||||
<td class="text-muted">{ album.date.as_deref().unwrap_or("") }</td>
|
||||
<td>
|
||||
|
||||
@@ -62,7 +62,10 @@ pub fn dashboard() -> Html {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::sync_downloads().await {
|
||||
Ok(s) => {
|
||||
message.set(Some(format!("Synced: {} enqueued, {} skipped", s.enqueued, s.skipped)));
|
||||
message.set(Some(format!(
|
||||
"Synced: {} enqueued, {} skipped",
|
||||
s.enqueued, s.skipped
|
||||
)));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
@@ -82,7 +85,10 @@ pub fn dashboard() -> Html {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::process_downloads().await {
|
||||
Ok(t) => {
|
||||
message.set(Some(format!("Downloads started (task: {})", &t.task_id[..8])));
|
||||
message.set(Some(format!(
|
||||
"Downloads started (task: {})",
|
||||
&t.task_id[..8]
|
||||
)));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
@@ -101,7 +107,10 @@ pub fn dashboard() -> Html {
|
||||
let fetch = fetch.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::trigger_index().await {
|
||||
Ok(t) => { message.set(Some(format!("Indexing started ({})", &t.task_id[..8]))); fetch.emit(()); }
|
||||
Ok(t) => {
|
||||
message.set(Some(format!("Indexing started ({})", &t.task_id[..8])));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
}
|
||||
});
|
||||
@@ -118,7 +127,10 @@ pub fn dashboard() -> Html {
|
||||
let fetch = fetch.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::trigger_tag().await {
|
||||
Ok(t) => { message.set(Some(format!("Tagging started ({})", &t.task_id[..8]))); fetch.emit(()); }
|
||||
Ok(t) => {
|
||||
message.set(Some(format!("Tagging started ({})", &t.task_id[..8])));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
}
|
||||
});
|
||||
@@ -135,7 +147,10 @@ pub fn dashboard() -> Html {
|
||||
let fetch = fetch.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::trigger_organize().await {
|
||||
Ok(t) => { message.set(Some(format!("Organizing started ({})", &t.task_id[..8]))); fetch.emit(()); }
|
||||
Ok(t) => {
|
||||
message.set(Some(format!("Organizing started ({})", &t.task_id[..8])));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
}
|
||||
});
|
||||
@@ -153,7 +168,10 @@ pub fn dashboard() -> Html {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match api::trigger_pipeline().await {
|
||||
Ok(p) => {
|
||||
message.set(Some(format!("Pipeline started — {} tasks queued", p.task_ids.len())));
|
||||
message.set(Some(format!(
|
||||
"Pipeline started — {} tasks queued",
|
||||
p.task_ids.len()
|
||||
)));
|
||||
fetch.emit(());
|
||||
}
|
||||
Err(e) => error.set(Some(e.0)),
|
||||
@@ -170,7 +188,10 @@ pub fn dashboard() -> Html {
|
||||
return html! { <p class="loading">{ "Loading..." }</p> };
|
||||
};
|
||||
|
||||
let pipeline_active = s.tasks.iter().any(|t| t.status == "Pending" || t.status == "Running");
|
||||
let pipeline_active = s
|
||||
.tasks
|
||||
.iter()
|
||||
.any(|t| t.status == "Pending" || t.status == "Running");
|
||||
|
||||
html! {
|
||||
<div>
|
||||
|
||||
@@ -61,6 +61,40 @@ pub struct FullArtistDetail {
|
||||
pub total_owned_tracks: u32,
|
||||
#[serde(default)]
|
||||
pub enriched: bool,
|
||||
#[serde(default)]
|
||||
pub artist_info: Option<ArtistInfoFe>,
|
||||
#[serde(default)]
|
||||
pub artist_photo: Option<String>,
|
||||
#[serde(default)]
|
||||
pub artist_bio: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct ArtistInfoFe {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub disambiguation: Option<String>,
|
||||
#[serde(default)]
|
||||
pub country: Option<String>,
|
||||
#[serde(default)]
|
||||
pub artist_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub begin_year: Option<String>,
|
||||
#[serde(default)]
|
||||
pub urls: Vec<ArtistUrlFe>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct ArtistUrlFe {
|
||||
pub url: String,
|
||||
pub link_type: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct LyricsResult {
|
||||
pub found: bool,
|
||||
pub lyrics: Option<String>,
|
||||
pub synced_lyrics: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
|
||||
@@ -88,6 +88,92 @@ a:hover { color: var(--accent-hover); }
|
||||
.stat-card .value { font-size: 2rem; font-weight: bold; color: var(--accent); }
|
||||
.stat-card .label { font-size: 0.85rem; color: var(--text-secondary); }
|
||||
|
||||
/* Album art */
|
||||
.album-art {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 4px;
|
||||
object-fit: cover;
|
||||
background: var(--bg-card);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.album-art-lg {
|
||||
width: 250px;
|
||||
height: 250px;
|
||||
border-radius: var(--radius);
|
||||
object-fit: cover;
|
||||
background: var(--bg-card);
|
||||
}
|
||||
.album-art-placeholder {
|
||||
display: inline-block;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg-card);
|
||||
}
|
||||
.album-art-placeholder-lg {
|
||||
display: block;
|
||||
width: 250px;
|
||||
height: 250px;
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-card);
|
||||
}
|
||||
.album-header {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.artist-meta {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.artist-meta .tag {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.1rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-card);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.artist-links {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.artist-links a {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.artist-links a:hover { color: var(--accent); }
|
||||
.artist-photo {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
border-radius: var(--radius);
|
||||
object-fit: cover;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.artist-bio {
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.6;
|
||||
max-width: 800px;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.lyrics {
|
||||
font-family: inherit;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-secondary);
|
||||
white-space: pre-wrap;
|
||||
padding: 1rem;
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius);
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Tables */
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 0.75rem; border-bottom: 1px solid var(--border); }
|
||||
|
||||
@@ -310,17 +310,17 @@ pub async fn enrich_artist(
|
||||
let local_id = a.id;
|
||||
(a, Some(local_id), mbid)
|
||||
} else {
|
||||
// Look up artist name from MusicBrainz by MBID — don't create a local record
|
||||
let (name, _disambiguation) = state
|
||||
// Look up artist info from MusicBrainz by MBID — don't create a local record
|
||||
let info = state
|
||||
.mb_client
|
||||
.get_artist_by_mbid(&mbid)
|
||||
.get_artist_info(&mbid)
|
||||
.await
|
||||
.map_err(|e| ApiError::NotFound(format!("artist MBID {mbid} not found: {e}")))?;
|
||||
|
||||
// Create a synthetic artist object for display only (not saved to DB)
|
||||
let synthetic = shanty_db::entities::artist::Model {
|
||||
id: 0,
|
||||
name,
|
||||
name: info.name.clone(),
|
||||
musicbrainz_id: Some(mbid.clone()),
|
||||
added_at: chrono::Utc::now().naive_utc(),
|
||||
top_songs: "[]".to_string(),
|
||||
@@ -330,6 +330,27 @@ pub async fn enrich_artist(
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch detailed artist info (country, type, URLs) — best-effort
|
||||
let artist_info = match state.mb_client.get_artist_info(&mbid).await {
|
||||
Ok(info) => {
|
||||
tracing::debug!(
|
||||
mbid = %mbid,
|
||||
urls = info.urls.len(),
|
||||
country = ?info.country,
|
||||
"fetched artist info"
|
||||
);
|
||||
Some(info)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(mbid = %mbid, error = %e, "failed to fetch artist info");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch Wikipedia photo + bio (cached)
|
||||
let (artist_photo, artist_bio) = fetch_wikipedia_data(state, &mbid, &artist_info).await;
|
||||
tracing::debug!(mbid = %mbid, has_photo = artist_photo.is_some(), has_bio = artist_bio.is_some(), "wikipedia data");
|
||||
|
||||
// Fetch release groups and filter by allowed secondary types
|
||||
let all_release_groups = state
|
||||
.search
|
||||
@@ -568,6 +589,9 @@ pub async fn enrich_artist(
|
||||
"total_watched_tracks": total_artist_watched,
|
||||
"total_owned_tracks": total_artist_owned,
|
||||
"enriched": !skip_track_fetch,
|
||||
"artist_info": artist_info,
|
||||
"artist_photo": artist_photo,
|
||||
"artist_bio": artist_bio,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -591,6 +615,140 @@ pub async fn enrich_all_watched_artists(state: &AppState) -> Result<u32, ApiErro
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Fetch artist photo and bio from Wikipedia, with caching.
|
||||
async fn fetch_wikipedia_data(
|
||||
state: &AppState,
|
||||
mbid: &str,
|
||||
artist_info: &Option<shanty_tag::provider::ArtistInfo>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
let cache_key = format!("artist_wiki:{mbid}");
|
||||
|
||||
// Check cache first
|
||||
if let Ok(Some(json)) = queries::cache::get(state.db.conn(), &cache_key).await {
|
||||
if let Ok(cached) = serde_json::from_str::<serde_json::Value>(&json) {
|
||||
return (
|
||||
cached.get("photo_url").and_then(|v| v.as_str()).map(String::from),
|
||||
cached.get("bio").and_then(|v| v.as_str()).map(String::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Find Wikipedia URL from artist info — try direct link first, then resolve via Wikidata
|
||||
let wiki_url = if let Some(info) = artist_info.as_ref() {
|
||||
if let Some(u) = info.urls.iter().find(|u| u.link_type == "wikipedia") {
|
||||
Some(u.url.clone())
|
||||
} else if let Some(wd) = info.urls.iter().find(|u| u.link_type == "wikidata") {
|
||||
// Extract Wikidata entity ID and resolve to Wikipedia URL
|
||||
let entity_id = wd.url.split('/').last().unwrap_or("");
|
||||
resolve_wikidata_to_wikipedia(entity_id).await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let Some(wiki_url) = wiki_url else {
|
||||
tracing::debug!(mbid = mbid, "no wikipedia URL found");
|
||||
return (None, None);
|
||||
};
|
||||
tracing::debug!(mbid = mbid, wiki_url = %wiki_url, "found wikipedia URL");
|
||||
|
||||
// Parse article title from URL (e.g., https://en.wikipedia.org/wiki/Pink_Floyd → Pink_Floyd)
|
||||
let title = wiki_url
|
||||
.split("/wiki/")
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
if title.is_empty() {
|
||||
return (None, None);
|
||||
}
|
||||
|
||||
// Detect language from URL (e.g., en.wikipedia.org → en)
|
||||
let lang = wiki_url
|
||||
.split("://")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split('.').next())
|
||||
.unwrap_or("en");
|
||||
|
||||
// Call Wikipedia REST API
|
||||
let api_url = format!("https://{lang}.wikipedia.org/api/rest_v1/page/summary/{title}");
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("Shanty/0.1.0 (shanty-music-app)")
|
||||
.build()
|
||||
.ok();
|
||||
|
||||
let Some(client) = client else {
|
||||
return (None, None);
|
||||
};
|
||||
|
||||
let resp = match client.get(&api_url).send().await {
|
||||
Ok(r) if r.status().is_success() => r,
|
||||
_ => return (None, None),
|
||||
};
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
Ok(v) => v,
|
||||
Err(_) => return (None, None),
|
||||
};
|
||||
|
||||
let photo_url = body
|
||||
.get("thumbnail")
|
||||
.and_then(|t| t.get("source"))
|
||||
.and_then(|s| s.as_str())
|
||||
.map(String::from);
|
||||
|
||||
let bio = body
|
||||
.get("extract")
|
||||
.and_then(|e| e.as_str())
|
||||
.map(String::from);
|
||||
|
||||
// Cache for 30 days
|
||||
let cache_val = serde_json::json!({ "photo_url": photo_url, "bio": bio });
|
||||
let _ = queries::cache::set(
|
||||
state.db.conn(),
|
||||
&cache_key,
|
||||
"wikipedia",
|
||||
&cache_val.to_string(),
|
||||
30 * 86400,
|
||||
)
|
||||
.await;
|
||||
|
||||
(photo_url, bio)
|
||||
}
|
||||
|
||||
/// Resolve a Wikidata entity ID to an English Wikipedia URL.
|
||||
async fn resolve_wikidata_to_wikipedia(entity_id: &str) -> Option<String> {
|
||||
if entity_id.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let url = format!(
|
||||
"https://www.wikidata.org/w/api.php?action=wbgetentities&ids={entity_id}&props=sitelinks&sitefilter=enwiki&format=json"
|
||||
);
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("Shanty/0.1.0 (shanty-music-app)")
|
||||
.build()
|
||||
.ok()?;
|
||||
|
||||
let resp: serde_json::Value = client.get(&url).send().await.ok()?.json().await.ok()?;
|
||||
|
||||
let title = resp
|
||||
.get("entities")
|
||||
.and_then(|e| e.get(entity_id))
|
||||
.and_then(|e| e.get("sitelinks"))
|
||||
.and_then(|s| s.get("enwiki"))
|
||||
.and_then(|w| w.get("title"))
|
||||
.and_then(|t| t.as_str())?;
|
||||
|
||||
Some(format!(
|
||||
"https://en.wikipedia.org/wiki/{}",
|
||||
title.replace(' ', "_")
|
||||
))
|
||||
}
|
||||
|
||||
async fn add_artist(
|
||||
state: web::Data<AppState>,
|
||||
session: Session,
|
||||
|
||||
113
src/routes/lyrics.rs
Normal file
113
src/routes/lyrics.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use actix_session::Session;
|
||||
use actix_web::{HttpResponse, web};
|
||||
use serde::Deserialize;
|
||||
|
||||
use shanty_db::queries;
|
||||
|
||||
use crate::auth;
|
||||
use crate::error::ApiError;
|
||||
use crate::state::AppState;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LyricsQuery {
|
||||
artist: String,
|
||||
title: String,
|
||||
}
|
||||
|
||||
pub fn configure(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(web::resource("/lyrics").route(web::get().to(get_lyrics)));
|
||||
}
|
||||
|
||||
async fn get_lyrics(
|
||||
state: web::Data<AppState>,
|
||||
session: Session,
|
||||
query: web::Query<LyricsQuery>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
auth::require_auth(&session)?;
|
||||
|
||||
let artist = &query.artist;
|
||||
let title = &query.title;
|
||||
|
||||
// Normalize cache key
|
||||
let cache_key = format!("lyrics:{}:{}", artist.to_lowercase(), title.to_lowercase());
|
||||
|
||||
// Check cache first
|
||||
if let Ok(Some(json)) = queries::cache::get(state.db.conn(), &cache_key).await {
|
||||
return Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(json));
|
||||
}
|
||||
|
||||
// Call LRCLIB API
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("Shanty/0.1.0 (shanty-music-app)")
|
||||
.build()
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
|
||||
let url = format!(
|
||||
"https://lrclib.net/api/search?artist_name={}&track_name={}",
|
||||
urlencoded(artist),
|
||||
urlencoded(title),
|
||||
);
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("LRCLIB request failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Ok(HttpResponse::Ok().json(serde_json::json!({
|
||||
"found": false,
|
||||
"lyrics": null,
|
||||
"synced_lyrics": null,
|
||||
})));
|
||||
}
|
||||
|
||||
let results: Vec<serde_json::Value> = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("LRCLIB parse failed: {e}")))?;
|
||||
|
||||
let result = if let Some(entry) = results.first() {
|
||||
let plain = entry
|
||||
.get("plainLyrics")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
let synced = entry
|
||||
.get("syncedLyrics")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
|
||||
serde_json::json!({
|
||||
"found": plain.is_some() || synced.is_some(),
|
||||
"lyrics": plain,
|
||||
"synced_lyrics": synced,
|
||||
})
|
||||
} else {
|
||||
serde_json::json!({
|
||||
"found": false,
|
||||
"lyrics": null,
|
||||
"synced_lyrics": null,
|
||||
})
|
||||
};
|
||||
|
||||
// Cache for 30 days
|
||||
let _ = queries::cache::set(
|
||||
state.db.conn(),
|
||||
&cache_key,
|
||||
"lrclib",
|
||||
&result.to_string(),
|
||||
30 * 86400,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(HttpResponse::Ok().json(result))
|
||||
}
|
||||
|
||||
fn urlencoded(s: &str) -> String {
|
||||
s.replace(' ', "+")
|
||||
.replace('&', "%26")
|
||||
.replace('=', "%3D")
|
||||
.replace('#', "%23")
|
||||
}
|
||||
@@ -2,6 +2,7 @@ pub mod albums;
|
||||
pub mod artists;
|
||||
pub mod auth;
|
||||
pub mod downloads;
|
||||
pub mod lyrics;
|
||||
pub mod search;
|
||||
pub mod system;
|
||||
pub mod tracks;
|
||||
@@ -17,6 +18,7 @@ pub fn configure(cfg: &mut web::ServiceConfig) {
|
||||
.configure(tracks::configure)
|
||||
.configure(search::configure)
|
||||
.configure(downloads::configure)
|
||||
.configure(lyrics::configure)
|
||||
.configure(system::configure),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user