Compare commits
8 Commits
abe321a317
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36345b12ee | ||
|
|
59a26c18f3 | ||
|
|
673de39918 | ||
|
|
f87949dc82 | ||
|
|
44c96d125a | ||
|
|
3dba620c9b | ||
|
|
75f3b4f704 | ||
|
|
621355e352 |
@@ -23,6 +23,10 @@ actix-cors = "0.7"
|
|||||||
actix-files = "0.6"
|
actix-files = "0.6"
|
||||||
actix-session = { version = "0.10", features = ["cookie-session"] }
|
actix-session = { version = "0.10", features = ["cookie-session"] }
|
||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
|
md-5 = "0.10"
|
||||||
|
hex = "0.4"
|
||||||
|
quick-xml = { version = "0.37", features = ["serialize"] }
|
||||||
|
serde_urlencoded = "0.7"
|
||||||
rand = "0.9"
|
rand = "0.9"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
@@ -32,6 +36,7 @@ serde = { version = "1", features = ["derive"] }
|
|||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
serde_yaml = "0.9"
|
serde_yaml = "0.9"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
tokio-util = { version = "0.7", features = ["io"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
tracing-actix-web = "0.7"
|
tracing-actix-web = "0.7"
|
||||||
|
|||||||
@@ -176,6 +176,11 @@ pub async fn add_album(
|
|||||||
post_json(&format!("{BASE}/albums"), &body).await
|
post_json(&format!("{BASE}/albums"), &body).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn watch_track(title: &str, mbid: &str) -> Result<WatchTrackResponse, ApiError> {
|
||||||
|
let body = serde_json::json!({"title": title, "mbid": mbid}).to_string();
|
||||||
|
post_json(&format!("{BASE}/tracks/watch"), &body).await
|
||||||
|
}
|
||||||
|
|
||||||
// --- Downloads ---
|
// --- Downloads ---
|
||||||
pub async fn get_downloads(status: Option<&str>) -> Result<Vec<DownloadItem>, ApiError> {
|
pub async fn get_downloads(status: Option<&str>) -> Result<Vec<DownloadItem>, ApiError> {
|
||||||
let mut url = format!("{BASE}/downloads/queue");
|
let mut url = format!("{BASE}/downloads/queue");
|
||||||
@@ -326,14 +331,8 @@ pub async fn add_track_to_playlist(
|
|||||||
post_json(&format!("{BASE}/playlists/{playlist_id}/tracks"), &body).await
|
post_json(&format!("{BASE}/playlists/{playlist_id}/tracks"), &body).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn remove_track_from_playlist(
|
pub async fn remove_track_from_playlist(playlist_id: i32, track_id: i32) -> Result<(), ApiError> {
|
||||||
playlist_id: i32,
|
delete(&format!("{BASE}/playlists/{playlist_id}/tracks/{track_id}")).await
|
||||||
track_id: i32,
|
|
||||||
) -> Result<(), ApiError> {
|
|
||||||
delete(&format!(
|
|
||||||
"{BASE}/playlists/{playlist_id}/tracks/{track_id}"
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn reorder_playlist_tracks(
|
pub async fn reorder_playlist_tracks(
|
||||||
@@ -348,6 +347,17 @@ pub async fn search_tracks(query: &str) -> Result<Vec<Track>, ApiError> {
|
|||||||
get_json(&format!("{BASE}/tracks?q={query}&limit=50")).await
|
get_json(&format!("{BASE}/tracks?q={query}&limit=50")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Subsonic ---
|
||||||
|
|
||||||
|
pub async fn get_subsonic_password_status() -> Result<SubsonicPasswordStatus, ApiError> {
|
||||||
|
get_json(&format!("{BASE}/auth/subsonic-password-status")).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_subsonic_password(password: &str) -> Result<serde_json::Value, ApiError> {
|
||||||
|
let body = serde_json::json!({"password": password}).to_string();
|
||||||
|
put_json(&format!("{BASE}/auth/subsonic-password"), &body).await
|
||||||
|
}
|
||||||
|
|
||||||
// --- YouTube Auth ---
|
// --- YouTube Auth ---
|
||||||
|
|
||||||
pub async fn get_ytauth_status() -> Result<YtAuthStatus, ApiError> {
|
pub async fn get_ytauth_status() -> Result<YtAuthStatus, ApiError> {
|
||||||
@@ -369,3 +379,13 @@ pub async fn ytauth_refresh() -> Result<serde_json::Value, ApiError> {
|
|||||||
pub async fn ytauth_clear_cookies() -> Result<(), ApiError> {
|
pub async fn ytauth_clear_cookies() -> Result<(), ApiError> {
|
||||||
delete(&format!("{BASE}/ytauth/cookies")).await
|
delete(&format!("{BASE}/ytauth/cookies")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- MusicBrainz Local DB ---
|
||||||
|
|
||||||
|
pub async fn get_mb_status() -> Result<MbStatus, ApiError> {
|
||||||
|
get_json(&format!("{BASE}/mb-status")).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn trigger_mb_import() -> Result<TaskRef, ApiError> {
|
||||||
|
post_empty(&format!("{BASE}/mb-import")).await
|
||||||
|
}
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ pub fn album_page(props: &Props) -> Html {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{ for d.tracks.iter().map(|t| {
|
{ for d.tracks.iter().enumerate().map(|(idx, t)| {
|
||||||
let duration = t.duration_ms
|
let duration = t.duration_ms
|
||||||
.map(&fmt_duration)
|
.map(&fmt_duration)
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
@@ -88,6 +88,7 @@ pub fn album_page(props: &Props) -> Html {
|
|||||||
let track_key = t.recording_mbid.clone();
|
let track_key = t.recording_mbid.clone();
|
||||||
let is_active = active_lyrics.as_ref() == Some(&track_key);
|
let is_active = active_lyrics.as_ref() == Some(&track_key);
|
||||||
let cached = lyrics_cache.get(&track_key).cloned();
|
let cached = lyrics_cache.get(&track_key).cloned();
|
||||||
|
let has_status = t.status.is_some();
|
||||||
|
|
||||||
let on_lyrics_click = {
|
let on_lyrics_click = {
|
||||||
let active = active_lyrics.clone();
|
let active = active_lyrics.clone();
|
||||||
@@ -117,6 +118,29 @@ pub fn album_page(props: &Props) -> Html {
|
|||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let on_watch_click = {
|
||||||
|
let detail = detail.clone();
|
||||||
|
let title = t.title.clone();
|
||||||
|
let mbid = t.recording_mbid.clone();
|
||||||
|
Callback::from(move |_: MouseEvent| {
|
||||||
|
let detail = detail.clone();
|
||||||
|
let title = title.clone();
|
||||||
|
let mbid = mbid.clone();
|
||||||
|
let idx = idx;
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
if let Ok(resp) = api::watch_track(&title, &mbid).await {
|
||||||
|
if let Some(ref d) = *detail {
|
||||||
|
let mut updated = d.clone();
|
||||||
|
if let Some(track) = updated.tracks.get_mut(idx) {
|
||||||
|
track.status = Some(resp.status);
|
||||||
|
}
|
||||||
|
detail.set(Some(updated));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
html! {
|
html! {
|
||||||
<>
|
<>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -130,7 +154,13 @@ pub fn album_page(props: &Props) -> Html {
|
|||||||
<span class="text-muted text-sm">{ "\u{2014}" }</span>
|
<span class="text-muted text-sm">{ "\u{2014}" }</span>
|
||||||
}
|
}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td class="actions">
|
||||||
|
if !has_status {
|
||||||
|
<button class="btn btn-sm"
|
||||||
|
onclick={on_watch_click}>
|
||||||
|
{ "Watch" }
|
||||||
|
</button>
|
||||||
|
}
|
||||||
<button class="btn btn-sm btn-secondary"
|
<button class="btn btn-sm btn-secondary"
|
||||||
onclick={on_lyrics_click}>
|
onclick={on_lyrics_click}>
|
||||||
{ if is_active { "Hide" } else { "Lyrics" } }
|
{ if is_active { "Hide" } else { "Lyrics" } }
|
||||||
|
|||||||
@@ -365,6 +365,35 @@ pub fn dashboard() -> Html {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
// Work Queue Progress
|
||||||
|
if let Some(ref wq) = s.work_queue {
|
||||||
|
if wq.download.pending + wq.download.running + wq.tag.pending + wq.tag.running + wq.organize.pending + wq.organize.running > 0
|
||||||
|
|| wq.download.completed + wq.tag.completed + wq.organize.completed > 0
|
||||||
|
{
|
||||||
|
<div class="card">
|
||||||
|
<h3>{ "Pipeline Progress" }</h3>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>{ "Step" }</th><th>{ "Pending" }</th><th>{ "Running" }</th><th>{ "Done" }</th><th>{ "Failed" }</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{ for [("Download", &wq.download), ("Index", &wq.index), ("Tag", &wq.tag), ("Organize", &wq.organize)].iter().map(|(name, c)| {
|
||||||
|
html! {
|
||||||
|
<tr>
|
||||||
|
<td>{ name }</td>
|
||||||
|
<td>{ c.pending }</td>
|
||||||
|
<td>{ if c.running > 0 { html! { <span class="badge badge-accent">{ c.running }</span> } } else { html! { { "0" } } } }</td>
|
||||||
|
<td>{ c.completed }</td>
|
||||||
|
<td>{ if c.failed > 0 { html! { <span class="badge badge-danger">{ c.failed }</span> } } else { html! { { "0" } } } }</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Background Tasks (always show if there are tasks or scheduled items)
|
// Background Tasks (always show if there are tasks or scheduled items)
|
||||||
if !s.tasks.is_empty() || has_scheduled {
|
if !s.tasks.is_empty() || has_scheduled {
|
||||||
<div class="card">
|
<div class="card">
|
||||||
|
|||||||
@@ -560,16 +560,8 @@ pub fn playlists_page() -> Html {
|
|||||||
if existing_ids.contains(&t.id) {
|
if existing_ids.contains(&t.id) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let title_lower = t
|
let title_lower = t.title.as_deref().unwrap_or("").to_lowercase();
|
||||||
.title
|
let artist_lower = t.artist.as_deref().unwrap_or("").to_lowercase();
|
||||||
.as_deref()
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_lowercase();
|
|
||||||
let artist_lower = t
|
|
||||||
.artist
|
|
||||||
.as_deref()
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_lowercase();
|
|
||||||
// Subsequence match on title or artist
|
// Subsequence match on title or artist
|
||||||
let matches_field = |field: &str| {
|
let matches_field = |field: &str| {
|
||||||
let mut chars = search_query.chars();
|
let mut chars = search_query.chars();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use web_sys::HtmlSelectElement;
|
|||||||
use yew::prelude::*;
|
use yew::prelude::*;
|
||||||
|
|
||||||
use crate::api;
|
use crate::api;
|
||||||
use crate::types::{AppConfig, YtAuthStatus};
|
use crate::types::{AppConfig, MbStatus, SubsonicPasswordStatus, YtAuthStatus};
|
||||||
|
|
||||||
#[function_component(SettingsPage)]
|
#[function_component(SettingsPage)]
|
||||||
pub fn settings_page() -> Html {
|
pub fn settings_page() -> Html {
|
||||||
@@ -12,11 +12,18 @@ pub fn settings_page() -> Html {
|
|||||||
let message = use_state(|| None::<String>);
|
let message = use_state(|| None::<String>);
|
||||||
let ytauth = use_state(|| None::<YtAuthStatus>);
|
let ytauth = use_state(|| None::<YtAuthStatus>);
|
||||||
let ytauth_loading = use_state(|| false);
|
let ytauth_loading = use_state(|| false);
|
||||||
|
let subsonic_status = use_state(|| None::<SubsonicPasswordStatus>);
|
||||||
|
let subsonic_password = use_state(String::new);
|
||||||
|
let subsonic_saving = use_state(|| false);
|
||||||
|
let mb_status = use_state(|| None::<MbStatus>);
|
||||||
|
let mb_importing = use_state(|| false);
|
||||||
|
|
||||||
{
|
{
|
||||||
let config = config.clone();
|
let config = config.clone();
|
||||||
let error = error.clone();
|
let error = error.clone();
|
||||||
let ytauth = ytauth.clone();
|
let ytauth = ytauth.clone();
|
||||||
|
let subsonic_status = subsonic_status.clone();
|
||||||
|
let mb_status = mb_status.clone();
|
||||||
use_effect_with((), move |_| {
|
use_effect_with((), move |_| {
|
||||||
wasm_bindgen_futures::spawn_local(async move {
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
match api::get_config().await {
|
match api::get_config().await {
|
||||||
@@ -29,6 +36,16 @@ pub fn settings_page() -> Html {
|
|||||||
ytauth.set(Some(status));
|
ytauth.set(Some(status));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
if let Ok(status) = api::get_subsonic_password_status().await {
|
||||||
|
subsonic_status.set(Some(status));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
if let Ok(status) = api::get_mb_status().await {
|
||||||
|
mb_status.set(Some(status));
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -500,6 +517,181 @@ pub fn settings_page() -> Html {
|
|||||||
{ ytauth_html }
|
{ ytauth_html }
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
// Subsonic API
|
||||||
|
<div class="card">
|
||||||
|
<h3>{ "Subsonic API" }</h3>
|
||||||
|
<p class="text-sm text-muted mb-1">
|
||||||
|
{ "Connect Subsonic-compatible apps (DSub, Symfonium, Feishin) to stream your library. " }
|
||||||
|
{ "This is a minimal Subsonic implementation for basic browsing and playback. " }
|
||||||
|
{ "For a full-featured Subsonic server, consider " }
|
||||||
|
<a href="https://www.navidrome.org" target="_blank">{ "Navidrome" }</a>
|
||||||
|
{ " pointed at the same library." }
|
||||||
|
</p>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>{ "Server URL (most clients add /rest automatically)" }</label>
|
||||||
|
<input type="text" readonly=true value={
|
||||||
|
format!("http://{}:{}",
|
||||||
|
c.web.bind.clone(),
|
||||||
|
c.web.port)
|
||||||
|
} />
|
||||||
|
</div>
|
||||||
|
{
|
||||||
|
if let Some(ref status) = *subsonic_status {
|
||||||
|
if status.set {
|
||||||
|
html! {
|
||||||
|
<p class="text-sm">
|
||||||
|
<span class="badge badge-success">{ "Password set" }</span>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
html! {
|
||||||
|
<p class="text-sm text-muted">{ "No Subsonic password set. Set one below to enable access." }</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
html! { <p class="text-sm text-muted">{ "Loading..." }</p> }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<div class="card" style="border-color: var(--warning); background: rgba(234, 179, 8, 0.08); margin: 0.75rem 0;">
|
||||||
|
<p class="text-sm" style="margin:0;">
|
||||||
|
<strong style="color: var(--warning);">{ "Warning: " }</strong>
|
||||||
|
{ "This password is stored in plaintext per the Subsonic protocol. Do " }
|
||||||
|
<strong>{ "not" }</strong>
|
||||||
|
{ " reuse a password from another account." }
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>{ "Subsonic Password" }</label>
|
||||||
|
<input type="password" placeholder="Enter Subsonic password"
|
||||||
|
value={(*subsonic_password).clone()}
|
||||||
|
oninput={let subsonic_password = subsonic_password.clone(); Callback::from(move |e: InputEvent| {
|
||||||
|
let input: HtmlInputElement = e.target_unchecked_into();
|
||||||
|
subsonic_password.set(input.value());
|
||||||
|
})} />
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn btn-primary"
|
||||||
|
disabled={*subsonic_saving || subsonic_password.is_empty()}
|
||||||
|
onclick={{
|
||||||
|
let subsonic_password = subsonic_password.clone();
|
||||||
|
let subsonic_saving = subsonic_saving.clone();
|
||||||
|
let subsonic_status = subsonic_status.clone();
|
||||||
|
let message = message.clone();
|
||||||
|
let error = error.clone();
|
||||||
|
Callback::from(move |_: MouseEvent| {
|
||||||
|
let pw = (*subsonic_password).clone();
|
||||||
|
let subsonic_saving = subsonic_saving.clone();
|
||||||
|
let subsonic_status = subsonic_status.clone();
|
||||||
|
let subsonic_password = subsonic_password.clone();
|
||||||
|
let message = message.clone();
|
||||||
|
let error = error.clone();
|
||||||
|
subsonic_saving.set(true);
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
match api::set_subsonic_password(&pw).await {
|
||||||
|
Ok(_) => {
|
||||||
|
message.set(Some("Subsonic password saved".into()));
|
||||||
|
subsonic_password.set(String::new());
|
||||||
|
if let Ok(s) = api::get_subsonic_password_status().await {
|
||||||
|
subsonic_status.set(Some(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => error.set(Some(e.0)),
|
||||||
|
}
|
||||||
|
subsonic_saving.set(false);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
}}>
|
||||||
|
{ if *subsonic_saving { "Saving..." } else { "Save Subsonic Password" } }
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
// MusicBrainz Local Database
|
||||||
|
<div class="card">
|
||||||
|
<h3>{ "MusicBrainz Database" }</h3>
|
||||||
|
<p class="text-sm text-muted mb-1">
|
||||||
|
{ "Import the MusicBrainz database locally for instant artist/album lookups instead of rate-limited API calls. " }
|
||||||
|
{ "Makes browsing and watching artists dramatically faster." }
|
||||||
|
</p>
|
||||||
|
<div class="card" style="border-color: var(--warning); background: rgba(234, 179, 8, 0.08); margin: 0.5rem 0;">
|
||||||
|
<p class="text-sm" style="margin:0;">
|
||||||
|
<strong style="color: var(--warning);">{ "Heads up: " }</strong>
|
||||||
|
{ "This downloads ~24 GB of data and builds a ~10 GB local database. " }
|
||||||
|
{ "The initial import can take 12-24 hours depending on your hardware. " }
|
||||||
|
{ "Total disk usage: ~35 GB (downloads + database). " }
|
||||||
|
{ "After the initial import, the database is automatically refreshed weekly to stay current. " }
|
||||||
|
<strong>{ "SSD storage is recommended" }</strong>
|
||||||
|
{ " for best performance. HDDs will still be faster than the API, but lookups may take a few seconds instead of being instant." }
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{
|
||||||
|
if let Some(ref status) = *mb_status {
|
||||||
|
if status.has_local_db {
|
||||||
|
if let Some(ref stats) = status.stats {
|
||||||
|
let import_date = stats.last_import_date.clone().unwrap_or_else(|| "unknown".into());
|
||||||
|
html! {
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
<span class="badge badge-success">{ "Loaded" }</span>
|
||||||
|
<span class="text-muted text-sm" style="margin-left: 0.5rem;">
|
||||||
|
{ format!("imported {}", import_date) }
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<p class="text-sm">
|
||||||
|
{ format!("{} artists, {} release groups, {} releases, {} recordings",
|
||||||
|
stats.artists, stats.release_groups, stats.releases, stats.recordings) }
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
html! {
|
||||||
|
<p><span class="badge badge-success">{ "Loaded" }</span></p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
html! {
|
||||||
|
<p class="text-sm text-muted">
|
||||||
|
{ "Not configured. Import data to enable instant lookups." }
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
html! { <p class="text-sm text-muted">{ "Loading..." }</p> }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<button type="button" class="btn btn-primary"
|
||||||
|
disabled={*mb_importing}
|
||||||
|
onclick={{
|
||||||
|
let mb_importing = mb_importing.clone();
|
||||||
|
let mb_status = mb_status.clone();
|
||||||
|
let message = message.clone();
|
||||||
|
let error = error.clone();
|
||||||
|
Callback::from(move |_: MouseEvent| {
|
||||||
|
let mb_importing = mb_importing.clone();
|
||||||
|
let mb_status = mb_status.clone();
|
||||||
|
let message = message.clone();
|
||||||
|
let error = error.clone();
|
||||||
|
mb_importing.set(true);
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
match api::trigger_mb_import().await {
|
||||||
|
Ok(task_ref) => {
|
||||||
|
message.set(Some(format!(
|
||||||
|
"MusicBrainz import started (task {}). This will take a while.",
|
||||||
|
task_ref.task_id
|
||||||
|
)));
|
||||||
|
// Refresh status after a short delay
|
||||||
|
if let Ok(s) = api::get_mb_status().await {
|
||||||
|
mb_status.set(Some(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => error.set(Some(e.0)),
|
||||||
|
}
|
||||||
|
mb_importing.set(false);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
}}>
|
||||||
|
{ if *mb_importing { "Starting import..." } else { "Import MusicBrainz Data" } }
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
// Metadata Providers
|
// Metadata Providers
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>{ "Metadata Providers" }</h3>
|
<h3>{ "Metadata Providers" }</h3>
|
||||||
@@ -647,6 +839,27 @@ pub fn settings_page() -> Html {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
// Logging
|
||||||
|
<div class="card">
|
||||||
|
<h3>{ "Logging" }</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>{ "Log Level" }</label>
|
||||||
|
<select onchange={let config = config.clone(); Callback::from(move |e: Event| {
|
||||||
|
let select: HtmlSelectElement = e.target_unchecked_into();
|
||||||
|
let mut cfg = (*config).clone().unwrap();
|
||||||
|
cfg.log_level = select.value();
|
||||||
|
config.set(Some(cfg));
|
||||||
|
})}>
|
||||||
|
{ for [("error", "Error"), ("warn", "Warning"), ("info", "Info"), ("debug", "Debug"), ("trace", "Trace")].iter().map(|(v, label)| html! {
|
||||||
|
<option value={*v} selected={c.log_level == *v}>{ label }</option>
|
||||||
|
})}
|
||||||
|
</select>
|
||||||
|
<p class="text-muted text-sm" style="margin-top: 0.25rem;">
|
||||||
|
{ "Requires restart to take effect. CLI flags (-v, -vv) override this setting." }
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button type="submit" class="btn btn-primary">{ "Save Settings" }</button>
|
<button type="submit" class="btn btn-primary">{ "Save Settings" }</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -225,7 +225,10 @@ pub struct TaskRef {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
pub struct PipelineRef {
|
pub struct PipelineRef {
|
||||||
|
#[serde(default)]
|
||||||
pub task_ids: Vec<String>,
|
pub task_ids: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub pipeline_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Status ---
|
// --- Status ---
|
||||||
@@ -246,6 +249,10 @@ pub struct Status {
|
|||||||
pub tasks: Vec<TaskInfo>,
|
pub tasks: Vec<TaskInfo>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub scheduled: Option<ScheduledTasks>,
|
pub scheduled: Option<ScheduledTasks>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub work_queue: Option<WorkQueueStats>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub scheduler: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
@@ -254,6 +261,22 @@ pub struct ScheduledTasks {
|
|||||||
pub next_monitor: Option<String>,
|
pub next_monitor: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct WorkQueueCounts {
|
||||||
|
pub pending: u64,
|
||||||
|
pub running: u64,
|
||||||
|
pub completed: u64,
|
||||||
|
pub failed: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct WorkQueueStats {
|
||||||
|
pub download: WorkQueueCounts,
|
||||||
|
pub index: WorkQueueCounts,
|
||||||
|
pub tag: WorkQueueCounts,
|
||||||
|
pub organize: WorkQueueCounts,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
pub struct LibrarySummary {
|
pub struct LibrarySummary {
|
||||||
pub total_items: u64,
|
pub total_items: u64,
|
||||||
@@ -282,6 +305,14 @@ pub struct AddSummary {
|
|||||||
pub errors: u64,
|
pub errors: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct WatchTrackResponse {
|
||||||
|
pub id: i32,
|
||||||
|
pub status: String,
|
||||||
|
pub name: String,
|
||||||
|
pub artist_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
pub struct SyncStats {
|
pub struct SyncStats {
|
||||||
pub found: u64,
|
pub found: u64,
|
||||||
@@ -371,6 +402,13 @@ pub struct SavedPlaylist {
|
|||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Subsonic ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct SubsonicPasswordStatus {
|
||||||
|
pub set: bool,
|
||||||
|
}
|
||||||
|
|
||||||
// --- Config ---
|
// --- Config ---
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -393,6 +431,14 @@ pub struct AppConfig {
|
|||||||
pub metadata: MetadataConfigFe,
|
pub metadata: MetadataConfigFe,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub scheduling: SchedulingConfigFe,
|
pub scheduling: SchedulingConfigFe,
|
||||||
|
#[serde(default)]
|
||||||
|
pub musicbrainz: MusicBrainzConfigFe,
|
||||||
|
#[serde(default = "default_log_level")]
|
||||||
|
pub log_level: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_log_level() -> String {
|
||||||
|
"info".into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||||
@@ -506,3 +552,36 @@ fn default_lyrics_source() -> String {
|
|||||||
fn default_cover_art_source() -> String {
|
fn default_cover_art_source() -> String {
|
||||||
"coverartarchive".into()
|
"coverartarchive".into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- MusicBrainz local DB ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct MusicBrainzConfigFe {
|
||||||
|
#[serde(default)]
|
||||||
|
pub local_db_path: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub auto_update: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct MbStatus {
|
||||||
|
pub has_local_db: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub stats: Option<MbLocalStats>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
|
pub struct MbLocalStats {
|
||||||
|
#[serde(default)]
|
||||||
|
pub artists: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub release_groups: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub releases: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub recordings: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub tracks: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub last_import_date: Option<String>,
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,59 +1,22 @@
|
|||||||
//! Background task that periodically refreshes YouTube cookies via headless Firefox.
|
//! YouTube cookie refresh via headless Firefox.
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
use std::process::Stdio;
|
use std::process::Stdio;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use tokio::process::Command;
|
use tokio::process::Command;
|
||||||
use tokio::sync::RwLock;
|
|
||||||
|
|
||||||
use crate::config::AppConfig;
|
|
||||||
|
|
||||||
/// Spawn the cookie refresh background loop.
|
|
||||||
///
|
|
||||||
/// This task runs forever, sleeping for `cookie_refresh_hours` between refreshes.
|
|
||||||
/// It reads the current config on each iteration so changes take effect without restart.
|
|
||||||
pub fn spawn(config: Arc<RwLock<AppConfig>>) {
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
let (enabled, hours) = {
|
|
||||||
let cfg = config.read().await;
|
|
||||||
(
|
|
||||||
cfg.download.cookie_refresh_enabled,
|
|
||||||
cfg.download.cookie_refresh_hours.max(1),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Sleep for the configured interval
|
|
||||||
tokio::time::sleep(Duration::from_secs(u64::from(hours) * 3600)).await;
|
|
||||||
|
|
||||||
if !enabled {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/// Run a headless cookie refresh. Returns success message or error.
|
||||||
|
pub async fn run_refresh() -> Result<String, String> {
|
||||||
let profile_dir = shanty_config::data_dir().join("firefox-profile");
|
let profile_dir = shanty_config::data_dir().join("firefox-profile");
|
||||||
let cookies_path = shanty_config::data_dir().join("cookies.txt");
|
let cookies_path = shanty_config::data_dir().join("cookies.txt");
|
||||||
|
|
||||||
if !profile_dir.exists() {
|
if !profile_dir.exists() {
|
||||||
tracing::warn!(
|
return Err(format!(
|
||||||
"cookie refresh skipped: no Firefox profile at {}",
|
"no Firefox profile at {}",
|
||||||
profile_dir.display()
|
profile_dir.display()
|
||||||
);
|
));
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tracing::info!("starting cookie refresh");
|
|
||||||
|
|
||||||
match run_refresh(&profile_dir, &cookies_path).await {
|
|
||||||
Ok(msg) => tracing::info!("cookie refresh complete: {msg}"),
|
|
||||||
Err(e) => tracing::error!("cookie refresh failed: {e}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_refresh(profile_dir: &Path, cookies_path: &Path) -> Result<String, String> {
|
|
||||||
let script = find_script()?;
|
let script = find_script()?;
|
||||||
|
|
||||||
let output = Command::new("python3")
|
let output = Command::new("python3")
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ pub mod auth;
|
|||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod cookie_refresh;
|
pub mod cookie_refresh;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod mb_update;
|
||||||
pub mod monitor;
|
pub mod monitor;
|
||||||
pub mod pipeline;
|
pub mod pipeline;
|
||||||
pub mod pipeline_scheduler;
|
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
|
pub mod scheduler;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod tasks;
|
pub mod tasks;
|
||||||
|
pub mod workers;
|
||||||
|
|||||||
106
src/main.rs
106
src/main.rs
@@ -5,8 +5,8 @@ use clap::Parser;
|
|||||||
use tracing_actix_web::TracingLogger;
|
use tracing_actix_web::TracingLogger;
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
use shanty_data::MusicBrainzFetcher;
|
|
||||||
use shanty_data::WikipediaFetcher;
|
use shanty_data::WikipediaFetcher;
|
||||||
|
use shanty_data::{HybridMusicBrainzFetcher, LocalMusicBrainzFetcher, MusicBrainzFetcher};
|
||||||
use shanty_db::Database;
|
use shanty_db::Database;
|
||||||
use shanty_search::MusicBrainzSearch;
|
use shanty_search::MusicBrainzSearch;
|
||||||
|
|
||||||
@@ -14,6 +14,7 @@ use shanty_web::config::AppConfig;
|
|||||||
use shanty_web::routes;
|
use shanty_web::routes;
|
||||||
use shanty_web::state::AppState;
|
use shanty_web::state::AppState;
|
||||||
use shanty_web::tasks::TaskManager;
|
use shanty_web::tasks::TaskManager;
|
||||||
|
use shanty_web::workers::WorkerManager;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(name = "shanty-web", about = "Shanty web interface backend")]
|
#[command(name = "shanty-web", about = "Shanty web interface backend")]
|
||||||
@@ -35,18 +36,27 @@ struct Cli {
|
|||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
|
let mut config = AppConfig::load(cli.config.as_deref());
|
||||||
|
|
||||||
let filter = match cli.verbose {
|
let filter = match cli.verbose {
|
||||||
0 => "info,shanty_web=info",
|
0 => {
|
||||||
1 => "info,shanty_web=debug",
|
let level = config.log_level.to_lowercase();
|
||||||
_ => "debug,shanty_web=trace",
|
match level.as_str() {
|
||||||
|
"error" => "error".to_string(),
|
||||||
|
"warn" => "warn".to_string(),
|
||||||
|
"debug" => "debug,shanty_web=debug".to_string(),
|
||||||
|
"trace" => "trace,shanty_web=trace".to_string(),
|
||||||
|
_ => "info,shanty_web=info".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
1 => "info,shanty_web=debug".to_string(),
|
||||||
|
_ => "debug,shanty_web=trace".to_string(),
|
||||||
};
|
};
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(filter)),
|
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&filter)),
|
||||||
)
|
)
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
let mut config = AppConfig::load(cli.config.as_deref());
|
|
||||||
if let Some(port) = cli.port {
|
if let Some(port) = cli.port {
|
||||||
config.web.port = port;
|
config.web.port = port;
|
||||||
}
|
}
|
||||||
@@ -54,8 +64,23 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
tracing::info!(url = %config.database_url, "connecting to database");
|
tracing::info!(url = %config.database_url, "connecting to database");
|
||||||
let db = Database::new(&config.database_url).await?;
|
let db = Database::new(&config.database_url).await?;
|
||||||
|
|
||||||
let mb_client = MusicBrainzFetcher::new()?;
|
let mb_remote = MusicBrainzFetcher::new()?;
|
||||||
let search = MusicBrainzSearch::with_limiter(mb_client.limiter())?;
|
let search = MusicBrainzSearch::with_limiter(mb_remote.limiter())?;
|
||||||
|
|
||||||
|
// Set up local MB database if configured
|
||||||
|
let local_mb = create_local_mb_fetcher(&config);
|
||||||
|
let mb_client = HybridMusicBrainzFetcher::new(local_mb, mb_remote);
|
||||||
|
|
||||||
|
if mb_client.has_local_db()
|
||||||
|
&& let Some(stats) = mb_client.local_stats()
|
||||||
|
{
|
||||||
|
tracing::info!(
|
||||||
|
artists = stats.artists,
|
||||||
|
release_groups = stats.release_groups,
|
||||||
|
"local MusicBrainz database loaded"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let wiki_fetcher = WikipediaFetcher::new()?;
|
let wiki_fetcher = WikipediaFetcher::new()?;
|
||||||
|
|
||||||
let bind = format!("{}:{}", config.web.bind, config.web.port);
|
let bind = format!("{}:{}", config.web.bind, config.web.port);
|
||||||
@@ -70,21 +95,14 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
config: std::sync::Arc::new(tokio::sync::RwLock::new(config)),
|
config: std::sync::Arc::new(tokio::sync::RwLock::new(config)),
|
||||||
config_path,
|
config_path,
|
||||||
tasks: TaskManager::new(),
|
tasks: TaskManager::new(),
|
||||||
|
workers: WorkerManager::new(),
|
||||||
firefox_login: tokio::sync::Mutex::new(None),
|
firefox_login: tokio::sync::Mutex::new(None),
|
||||||
scheduler: tokio::sync::Mutex::new(shanty_web::state::SchedulerInfo {
|
|
||||||
next_pipeline: None,
|
|
||||||
next_monitor: None,
|
|
||||||
skip_pipeline: false,
|
|
||||||
skip_monitor: false,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Start background cookie refresh task
|
// Start work queue workers and unified scheduler
|
||||||
shanty_web::cookie_refresh::spawn(state.config.clone());
|
WorkerManager::spawn_all(state.clone());
|
||||||
|
shanty_web::scheduler::spawn(state.clone());
|
||||||
// Start pipeline and monitor schedulers
|
shanty_web::mb_update::spawn(state.clone());
|
||||||
shanty_web::pipeline_scheduler::spawn(state.clone());
|
|
||||||
shanty_web::monitor::spawn(state.clone());
|
|
||||||
|
|
||||||
// Resolve static files directory relative to the binary location
|
// Resolve static files directory relative to the binary location
|
||||||
let static_dir = std::env::current_exe()
|
let static_dir = std::env::current_exe()
|
||||||
@@ -126,15 +144,24 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
.service(
|
.service(
|
||||||
actix_files::Files::new("/", static_dir.clone())
|
actix_files::Files::new("/", static_dir.clone())
|
||||||
.index_file("index.html")
|
.index_file("index.html")
|
||||||
.prefer_utf8(true),
|
.prefer_utf8(true)
|
||||||
|
.guard(actix_web::guard::fn_guard(|ctx| {
|
||||||
|
!ctx.head().uri.path().starts_with("/rest")
|
||||||
|
})),
|
||||||
)
|
)
|
||||||
// SPA fallback: serve index.html for any route not matched
|
// SPA fallback: serve index.html for any route not matched
|
||||||
// by API or static files, so client-side routing works on refresh
|
// by API or static files, so client-side routing works on refresh.
|
||||||
|
// /rest/* paths get a Subsonic error instead of index.html.
|
||||||
.default_service(web::to({
|
.default_service(web::to({
|
||||||
let index_path = static_dir.join("index.html");
|
let index_path = static_dir.join("index.html");
|
||||||
move |req: actix_web::HttpRequest| {
|
move |req: actix_web::HttpRequest| {
|
||||||
let index_path = index_path.clone();
|
let index_path = index_path.clone();
|
||||||
async move {
|
async move {
|
||||||
|
if req.path().starts_with("/rest") {
|
||||||
|
return Ok(actix_web::HttpResponse::NotFound()
|
||||||
|
.content_type("application/json")
|
||||||
|
.body(r#"{"subsonic-response":{"status":"failed","version":"1.16.1","error":{"code":0,"message":"Unknown endpoint"}}}"#));
|
||||||
|
}
|
||||||
actix_files::NamedFile::open_async(index_path)
|
actix_files::NamedFile::open_async(index_path)
|
||||||
.await
|
.await
|
||||||
.map(|f| f.into_response(&req))
|
.map(|f| f.into_response(&req))
|
||||||
@@ -148,3 +175,36 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create a LocalMusicBrainzFetcher from config if available.
|
||||||
|
fn create_local_mb_fetcher(config: &AppConfig) -> Option<LocalMusicBrainzFetcher> {
|
||||||
|
let db_path = config
|
||||||
|
.musicbrainz
|
||||||
|
.local_db_path
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| p.to_string_lossy().to_string())
|
||||||
|
.or_else(|| {
|
||||||
|
let default_path = shanty_config::data_dir().join("shanty-mb.db");
|
||||||
|
if default_path.exists() {
|
||||||
|
Some(default_path.to_string_lossy().to_string())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
match LocalMusicBrainzFetcher::new(&db_path) {
|
||||||
|
Ok(fetcher) => {
|
||||||
|
if fetcher.is_available() {
|
||||||
|
tracing::info!(path = %db_path, "opened local MusicBrainz database");
|
||||||
|
Some(fetcher)
|
||||||
|
} else {
|
||||||
|
tracing::debug!(path = %db_path, "local MB database exists but has no data");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(path = %db_path, error = %e, "failed to open local MB database");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
120
src/mb_update.rs
Normal file
120
src/mb_update.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
//! Background task that periodically re-imports the MusicBrainz database.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use actix_web::web;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Spawn the weekly MB database update loop.
|
||||||
|
///
|
||||||
|
/// Only runs if a local MB database exists (meaning the user has done an initial import).
|
||||||
|
/// Downloads fresh dumps and re-imports weekly.
|
||||||
|
pub fn spawn(state: web::Data<AppState>) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Wait 1 hour after startup before first check
|
||||||
|
tokio::time::sleep(Duration::from_secs(3600)).await;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Check if local DB exists and auto-update is desired
|
||||||
|
let has_local = state.mb_client.has_local_db();
|
||||||
|
if !has_local {
|
||||||
|
// No local DB — sleep a day and check again
|
||||||
|
tokio::time::sleep(Duration::from_secs(86400)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check how old the import is
|
||||||
|
let needs_update = state
|
||||||
|
.mb_client
|
||||||
|
.local_stats()
|
||||||
|
.and_then(|s| s.last_import_date)
|
||||||
|
.map(|date| {
|
||||||
|
// Parse the date and check if it's older than 7 days
|
||||||
|
chrono::NaiveDate::parse_from_str(&date, "%Y-%m-%d")
|
||||||
|
.map(|d| {
|
||||||
|
let age = chrono::Utc::now().naive_utc().date() - d;
|
||||||
|
age.num_days() >= 7
|
||||||
|
})
|
||||||
|
.unwrap_or(true) // If we can't parse the date, update
|
||||||
|
})
|
||||||
|
.unwrap_or(false); // No stats = no local DB = skip
|
||||||
|
|
||||||
|
if !needs_update {
|
||||||
|
// Check again in 24 hours
|
||||||
|
tokio::time::sleep(Duration::from_secs(86400)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!("starting weekly MusicBrainz database update");
|
||||||
|
|
||||||
|
let data_dir = shanty_config::data_dir().join("mb-dumps");
|
||||||
|
let db_path = state
|
||||||
|
.config
|
||||||
|
.read()
|
||||||
|
.await
|
||||||
|
.musicbrainz
|
||||||
|
.local_db_path
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| shanty_config::data_dir().join("shanty-mb.db"));
|
||||||
|
|
||||||
|
// Download fresh dumps
|
||||||
|
if let Err(e) = std::fs::create_dir_all(&data_dir) {
|
||||||
|
tracing::error!(error = %e, "failed to create dump dir for MB update");
|
||||||
|
tokio::time::sleep(Duration::from_secs(86400)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp = match shanty_data::mb_import::discover_latest_dump_folder().await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(error = %e, "failed to discover latest MB dump");
|
||||||
|
tokio::time::sleep(Duration::from_secs(86400)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut download_failed = false;
|
||||||
|
for filename in shanty_data::mb_import::DUMP_FILES {
|
||||||
|
if let Err(e) =
|
||||||
|
shanty_data::mb_import::download_dump(filename, ×tamp, &data_dir, |msg| {
|
||||||
|
tracing::info!("{msg}");
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(file = filename, error = %e, "MB dump download failed");
|
||||||
|
download_failed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if download_failed {
|
||||||
|
tokio::time::sleep(Duration::from_secs(86400)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run import in blocking task
|
||||||
|
let result = tokio::task::spawn_blocking(move || {
|
||||||
|
shanty_data::mb_import::run_import_at_path(&db_path, &data_dir, |msg| {
|
||||||
|
tracing::info!("{msg}");
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Ok(stats)) => {
|
||||||
|
tracing::info!(%stats, "weekly MusicBrainz update complete");
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
tracing::error!(error = %e, "weekly MusicBrainz import failed");
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(error = %e, "weekly MusicBrainz import task panicked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sleep 7 days before next check
|
||||||
|
tokio::time::sleep(Duration::from_secs(7 * 86400)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
//! and automatically adds them to the watchlist.
|
//! and automatically adds them to the watchlist.
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -197,68 +196,3 @@ pub async fn check_monitored_artists(
|
|||||||
|
|
||||||
Ok(stats)
|
Ok(stats)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn the monitor scheduler background loop.
|
|
||||||
///
|
|
||||||
/// Sleeps for the configured interval, then checks monitored artists if enabled.
|
|
||||||
/// Reads config each iteration so changes take effect without restart.
|
|
||||||
pub fn spawn(state: web::Data<AppState>) {
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
let (enabled, hours) = {
|
|
||||||
let cfg = state.config.read().await;
|
|
||||||
(
|
|
||||||
cfg.scheduling.monitor_enabled,
|
|
||||||
cfg.scheduling.monitor_interval_hours.max(1),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let sleep_secs = u64::from(hours) * 3600;
|
|
||||||
|
|
||||||
// Update next-run time
|
|
||||||
{
|
|
||||||
let mut sched = state.scheduler.lock().await;
|
|
||||||
sched.next_monitor = if enabled {
|
|
||||||
Some(
|
|
||||||
(chrono::Utc::now() + chrono::Duration::seconds(sleep_secs as i64))
|
|
||||||
.naive_utc(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_secs(sleep_secs)).await;
|
|
||||||
|
|
||||||
if !enabled {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this run was skipped
|
|
||||||
{
|
|
||||||
let mut sched = state.scheduler.lock().await;
|
|
||||||
sched.next_monitor = None;
|
|
||||||
if sched.skip_monitor {
|
|
||||||
sched.skip_monitor = false;
|
|
||||||
tracing::info!("scheduled monitor check skipped (user cancelled)");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::info!("scheduled monitor check starting");
|
|
||||||
match check_monitored_artists(&state).await {
|
|
||||||
Ok(stats) => {
|
|
||||||
tracing::info!(
|
|
||||||
artists_checked = stats.artists_checked,
|
|
||||||
new_releases = stats.new_releases_found,
|
|
||||||
tracks_added = stats.tracks_added,
|
|
||||||
"scheduled monitor check complete"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::error!(error = %e, "scheduled monitor check failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
259
src/pipeline.rs
259
src/pipeline.rs
@@ -1,218 +1,67 @@
|
|||||||
//! Shared pipeline logic used by both the API endpoint and the scheduler.
|
//! Pipeline trigger logic. Creates work queue items that flow through the
|
||||||
|
//! Download → Tag → Organize pipeline concurrently via typed workers.
|
||||||
|
|
||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
|
|
||||||
|
use shanty_db::entities::download_queue::DownloadStatus;
|
||||||
|
use shanty_db::entities::work_queue::WorkTaskType;
|
||||||
use shanty_db::queries;
|
use shanty_db::queries;
|
||||||
|
|
||||||
use crate::routes::artists::enrich_all_watched_artists;
|
use crate::error::ApiError;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
|
||||||
/// Register and spawn the full 6-step pipeline. Returns the task IDs immediately.
|
/// Trigger the full pipeline: sync wanted items to download queue, then create
|
||||||
///
|
/// work queue items for each pending download. Returns a pipeline ID for tracking.
|
||||||
/// Steps: sync, download, index, tag, organize, enrich.
|
pub async fn trigger_pipeline(state: &web::Data<AppState>) -> Result<String, ApiError> {
|
||||||
pub fn spawn_pipeline(state: &web::Data<AppState>) -> Vec<String> {
|
let pipeline_id = uuid::Uuid::new_v4().to_string();
|
||||||
let sync_id = state.tasks.register_pending("sync");
|
let conn = state.db.conn();
|
||||||
let download_id = state.tasks.register_pending("download");
|
|
||||||
let index_id = state.tasks.register_pending("index");
|
|
||||||
let tag_id = state.tasks.register_pending("tag");
|
|
||||||
let organize_id = state.tasks.register_pending("organize");
|
|
||||||
let enrich_id = state.tasks.register_pending("enrich");
|
|
||||||
|
|
||||||
let task_ids = vec![
|
// Step 1: Sync wanted items to download queue (fast, just DB inserts)
|
||||||
sync_id.clone(),
|
let sync_stats = shanty_dl::sync_wanted_to_queue(conn, false).await?;
|
||||||
download_id.clone(),
|
tracing::info!(
|
||||||
index_id.clone(),
|
enqueued = sync_stats.enqueued,
|
||||||
tag_id.clone(),
|
skipped = sync_stats.skipped,
|
||||||
organize_id.clone(),
|
pipeline_id = %pipeline_id,
|
||||||
enrich_id.clone(),
|
"pipeline sync complete"
|
||||||
];
|
);
|
||||||
|
|
||||||
|
// Step 2: Create Download work items for each pending download_queue entry
|
||||||
|
let pending = queries::downloads::list(conn, Some(DownloadStatus::Pending)).await?;
|
||||||
|
for dl_item in &pending {
|
||||||
|
let payload = serde_json::json!({"download_queue_id": dl_item.id});
|
||||||
|
queries::work_queue::enqueue(
|
||||||
|
conn,
|
||||||
|
WorkTaskType::Download,
|
||||||
|
&payload.to_string(),
|
||||||
|
Some(&pipeline_id),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !pending.is_empty() {
|
||||||
|
state.workers.notify(WorkTaskType::Download);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
download_items = pending.len(),
|
||||||
|
pipeline_id = %pipeline_id,
|
||||||
|
"pipeline work items created"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(pipeline_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trigger the pipeline and return immediately (for API endpoints).
|
||||||
|
pub fn spawn_pipeline(state: &web::Data<AppState>) -> String {
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
|
let pipeline_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
run_pipeline_inner(
|
match trigger_pipeline(&state).await {
|
||||||
&state,
|
Ok(id) => tracing::info!(pipeline_id = %id, "pipeline triggered"),
|
||||||
&sync_id,
|
Err(e) => tracing::error!(error = %e, "pipeline trigger failed"),
|
||||||
&download_id,
|
}
|
||||||
&index_id,
|
|
||||||
&tag_id,
|
|
||||||
&organize_id,
|
|
||||||
&enrich_id,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
task_ids
|
pipeline_id
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the pipeline without registering tasks (for the scheduler, which logs instead).
|
|
||||||
pub async fn run_pipeline(state: &web::Data<AppState>) -> Vec<String> {
|
|
||||||
let sync_id = state.tasks.register_pending("sync");
|
|
||||||
let download_id = state.tasks.register_pending("download");
|
|
||||||
let index_id = state.tasks.register_pending("index");
|
|
||||||
let tag_id = state.tasks.register_pending("tag");
|
|
||||||
let organize_id = state.tasks.register_pending("organize");
|
|
||||||
let enrich_id = state.tasks.register_pending("enrich");
|
|
||||||
|
|
||||||
let task_ids = vec![
|
|
||||||
sync_id.clone(),
|
|
||||||
download_id.clone(),
|
|
||||||
index_id.clone(),
|
|
||||||
tag_id.clone(),
|
|
||||||
organize_id.clone(),
|
|
||||||
enrich_id.clone(),
|
|
||||||
];
|
|
||||||
|
|
||||||
run_pipeline_inner(
|
|
||||||
state,
|
|
||||||
&sync_id,
|
|
||||||
&download_id,
|
|
||||||
&index_id,
|
|
||||||
&tag_id,
|
|
||||||
&organize_id,
|
|
||||||
&enrich_id,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
task_ids
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_pipeline_inner(
|
|
||||||
state: &web::Data<AppState>,
|
|
||||||
sync_id: &str,
|
|
||||||
download_id: &str,
|
|
||||||
index_id: &str,
|
|
||||||
tag_id: &str,
|
|
||||||
organize_id: &str,
|
|
||||||
enrich_id: &str,
|
|
||||||
) {
|
|
||||||
let cfg = state.config.read().await.clone();
|
|
||||||
|
|
||||||
// Step 1: Sync
|
|
||||||
state.tasks.start(sync_id);
|
|
||||||
state
|
|
||||||
.tasks
|
|
||||||
.update_progress(sync_id, 0, 0, "Syncing watchlist to download queue...");
|
|
||||||
match shanty_dl::sync_wanted_to_queue(state.db.conn(), false).await {
|
|
||||||
Ok(stats) => state.tasks.complete(sync_id, format!("{stats}")),
|
|
||||||
Err(e) => state.tasks.fail(sync_id, e.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 2: Download
|
|
||||||
state.tasks.start(download_id);
|
|
||||||
let cookies = cfg.download.cookies_path.clone();
|
|
||||||
let format: shanty_dl::AudioFormat = cfg
|
|
||||||
.download
|
|
||||||
.format
|
|
||||||
.parse()
|
|
||||||
.unwrap_or(shanty_dl::AudioFormat::Opus);
|
|
||||||
let source: shanty_dl::SearchSource = cfg
|
|
||||||
.download
|
|
||||||
.search_source
|
|
||||||
.parse()
|
|
||||||
.unwrap_or(shanty_dl::SearchSource::YouTubeMusic);
|
|
||||||
let rate = if cookies.is_some() {
|
|
||||||
cfg.download.rate_limit_auth
|
|
||||||
} else {
|
|
||||||
cfg.download.rate_limit
|
|
||||||
};
|
|
||||||
let backend = shanty_dl::YtDlpBackend::new(rate, source, cookies.clone());
|
|
||||||
let backend_config = shanty_dl::BackendConfig {
|
|
||||||
output_dir: cfg.download_path.clone(),
|
|
||||||
format,
|
|
||||||
cookies_path: cookies,
|
|
||||||
};
|
|
||||||
let task_state = state.clone();
|
|
||||||
let progress_tid = download_id.to_string();
|
|
||||||
let on_progress: shanty_dl::ProgressFn = Box::new(move |current, total, msg| {
|
|
||||||
task_state
|
|
||||||
.tasks
|
|
||||||
.update_progress(&progress_tid, current, total, msg);
|
|
||||||
});
|
|
||||||
match shanty_dl::run_queue_with_progress(
|
|
||||||
state.db.conn(),
|
|
||||||
&backend,
|
|
||||||
&backend_config,
|
|
||||||
false,
|
|
||||||
Some(on_progress),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(stats) => {
|
|
||||||
let _ = queries::cache::purge_prefix(state.db.conn(), "artist_totals:").await;
|
|
||||||
state.tasks.complete(download_id, format!("{stats}"));
|
|
||||||
}
|
|
||||||
Err(e) => state.tasks.fail(download_id, e.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 3: Index
|
|
||||||
state.tasks.start(index_id);
|
|
||||||
state
|
|
||||||
.tasks
|
|
||||||
.update_progress(index_id, 0, 0, "Scanning library...");
|
|
||||||
let scan_config = shanty_index::ScanConfig {
|
|
||||||
root: cfg.library_path.clone(),
|
|
||||||
dry_run: false,
|
|
||||||
concurrency: cfg.indexing.concurrency,
|
|
||||||
};
|
|
||||||
match shanty_index::run_scan(state.db.conn(), &scan_config).await {
|
|
||||||
Ok(stats) => state.tasks.complete(index_id, format!("{stats}")),
|
|
||||||
Err(e) => state.tasks.fail(index_id, e.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 4: Tag
|
|
||||||
state.tasks.start(tag_id);
|
|
||||||
state
|
|
||||||
.tasks
|
|
||||||
.update_progress(tag_id, 0, 0, "Tagging tracks...");
|
|
||||||
match shanty_tag::MusicBrainzClient::new() {
|
|
||||||
Ok(mb) => {
|
|
||||||
let tag_config = shanty_tag::TagConfig {
|
|
||||||
dry_run: false,
|
|
||||||
write_tags: cfg.tagging.write_tags,
|
|
||||||
confidence: cfg.tagging.confidence,
|
|
||||||
};
|
|
||||||
match shanty_tag::run_tagging(state.db.conn(), &mb, &tag_config, None).await {
|
|
||||||
Ok(stats) => state.tasks.complete(tag_id, format!("{stats}")),
|
|
||||||
Err(e) => state.tasks.fail(tag_id, e.to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => state.tasks.fail(tag_id, e.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 5: Organize
|
|
||||||
state.tasks.start(organize_id);
|
|
||||||
state
|
|
||||||
.tasks
|
|
||||||
.update_progress(organize_id, 0, 0, "Organizing files...");
|
|
||||||
let org_config = shanty_org::OrgConfig {
|
|
||||||
target_dir: cfg.library_path.clone(),
|
|
||||||
format: cfg.organization_format.clone(),
|
|
||||||
dry_run: false,
|
|
||||||
copy: false,
|
|
||||||
};
|
|
||||||
match shanty_org::organize_from_db(state.db.conn(), &org_config).await {
|
|
||||||
Ok(stats) => {
|
|
||||||
let promoted = queries::wanted::promote_downloaded_to_owned(state.db.conn())
|
|
||||||
.await
|
|
||||||
.unwrap_or(0);
|
|
||||||
let msg = if promoted > 0 {
|
|
||||||
format!("{stats} — {promoted} items marked as owned")
|
|
||||||
} else {
|
|
||||||
format!("{stats}")
|
|
||||||
};
|
|
||||||
state.tasks.complete(organize_id, msg);
|
|
||||||
}
|
|
||||||
Err(e) => state.tasks.fail(organize_id, e.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 6: Enrich
|
|
||||||
state.tasks.start(enrich_id);
|
|
||||||
state
|
|
||||||
.tasks
|
|
||||||
.update_progress(enrich_id, 0, 0, "Refreshing artist data...");
|
|
||||||
match enrich_all_watched_artists(state).await {
|
|
||||||
Ok(count) => state
|
|
||||||
.tasks
|
|
||||||
.complete(enrich_id, format!("{count} artists refreshed")),
|
|
||||||
Err(e) => state.tasks.fail(enrich_id, e.to_string()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
//! Background task that runs the full pipeline on a configurable interval.
|
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use actix_web::web;
|
|
||||||
use chrono::Utc;
|
|
||||||
|
|
||||||
use crate::state::AppState;
|
|
||||||
|
|
||||||
/// Spawn the pipeline scheduler background loop.
|
|
||||||
///
|
|
||||||
/// Sleeps for the configured interval, then runs the full pipeline if enabled.
|
|
||||||
/// Reads config each iteration so changes take effect without restart.
|
|
||||||
pub fn spawn(state: web::Data<AppState>) {
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
let (enabled, hours) = {
|
|
||||||
let cfg = state.config.read().await;
|
|
||||||
(
|
|
||||||
cfg.scheduling.pipeline_enabled,
|
|
||||||
cfg.scheduling.pipeline_interval_hours.max(1),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let sleep_secs = u64::from(hours) * 3600;
|
|
||||||
|
|
||||||
// Update next-run time
|
|
||||||
{
|
|
||||||
let mut sched = state.scheduler.lock().await;
|
|
||||||
sched.next_pipeline = if enabled {
|
|
||||||
Some((Utc::now() + chrono::Duration::seconds(sleep_secs as i64)).naive_utc())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_secs(sleep_secs)).await;
|
|
||||||
|
|
||||||
if !enabled {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this run was skipped
|
|
||||||
{
|
|
||||||
let mut sched = state.scheduler.lock().await;
|
|
||||||
sched.next_pipeline = None;
|
|
||||||
if sched.skip_pipeline {
|
|
||||||
sched.skip_pipeline = false;
|
|
||||||
tracing::info!("scheduled pipeline skipped (user cancelled)");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::info!("scheduled pipeline starting");
|
|
||||||
let task_ids = crate::pipeline::run_pipeline(&state).await;
|
|
||||||
tracing::info!(?task_ids, "scheduled pipeline complete");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -192,13 +192,30 @@ async fn get_cached_album_tracks(
|
|||||||
// Not cached — resolve release MBID and fetch tracks
|
// Not cached — resolve release MBID and fetch tracks
|
||||||
let release_mbid = if let Some(rid) = first_release_id {
|
let release_mbid = if let Some(rid) = first_release_id {
|
||||||
rid.to_string()
|
rid.to_string()
|
||||||
|
} else {
|
||||||
|
// Check DB cache for previously resolved release MBID
|
||||||
|
let resolve_cache_key = format!("release_for_rg:{rg_id}");
|
||||||
|
if let Ok(Some(cached_rid)) = queries::cache::get(state.db.conn(), &resolve_cache_key).await
|
||||||
|
{
|
||||||
|
cached_rid
|
||||||
} else {
|
} else {
|
||||||
// Browse releases for this release group (through shared rate limiter)
|
// Browse releases for this release group (through shared rate limiter)
|
||||||
state
|
let rid = state
|
||||||
.mb_client
|
.mb_client
|
||||||
.resolve_release_from_group(rg_id)
|
.resolve_release_from_group(rg_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ApiError::Internal(format!("MB error for group {rg_id}: {e}")))?
|
.map_err(|e| ApiError::Internal(format!("MB error for group {rg_id}: {e}")))?;
|
||||||
|
// Cache the resolved release MBID for 365 days — it never changes
|
||||||
|
let _ = queries::cache::set(
|
||||||
|
state.db.conn(),
|
||||||
|
&resolve_cache_key,
|
||||||
|
"musicbrainz",
|
||||||
|
&rid,
|
||||||
|
365 * 86400,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
rid
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mb_tracks = state
|
let mb_tracks = state
|
||||||
@@ -259,7 +276,8 @@ pub async fn enrich_artist(
|
|||||||
quick_mode: bool,
|
quick_mode: bool,
|
||||||
) -> Result<serde_json::Value, ApiError> {
|
) -> Result<serde_json::Value, ApiError> {
|
||||||
// Resolve artist: local ID or MBID
|
// Resolve artist: local ID or MBID
|
||||||
let (artist, id, mbid) = if let Ok(local_id) = id_or_mbid.parse() {
|
// Track whether we already fetched artist info during resolution to avoid a duplicate API call
|
||||||
|
let (artist, id, mbid, prefetched_info) = if let Ok(local_id) = id_or_mbid.parse() {
|
||||||
let artist = queries::artists::get_by_id(state.db.conn(), local_id).await?;
|
let artist = queries::artists::get_by_id(state.db.conn(), local_id).await?;
|
||||||
let mbid = match &artist.musicbrainz_id {
|
let mbid = match &artist.musicbrainz_id {
|
||||||
Some(m) => m.clone(),
|
Some(m) => m.clone(),
|
||||||
@@ -274,7 +292,7 @@ pub async fn enrich_artist(
|
|||||||
})?
|
})?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
(artist, Some(local_id), mbid)
|
(artist, Some(local_id), mbid, None)
|
||||||
} else {
|
} else {
|
||||||
let mbid = id_or_mbid.to_string();
|
let mbid = id_or_mbid.to_string();
|
||||||
|
|
||||||
@@ -288,9 +306,10 @@ pub async fn enrich_artist(
|
|||||||
|
|
||||||
if let Some(a) = local {
|
if let Some(a) = local {
|
||||||
let local_id = a.id;
|
let local_id = a.id;
|
||||||
(a, Some(local_id), mbid)
|
(a, Some(local_id), mbid, None)
|
||||||
} else {
|
} else {
|
||||||
// Look up artist info from MusicBrainz by MBID — don't create a local record
|
// Look up artist info from MusicBrainz by MBID — don't create a local record
|
||||||
|
// This fetches url-rels too, so we reuse it below instead of calling get_artist_info() again
|
||||||
let info =
|
let info =
|
||||||
state.mb_client.get_artist_info(&mbid).await.map_err(|e| {
|
state.mb_client.get_artist_info(&mbid).await.map_err(|e| {
|
||||||
ApiError::NotFound(format!("artist MBID {mbid} not found: {e}"))
|
ApiError::NotFound(format!("artist MBID {mbid} not found: {e}"))
|
||||||
@@ -307,12 +326,21 @@ pub async fn enrich_artist(
|
|||||||
monitored: false,
|
monitored: false,
|
||||||
last_checked_at: None,
|
last_checked_at: None,
|
||||||
};
|
};
|
||||||
(synthetic, None, mbid)
|
(synthetic, None, mbid, Some(info))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch detailed artist info (country, type, URLs) — best-effort
|
// Fetch detailed artist info (country, type, URLs) — reuse if already fetched during resolution
|
||||||
let artist_info = match state.mb_client.get_artist_info(&mbid).await {
|
let artist_info = if let Some(info) = prefetched_info {
|
||||||
|
tracing::debug!(
|
||||||
|
mbid = %mbid,
|
||||||
|
urls = info.urls.len(),
|
||||||
|
country = ?info.country,
|
||||||
|
"reusing prefetched artist info"
|
||||||
|
);
|
||||||
|
Some(info)
|
||||||
|
} else {
|
||||||
|
match state.mb_client.get_artist_info(&mbid).await {
|
||||||
Ok(info) => {
|
Ok(info) => {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
mbid = %mbid,
|
mbid = %mbid,
|
||||||
@@ -326,6 +354,7 @@ pub async fn enrich_artist(
|
|||||||
tracing::warn!(mbid = %mbid, error = %e, "failed to fetch artist info");
|
tracing::warn!(mbid = %mbid, error = %e, "failed to fetch artist info");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch artist photo + bio + banner (cached, provider-aware)
|
// Fetch artist photo + bio + banner (cached, provider-aware)
|
||||||
|
|||||||
@@ -20,7 +20,14 @@ pub fn configure(cfg: &mut web::ServiceConfig) {
|
|||||||
.route(web::get().to(list_users))
|
.route(web::get().to(list_users))
|
||||||
.route(web::post().to(create_user)),
|
.route(web::post().to(create_user)),
|
||||||
)
|
)
|
||||||
.service(web::resource("/auth/users/{id}").route(web::delete().to(delete_user)));
|
.service(web::resource("/auth/users/{id}").route(web::delete().to(delete_user)))
|
||||||
|
.service(
|
||||||
|
web::resource("/auth/subsonic-password").route(web::put().to(set_subsonic_password)),
|
||||||
|
)
|
||||||
|
.service(
|
||||||
|
web::resource("/auth/subsonic-password-status")
|
||||||
|
.route(web::get().to(subsonic_password_status)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -41,6 +48,11 @@ struct CreateUserRequest {
|
|||||||
password: String,
|
password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct SubsonicPasswordRequest {
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if initial setup is required (no users in database).
|
/// Check if initial setup is required (no users in database).
|
||||||
async fn setup_required(state: web::Data<AppState>) -> Result<HttpResponse, ApiError> {
|
async fn setup_required(state: web::Data<AppState>) -> Result<HttpResponse, ApiError> {
|
||||||
let count = queries::users::count(state.db.conn()).await?;
|
let count = queries::users::count(state.db.conn()).await?;
|
||||||
@@ -205,3 +217,34 @@ async fn delete_user(
|
|||||||
tracing::info!(user_id = user_id, "user deleted by admin");
|
tracing::info!(user_id = user_id, "user deleted by admin");
|
||||||
Ok(HttpResponse::NoContent().finish())
|
Ok(HttpResponse::NoContent().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set the Subsonic password for the current user.
|
||||||
|
async fn set_subsonic_password(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
session: Session,
|
||||||
|
body: web::Json<SubsonicPasswordRequest>,
|
||||||
|
) -> Result<HttpResponse, ApiError> {
|
||||||
|
let (user_id, _, _) = auth::require_auth(&session)?;
|
||||||
|
|
||||||
|
if body.password.len() < 4 {
|
||||||
|
return Err(ApiError::BadRequest(
|
||||||
|
"password must be at least 4 characters".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
queries::users::set_subsonic_password(state.db.conn(), user_id, &body.password).await?;
|
||||||
|
tracing::info!(user_id = user_id, "subsonic password set");
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({ "status": "ok" })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether the current user has a Subsonic password set.
|
||||||
|
async fn subsonic_password_status(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
session: Session,
|
||||||
|
) -> Result<HttpResponse, ApiError> {
|
||||||
|
let (user_id, _, _) = auth::require_auth(&session)?;
|
||||||
|
let user = queries::users::get_by_id(state.db.conn(), user_id).await?;
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({
|
||||||
|
"set": user.subsonic_password.is_some(),
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ pub mod downloads;
|
|||||||
pub mod lyrics;
|
pub mod lyrics;
|
||||||
pub mod playlists;
|
pub mod playlists;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
|
pub mod subsonic;
|
||||||
pub mod system;
|
pub mod system;
|
||||||
pub mod tracks;
|
pub mod tracks;
|
||||||
pub mod ytauth;
|
pub mod ytauth;
|
||||||
@@ -25,4 +26,6 @@ pub fn configure(cfg: &mut web::ServiceConfig) {
|
|||||||
.configure(ytauth::configure)
|
.configure(ytauth::configure)
|
||||||
.configure(playlists::configure),
|
.configure(playlists::configure),
|
||||||
);
|
);
|
||||||
|
// Subsonic API at /rest/*
|
||||||
|
subsonic::configure(cfg);
|
||||||
}
|
}
|
||||||
|
|||||||
42
src/routes/subsonic/annotation.rs
Normal file
42
src/routes/subsonic/annotation.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::{authenticate, get_query_param, parse_subsonic_id};
|
||||||
|
use super::response;
|
||||||
|
|
||||||
|
/// GET /rest/scrobble[.view]
|
||||||
|
pub async fn scrobble(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (prefix, entity_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "invalid id");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Log the scrobble for now; full play tracking can be added later
|
||||||
|
tracing::info!(
|
||||||
|
user = %user.username,
|
||||||
|
id_type = prefix,
|
||||||
|
id = entity_id,
|
||||||
|
"subsonic scrobble"
|
||||||
|
);
|
||||||
|
|
||||||
|
response::ok(¶ms.format, serde_json::json!({}))
|
||||||
|
}
|
||||||
126
src/routes/subsonic/auth.rs
Normal file
126
src/routes/subsonic/auth.rs
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
use actix_web::HttpRequest;
|
||||||
|
use md5::{Digest, Md5};
|
||||||
|
use sea_orm::DatabaseConnection;
|
||||||
|
|
||||||
|
use shanty_db::entities::user::Model as User;
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
/// Subsonic authentication method.
|
||||||
|
pub enum AuthMethod {
|
||||||
|
/// Modern: token = md5(password + salt)
|
||||||
|
Token { token: String, salt: String },
|
||||||
|
/// Legacy: plaintext password
|
||||||
|
Password(String),
|
||||||
|
/// Legacy: hex-encoded password (p=enc:hexstring)
|
||||||
|
HexPassword(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Common Subsonic API parameters extracted from the query string.
|
||||||
|
pub struct SubsonicParams {
|
||||||
|
/// Username
|
||||||
|
pub username: String,
|
||||||
|
/// Authentication method + credentials
|
||||||
|
pub auth: AuthMethod,
|
||||||
|
/// API version requested
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub version: String,
|
||||||
|
/// Client name
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub client: String,
|
||||||
|
/// Response format: "xml" or "json"
|
||||||
|
pub format: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum SubsonicAuthError {
|
||||||
|
MissingParam(String),
|
||||||
|
AuthFailed,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SubsonicParams {
|
||||||
|
/// Extract Subsonic params from the query string.
|
||||||
|
pub fn from_request(req: &HttpRequest) -> Result<Self, SubsonicAuthError> {
|
||||||
|
let qs = req.query_string();
|
||||||
|
let params: Vec<(String, String)> = serde_urlencoded::from_str(qs).unwrap_or_default();
|
||||||
|
|
||||||
|
let get = |name: &str| -> Option<String> {
|
||||||
|
params
|
||||||
|
.iter()
|
||||||
|
.find(|(k, _)| k == name)
|
||||||
|
.map(|(_, v)| v.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
let username = get("u").ok_or_else(|| SubsonicAuthError::MissingParam("u".into()))?;
|
||||||
|
let version = get("v").unwrap_or_else(|| "1.16.1".into());
|
||||||
|
let client = get("c").unwrap_or_else(|| "unknown".into());
|
||||||
|
let format = get("f").unwrap_or_else(|| "xml".into());
|
||||||
|
|
||||||
|
// Try token auth first (modern), then legacy password
|
||||||
|
let auth = if let (Some(token), Some(salt)) = (get("t"), get("s")) {
|
||||||
|
AuthMethod::Token { token, salt }
|
||||||
|
} else if let Some(p) = get("p") {
|
||||||
|
if let Some(hex_str) = p.strip_prefix("enc:") {
|
||||||
|
AuthMethod::HexPassword(hex_str.to_string())
|
||||||
|
} else {
|
||||||
|
AuthMethod::Password(p)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err(SubsonicAuthError::MissingParam(
|
||||||
|
"authentication required (t+s or p)".into(),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
username,
|
||||||
|
auth,
|
||||||
|
version,
|
||||||
|
client,
|
||||||
|
format,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verify Subsonic authentication against the stored subsonic_password.
|
||||||
|
pub async fn verify_auth(
|
||||||
|
db: &DatabaseConnection,
|
||||||
|
params: &SubsonicParams,
|
||||||
|
) -> Result<User, SubsonicAuthError> {
|
||||||
|
let user = queries::users::find_by_username(db, ¶ms.username)
|
||||||
|
.await
|
||||||
|
.map_err(|_| SubsonicAuthError::AuthFailed)?
|
||||||
|
.ok_or(SubsonicAuthError::AuthFailed)?;
|
||||||
|
|
||||||
|
let subsonic_password = user
|
||||||
|
.subsonic_password
|
||||||
|
.as_deref()
|
||||||
|
.ok_or(SubsonicAuthError::AuthFailed)?;
|
||||||
|
|
||||||
|
match ¶ms.auth {
|
||||||
|
AuthMethod::Token { token, salt } => {
|
||||||
|
// Compute md5(password + salt) and compare
|
||||||
|
let mut hasher = Md5::new();
|
||||||
|
hasher.update(subsonic_password.as_bytes());
|
||||||
|
hasher.update(salt.as_bytes());
|
||||||
|
let result = hasher.finalize();
|
||||||
|
let expected = hex::encode(result);
|
||||||
|
if expected != *token {
|
||||||
|
return Err(SubsonicAuthError::AuthFailed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AuthMethod::Password(password) => {
|
||||||
|
// Direct plaintext comparison
|
||||||
|
if password != subsonic_password {
|
||||||
|
return Err(SubsonicAuthError::AuthFailed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AuthMethod::HexPassword(hex_str) => {
|
||||||
|
// Decode hex to string, compare
|
||||||
|
let decoded = hex::decode(hex_str).map_err(|_| SubsonicAuthError::AuthFailed)?;
|
||||||
|
let password = String::from_utf8(decoded).map_err(|_| SubsonicAuthError::AuthFailed)?;
|
||||||
|
if password != subsonic_password {
|
||||||
|
return Err(SubsonicAuthError::AuthFailed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
589
src/routes/subsonic/browsing.rs
Normal file
589
src/routes/subsonic/browsing.rs
Normal file
@@ -0,0 +1,589 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::{authenticate, get_query_param, parse_subsonic_id};
|
||||||
|
use super::response::{self, SubsonicChild};
|
||||||
|
|
||||||
|
/// GET /rest/getMusicFolders[.view]
|
||||||
|
pub async fn get_music_folders(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"musicFolders": {
|
||||||
|
"musicFolder": [
|
||||||
|
{ "id": 1, "name": "Music" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getArtists[.view]
|
||||||
|
pub async fn get_artists(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let artists = match queries::artists::list(state.db.conn(), 10000, 0).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_GENERIC,
|
||||||
|
&format!("database error: {e}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Group artists by first letter for the index
|
||||||
|
let mut index_map: BTreeMap<String, Vec<serde_json::Value>> = BTreeMap::new();
|
||||||
|
for artist in &artists {
|
||||||
|
let first_char = artist
|
||||||
|
.name
|
||||||
|
.chars()
|
||||||
|
.next()
|
||||||
|
.unwrap_or('#')
|
||||||
|
.to_uppercase()
|
||||||
|
.next()
|
||||||
|
.unwrap_or('#');
|
||||||
|
let key = if first_char.is_alphabetic() {
|
||||||
|
first_char.to_string()
|
||||||
|
} else {
|
||||||
|
"#".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Count albums for this artist
|
||||||
|
let album_count = queries::albums::get_by_artist(state.db.conn(), artist.id)
|
||||||
|
.await
|
||||||
|
.map(|a| a.len())
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
index_map.entry(key).or_default().push(serde_json::json!({
|
||||||
|
"id": format!("ar-{}", artist.id),
|
||||||
|
"name": artist.name,
|
||||||
|
"albumCount": album_count,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let indices: Vec<serde_json::Value> = index_map
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, artists)| {
|
||||||
|
serde_json::json!({
|
||||||
|
"name": name,
|
||||||
|
"artist": artists,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"artists": {
|
||||||
|
"ignoredArticles": "The El La Los Las Le Les",
|
||||||
|
"index": indices,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getArtist[.view]
|
||||||
|
pub async fn get_artist(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, artist_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"invalid artist id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let artist = match queries::artists::get_by_id(state.db.conn(), artist_id).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"artist not found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let albums = queries::albums::get_by_artist(state.db.conn(), artist_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut album_list: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for album in &albums {
|
||||||
|
let track_count = queries::tracks::get_by_album(state.db.conn(), album.id)
|
||||||
|
.await
|
||||||
|
.map(|t| t.len())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let duration: i32 = queries::tracks::get_by_album(state.db.conn(), album.id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.duration.map(|d| d as i32))
|
||||||
|
.sum();
|
||||||
|
let mut album_json = serde_json::json!({
|
||||||
|
"id": format!("al-{}", album.id),
|
||||||
|
"name": album.name,
|
||||||
|
"title": album.name,
|
||||||
|
"artist": if album.album_artist.is_empty() { &artist.name } else { &album.album_artist },
|
||||||
|
"artistId": format!("ar-{}", artist.id),
|
||||||
|
"coverArt": format!("al-{}", album.id),
|
||||||
|
"songCount": track_count,
|
||||||
|
"duration": duration,
|
||||||
|
"created": "2024-01-01T00:00:00",
|
||||||
|
});
|
||||||
|
// Only include year/genre if present (avoid nulls)
|
||||||
|
if let Some(year) = album.year {
|
||||||
|
album_json["year"] = serde_json::json!(year);
|
||||||
|
}
|
||||||
|
if let Some(ref genre) = album.genre {
|
||||||
|
album_json["genre"] = serde_json::json!(genre);
|
||||||
|
}
|
||||||
|
album_list.push(album_json);
|
||||||
|
}
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"artist": {
|
||||||
|
"id": format!("ar-{}", artist.id),
|
||||||
|
"name": artist.name,
|
||||||
|
"albumCount": albums.len(),
|
||||||
|
"album": album_list,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getAlbum[.view]
|
||||||
|
pub async fn get_album(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, album_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"invalid album id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let album = match queries::albums::get_by_id(state.db.conn(), album_id).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "album not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let tracks = queries::tracks::get_by_album(state.db.conn(), album_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let total_duration: i32 = tracks
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.duration.map(|d| d as i32))
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
let song_list: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.map(|track| serde_json::to_value(SubsonicChild::from_track(track)).unwrap_or_default())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut album_json = serde_json::json!({
|
||||||
|
"id": format!("al-{}", album.id),
|
||||||
|
"name": album.name,
|
||||||
|
"title": album.name,
|
||||||
|
"artist": album.album_artist,
|
||||||
|
"artistId": album.artist_id.map(|id| format!("ar-{id}")),
|
||||||
|
"coverArt": format!("al-{}", album.id),
|
||||||
|
"songCount": tracks.len(),
|
||||||
|
"duration": total_duration,
|
||||||
|
"created": "2024-01-01T00:00:00",
|
||||||
|
"song": song_list,
|
||||||
|
});
|
||||||
|
if let Some(year) = album.year {
|
||||||
|
album_json["year"] = serde_json::json!(year);
|
||||||
|
}
|
||||||
|
if let Some(ref genre) = album.genre {
|
||||||
|
album_json["genre"] = serde_json::json!(genre);
|
||||||
|
}
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"album": album_json,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getSong[.view]
|
||||||
|
pub async fn get_song(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, track_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "invalid song id");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let track = match queries::tracks::get_by_id(state.db.conn(), track_id).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "song not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let child = SubsonicChild::from_track(&track);
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"song": serde_json::to_value(child).unwrap_or_default(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getGenres[.view]
|
||||||
|
pub async fn get_genres(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get all tracks and extract unique genres
|
||||||
|
let tracks = queries::tracks::list(state.db.conn(), 100_000, 0)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut genre_counts: BTreeMap<String, (u64, u64)> = BTreeMap::new();
|
||||||
|
for track in &tracks {
|
||||||
|
if let Some(ref genre) = track.genre {
|
||||||
|
let entry = genre_counts.entry(genre.clone()).or_insert((0, 0));
|
||||||
|
entry.0 += 1; // song count
|
||||||
|
// album count is approximated - we count unique album_ids per genre
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also count album_ids per genre
|
||||||
|
let mut genre_albums: BTreeMap<String, std::collections::HashSet<i32>> = BTreeMap::new();
|
||||||
|
for track in &tracks {
|
||||||
|
if let Some(ref genre) = track.genre
|
||||||
|
&& let Some(album_id) = track.album_id
|
||||||
|
{
|
||||||
|
genre_albums
|
||||||
|
.entry(genre.clone())
|
||||||
|
.or_default()
|
||||||
|
.insert(album_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let genre_list: Vec<serde_json::Value> = genre_counts
|
||||||
|
.iter()
|
||||||
|
.map(|(name, (song_count, _))| {
|
||||||
|
let album_count = genre_albums.get(name).map(|s| s.len()).unwrap_or(0);
|
||||||
|
serde_json::json!({
|
||||||
|
"songCount": song_count,
|
||||||
|
"albumCount": album_count,
|
||||||
|
"value": name,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"genres": {
|
||||||
|
"genre": genre_list,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getIndexes[.view] — folder-based browsing (same data as getArtists).
|
||||||
|
pub async fn get_indexes(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let artists = match queries::artists::list(state.db.conn(), 10000, 0).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_GENERIC,
|
||||||
|
&format!("database error: {e}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut index_map: BTreeMap<String, Vec<serde_json::Value>> = BTreeMap::new();
|
||||||
|
for artist in &artists {
|
||||||
|
let first_char = artist
|
||||||
|
.name
|
||||||
|
.chars()
|
||||||
|
.next()
|
||||||
|
.unwrap_or('#')
|
||||||
|
.to_uppercase()
|
||||||
|
.next()
|
||||||
|
.unwrap_or('#');
|
||||||
|
let key = if first_char.is_alphabetic() {
|
||||||
|
first_char.to_string()
|
||||||
|
} else {
|
||||||
|
"#".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
index_map.entry(key).or_default().push(serde_json::json!({
|
||||||
|
"id": format!("ar-{}", artist.id),
|
||||||
|
"name": artist.name,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let indices: Vec<serde_json::Value> = index_map
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, artists)| {
|
||||||
|
serde_json::json!({
|
||||||
|
"name": name,
|
||||||
|
"artist": artists,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"indexes": {
|
||||||
|
"ignoredArticles": "The El La Los Las Le Les",
|
||||||
|
"index": indices,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getMusicDirectory[.view] — returns children of a directory.
|
||||||
|
/// For artist IDs (ar-N): returns albums as children.
|
||||||
|
/// For album IDs (al-N): returns tracks as children.
|
||||||
|
pub async fn get_music_directory(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (prefix, db_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "invalid id");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match prefix {
|
||||||
|
"ar" => {
|
||||||
|
// Artist directory → list albums
|
||||||
|
let artist = match queries::artists::get_by_id(state.db.conn(), db_id).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"artist not found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let albums = queries::albums::get_by_artist(state.db.conn(), db_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let children: Vec<serde_json::Value> = albums
|
||||||
|
.iter()
|
||||||
|
.map(|album| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": format!("al-{}", album.id),
|
||||||
|
"parent": format!("ar-{}", artist.id),
|
||||||
|
"isDir": true,
|
||||||
|
"title": album.name,
|
||||||
|
"artist": album.album_artist,
|
||||||
|
"coverArt": format!("al-{}", album.id),
|
||||||
|
"year": album.year,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"directory": {
|
||||||
|
"id": id_str,
|
||||||
|
"name": artist.name,
|
||||||
|
"child": children,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"al" => {
|
||||||
|
// Album directory → list tracks
|
||||||
|
let album = match queries::albums::get_by_id(state.db.conn(), db_id).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"album not found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let tracks = queries::tracks::get_by_album(state.db.conn(), db_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let children: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.map(|t| serde_json::to_value(SubsonicChild::from_track(t)).unwrap_or_default())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"directory": {
|
||||||
|
"id": id_str,
|
||||||
|
"name": album.name,
|
||||||
|
"parent": album.artist_id.map(|id| format!("ar-{id}")),
|
||||||
|
"child": children,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"unknown" => {
|
||||||
|
// Plain numeric ID — try artist first, then album
|
||||||
|
if let Ok(artist) = queries::artists::get_by_id(state.db.conn(), db_id).await {
|
||||||
|
let albums = queries::albums::get_by_artist(state.db.conn(), db_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let children: Vec<serde_json::Value> = albums
|
||||||
|
.iter()
|
||||||
|
.map(|album| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": format!("al-{}", album.id),
|
||||||
|
"parent": format!("ar-{}", artist.id),
|
||||||
|
"isDir": true,
|
||||||
|
"title": album.name,
|
||||||
|
"artist": album.album_artist,
|
||||||
|
"coverArt": format!("al-{}", album.id),
|
||||||
|
"year": album.year,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"directory": {
|
||||||
|
"id": id_str,
|
||||||
|
"name": artist.name,
|
||||||
|
"child": children,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
} else if let Ok(album) = queries::albums::get_by_id(state.db.conn(), db_id).await {
|
||||||
|
let tracks = queries::tracks::get_by_album(state.db.conn(), db_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let children: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.map(|t| serde_json::to_value(SubsonicChild::from_track(t)).unwrap_or_default())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"directory": {
|
||||||
|
"id": id_str,
|
||||||
|
"name": album.name,
|
||||||
|
"parent": album.artist_id.map(|id| format!("ar-{id}")),
|
||||||
|
"child": children,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
response::error(¶ms.format, response::ERROR_NOT_FOUND, "not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => response::error(¶ms.format, response::ERROR_NOT_FOUND, "unknown id type"),
|
||||||
|
}
|
||||||
|
}
|
||||||
70
src/routes/subsonic/helpers.rs
Normal file
70
src/routes/subsonic/helpers.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use shanty_db::entities::user::Model as User;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::auth::{SubsonicAuthError, SubsonicParams, verify_auth};
|
||||||
|
use super::response;
|
||||||
|
|
||||||
|
/// Extract and authenticate subsonic params, returning an error HttpResponse on failure.
|
||||||
|
pub async fn authenticate(
|
||||||
|
req: &HttpRequest,
|
||||||
|
state: &web::Data<AppState>,
|
||||||
|
) -> Result<(SubsonicParams, User), HttpResponse> {
|
||||||
|
tracing::debug!(
|
||||||
|
path = req.path(),
|
||||||
|
query = req.query_string(),
|
||||||
|
"subsonic request"
|
||||||
|
);
|
||||||
|
|
||||||
|
let params = SubsonicParams::from_request(req).map_err(|e| match e {
|
||||||
|
SubsonicAuthError::MissingParam(name) => response::error(
|
||||||
|
"xml",
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
&format!("missing required parameter: {name}"),
|
||||||
|
),
|
||||||
|
SubsonicAuthError::AuthFailed => response::error(
|
||||||
|
"xml",
|
||||||
|
response::ERROR_NOT_AUTHENTICATED,
|
||||||
|
"wrong username or password",
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let user = verify_auth(state.db.conn(), ¶ms)
|
||||||
|
.await
|
||||||
|
.map_err(|e| match e {
|
||||||
|
SubsonicAuthError::AuthFailed => response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_AUTHENTICATED,
|
||||||
|
"wrong username or password",
|
||||||
|
),
|
||||||
|
SubsonicAuthError::MissingParam(name) => response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
&format!("missing required parameter: {name}"),
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok((params, user))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a Subsonic ID like "ar-123" into (prefix, id).
|
||||||
|
/// Also accepts plain numbers (e.g., "123") — returns prefix "unknown".
|
||||||
|
pub fn parse_subsonic_id(id: &str) -> Option<(&str, i32)> {
|
||||||
|
if let Some((prefix, num_str)) = id.split_once('-') {
|
||||||
|
let num = num_str.parse().ok()?;
|
||||||
|
Some((prefix, num))
|
||||||
|
} else {
|
||||||
|
// Plain number — no prefix
|
||||||
|
let num = id.parse().ok()?;
|
||||||
|
Some(("unknown", num))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a query parameter by name from the request.
|
||||||
|
pub fn get_query_param(req: &HttpRequest, name: &str) -> Option<String> {
|
||||||
|
let qs = req.query_string();
|
||||||
|
let params: Vec<(String, String)> = serde_urlencoded::from_str(qs).unwrap_or_default();
|
||||||
|
params.into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
|
||||||
|
}
|
||||||
312
src/routes/subsonic/media.rs
Normal file
312
src/routes/subsonic/media.rs
Normal file
@@ -0,0 +1,312 @@
|
|||||||
|
use actix_files::NamedFile;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
use tokio::process::Command;
|
||||||
|
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::{authenticate, get_query_param, parse_subsonic_id};
|
||||||
|
use super::response;
|
||||||
|
|
||||||
|
/// GET /rest/stream[.view]
|
||||||
|
pub async fn stream(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, track_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "invalid song id");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let track = match queries::tracks::get_by_id(state.db.conn(), track_id).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "song not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let file_ext = std::path::Path::new(&track.file_path)
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_lowercase();
|
||||||
|
|
||||||
|
let requested_format = get_query_param(&req, "format");
|
||||||
|
let max_bit_rate = get_query_param(&req, "maxBitRate")
|
||||||
|
.and_then(|s| s.parse::<u32>().ok())
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
// Determine if transcoding is needed:
|
||||||
|
// - Client explicitly requests a different format
|
||||||
|
// - File is opus/ogg (many mobile clients can't play these natively)
|
||||||
|
// - Client requests a specific bitrate
|
||||||
|
let needs_transcode = match requested_format.as_deref() {
|
||||||
|
Some("raw") => false, // Explicitly asked for no transcoding
|
||||||
|
Some(fmt) if fmt != file_ext => true, // Different format requested
|
||||||
|
_ => {
|
||||||
|
// Auto-transcode opus/ogg to mp3 since many clients don't support them
|
||||||
|
matches!(file_ext.as_str(), "opus" | "ogg") || (max_bit_rate > 0 && max_bit_rate < 320)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check file exists before doing anything
|
||||||
|
if !std::path::Path::new(&track.file_path).exists() {
|
||||||
|
tracing::error!(path = %track.file_path, "track file not found on disk");
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
&format!("file not found: {}", track.file_path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if needs_transcode {
|
||||||
|
let target_format = requested_format
|
||||||
|
.as_deref()
|
||||||
|
.filter(|f| *f != "raw")
|
||||||
|
.unwrap_or("mp3");
|
||||||
|
let bitrate = if max_bit_rate > 0 {
|
||||||
|
max_bit_rate
|
||||||
|
} else {
|
||||||
|
192 // Default transcoding bitrate
|
||||||
|
};
|
||||||
|
|
||||||
|
let content_type = match target_format {
|
||||||
|
"mp3" => "audio/mpeg",
|
||||||
|
"opus" => "audio/ogg",
|
||||||
|
"ogg" => "audio/ogg",
|
||||||
|
"aac" | "m4a" => "audio/mp4",
|
||||||
|
"flac" => "audio/flac",
|
||||||
|
_ => "audio/mpeg",
|
||||||
|
};
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
track_id = track_id,
|
||||||
|
from = %file_ext,
|
||||||
|
to = target_format,
|
||||||
|
bitrate = bitrate,
|
||||||
|
"transcoding stream"
|
||||||
|
);
|
||||||
|
|
||||||
|
match Command::new("ffmpeg")
|
||||||
|
.args([
|
||||||
|
"-i",
|
||||||
|
&track.file_path,
|
||||||
|
"-map",
|
||||||
|
"0:a",
|
||||||
|
"-b:a",
|
||||||
|
&format!("{bitrate}k"),
|
||||||
|
"-v",
|
||||||
|
"0",
|
||||||
|
"-f",
|
||||||
|
target_format,
|
||||||
|
"-",
|
||||||
|
])
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.output()
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(output) => {
|
||||||
|
if output.status.success() && !output.stdout.is_empty() {
|
||||||
|
tracing::debug!(
|
||||||
|
track_id = track_id,
|
||||||
|
bytes = output.stdout.len(),
|
||||||
|
"transcoding complete"
|
||||||
|
);
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.content_type(content_type)
|
||||||
|
.body(output.stdout)
|
||||||
|
} else {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
tracing::error!(
|
||||||
|
status = ?output.status,
|
||||||
|
stderr = %stderr,
|
||||||
|
path = %track.file_path,
|
||||||
|
"ffmpeg transcoding failed"
|
||||||
|
);
|
||||||
|
match NamedFile::open_async(&track.file_path).await {
|
||||||
|
Ok(file) => file.into_response(&req),
|
||||||
|
Err(_) => response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"transcoding failed",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(error = %e, "failed to start ffmpeg");
|
||||||
|
match NamedFile::open_async(&track.file_path).await {
|
||||||
|
Ok(file) => file.into_response(&req),
|
||||||
|
Err(_) => {
|
||||||
|
response::error(¶ms.format, response::ERROR_NOT_FOUND, "file not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Serve the file directly with Range request support
|
||||||
|
match NamedFile::open_async(&track.file_path).await {
|
||||||
|
Ok(file) => file.into_response(&req),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(path = %track.file_path, error = %e, "failed to open track file for streaming");
|
||||||
|
response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"file not found on disk",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/download[.view]
|
||||||
|
pub async fn download(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, track_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "invalid song id");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let track = match queries::tracks::get_by_id(state.db.conn(), track_id).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(¶ms.format, response::ERROR_NOT_FOUND, "song not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match NamedFile::open_async(&track.file_path).await {
|
||||||
|
Ok(file) => {
|
||||||
|
let file = file.set_content_disposition(actix_web::http::header::ContentDisposition {
|
||||||
|
disposition: actix_web::http::header::DispositionType::Attachment,
|
||||||
|
parameters: vec![actix_web::http::header::DispositionParam::Filename(
|
||||||
|
std::path::Path::new(&track.file_path)
|
||||||
|
.file_name()
|
||||||
|
.and_then(|f| f.to_str())
|
||||||
|
.unwrap_or("track")
|
||||||
|
.to_string(),
|
||||||
|
)],
|
||||||
|
});
|
||||||
|
file.into_response(&req)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(path = %track.file_path, error = %e, "failed to open track file for download");
|
||||||
|
response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"file not found on disk",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getCoverArt[.view]
|
||||||
|
pub async fn get_cover_art(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cover art IDs can be album IDs (al-N) or artist IDs (ar-N)
|
||||||
|
let (prefix, entity_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"invalid cover art id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match prefix {
|
||||||
|
"al" => {
|
||||||
|
let album = match queries::albums::get_by_id(state.db.conn(), entity_id).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"album not found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(ref cover_art_path) = album.cover_art_path {
|
||||||
|
// If it's a URL, redirect to it
|
||||||
|
if cover_art_path.starts_with("http://") || cover_art_path.starts_with("https://") {
|
||||||
|
return HttpResponse::TemporaryRedirect()
|
||||||
|
.append_header(("Location", cover_art_path.as_str()))
|
||||||
|
.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise try to serve as a local file
|
||||||
|
match NamedFile::open_async(cover_art_path).await {
|
||||||
|
Ok(file) => return file.into_response(&req),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(path = %cover_art_path, error = %e, "cover art file not found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If album has a MusicBrainz ID, redirect to Cover Art Archive
|
||||||
|
if let Some(ref mbid) = album.musicbrainz_id {
|
||||||
|
let url = format!("https://coverartarchive.org/release/{mbid}/front-250");
|
||||||
|
return HttpResponse::TemporaryRedirect()
|
||||||
|
.append_header(("Location", url.as_str()))
|
||||||
|
.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
// No cover art available
|
||||||
|
HttpResponse::NotFound().finish()
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// For other types, no cover art
|
||||||
|
HttpResponse::NotFound().finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
86
src/routes/subsonic/mod.rs
Normal file
86
src/routes/subsonic/mod.rs
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
mod annotation;
|
||||||
|
mod auth;
|
||||||
|
mod browsing;
|
||||||
|
mod helpers;
|
||||||
|
mod media;
|
||||||
|
mod playlists;
|
||||||
|
mod response;
|
||||||
|
mod search;
|
||||||
|
mod system;
|
||||||
|
mod user;
|
||||||
|
|
||||||
|
use actix_web::web;
|
||||||
|
|
||||||
|
pub fn configure(cfg: &mut web::ServiceConfig) {
|
||||||
|
cfg.service(
|
||||||
|
web::scope("/rest")
|
||||||
|
// System
|
||||||
|
.route("/ping", web::get().to(system::ping))
|
||||||
|
.route("/ping.view", web::get().to(system::ping))
|
||||||
|
.route("/getLicense", web::get().to(system::get_license))
|
||||||
|
.route("/getLicense.view", web::get().to(system::get_license))
|
||||||
|
// Browsing
|
||||||
|
.route(
|
||||||
|
"/getMusicFolders",
|
||||||
|
web::get().to(browsing::get_music_folders),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/getMusicFolders.view",
|
||||||
|
web::get().to(browsing::get_music_folders),
|
||||||
|
)
|
||||||
|
.route("/getIndexes", web::get().to(browsing::get_indexes))
|
||||||
|
.route("/getIndexes.view", web::get().to(browsing::get_indexes))
|
||||||
|
.route(
|
||||||
|
"/getMusicDirectory",
|
||||||
|
web::get().to(browsing::get_music_directory),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/getMusicDirectory.view",
|
||||||
|
web::get().to(browsing::get_music_directory),
|
||||||
|
)
|
||||||
|
.route("/getArtists", web::get().to(browsing::get_artists))
|
||||||
|
.route("/getArtists.view", web::get().to(browsing::get_artists))
|
||||||
|
.route("/getArtist", web::get().to(browsing::get_artist))
|
||||||
|
.route("/getArtist.view", web::get().to(browsing::get_artist))
|
||||||
|
.route("/getAlbum", web::get().to(browsing::get_album))
|
||||||
|
.route("/getAlbum.view", web::get().to(browsing::get_album))
|
||||||
|
.route("/getSong", web::get().to(browsing::get_song))
|
||||||
|
.route("/getSong.view", web::get().to(browsing::get_song))
|
||||||
|
.route("/getGenres", web::get().to(browsing::get_genres))
|
||||||
|
.route("/getGenres.view", web::get().to(browsing::get_genres))
|
||||||
|
// Search
|
||||||
|
.route("/search3", web::get().to(search::search3))
|
||||||
|
.route("/search3.view", web::get().to(search::search3))
|
||||||
|
// Media
|
||||||
|
.route("/stream", web::get().to(media::stream))
|
||||||
|
.route("/stream.view", web::get().to(media::stream))
|
||||||
|
.route("/download", web::get().to(media::download))
|
||||||
|
.route("/download.view", web::get().to(media::download))
|
||||||
|
.route("/getCoverArt", web::get().to(media::get_cover_art))
|
||||||
|
.route("/getCoverArt.view", web::get().to(media::get_cover_art))
|
||||||
|
// Playlists
|
||||||
|
.route("/getPlaylists", web::get().to(playlists::get_playlists))
|
||||||
|
.route(
|
||||||
|
"/getPlaylists.view",
|
||||||
|
web::get().to(playlists::get_playlists),
|
||||||
|
)
|
||||||
|
.route("/getPlaylist", web::get().to(playlists::get_playlist))
|
||||||
|
.route("/getPlaylist.view", web::get().to(playlists::get_playlist))
|
||||||
|
.route("/createPlaylist", web::get().to(playlists::create_playlist))
|
||||||
|
.route(
|
||||||
|
"/createPlaylist.view",
|
||||||
|
web::get().to(playlists::create_playlist),
|
||||||
|
)
|
||||||
|
.route("/deletePlaylist", web::get().to(playlists::delete_playlist))
|
||||||
|
.route(
|
||||||
|
"/deletePlaylist.view",
|
||||||
|
web::get().to(playlists::delete_playlist),
|
||||||
|
)
|
||||||
|
// Annotation
|
||||||
|
.route("/scrobble", web::get().to(annotation::scrobble))
|
||||||
|
.route("/scrobble.view", web::get().to(annotation::scrobble))
|
||||||
|
// User
|
||||||
|
.route("/getUser", web::get().to(user::get_user))
|
||||||
|
.route("/getUser.view", web::get().to(user::get_user)),
|
||||||
|
);
|
||||||
|
}
|
||||||
250
src/routes/subsonic/playlists.rs
Normal file
250
src/routes/subsonic/playlists.rs
Normal file
@@ -0,0 +1,250 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::{authenticate, get_query_param, parse_subsonic_id};
|
||||||
|
use super::response::{self, SubsonicChild};
|
||||||
|
|
||||||
|
/// GET /rest/getPlaylists[.view]
|
||||||
|
pub async fn get_playlists(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let playlists = queries::playlists::list(state.db.conn(), Some(user.id))
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut playlist_list: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for pl in &playlists {
|
||||||
|
let track_count = queries::playlists::get_track_count(state.db.conn(), pl.id)
|
||||||
|
.await
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
// Calculate total duration
|
||||||
|
let tracks = queries::playlists::get_tracks(state.db.conn(), pl.id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
let duration: i32 = tracks
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.duration.map(|d| d as i32))
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
let mut pl_json = serde_json::json!({
|
||||||
|
"id": format!("pl-{}", pl.id),
|
||||||
|
"name": pl.name,
|
||||||
|
"owner": user.username,
|
||||||
|
"public": false,
|
||||||
|
"songCount": track_count,
|
||||||
|
"duration": duration,
|
||||||
|
"created": pl.created_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
"changed": pl.updated_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
});
|
||||||
|
if let Some(ref desc) = pl.description {
|
||||||
|
pl_json["comment"] = serde_json::json!(desc);
|
||||||
|
}
|
||||||
|
playlist_list.push(pl_json);
|
||||||
|
}
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"playlists": {
|
||||||
|
"playlist": playlist_list,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getPlaylist[.view]
|
||||||
|
pub async fn get_playlist(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, playlist_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"invalid playlist id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let playlist = match queries::playlists::get_by_id(state.db.conn(), playlist_id).await {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(_) => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"playlist not found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let tracks = queries::playlists::get_tracks(state.db.conn(), playlist_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let duration: i32 = tracks
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.duration.map(|d| d as i32))
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
let entry_list: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.map(|track| serde_json::to_value(SubsonicChild::from_track(track)).unwrap_or_default())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut pl_json = serde_json::json!({
|
||||||
|
"id": format!("pl-{}", playlist.id),
|
||||||
|
"name": playlist.name,
|
||||||
|
"owner": user.username,
|
||||||
|
"public": false,
|
||||||
|
"songCount": tracks.len(),
|
||||||
|
"duration": duration,
|
||||||
|
"created": playlist.created_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
"changed": playlist.updated_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
"entry": entry_list,
|
||||||
|
});
|
||||||
|
if let Some(ref desc) = playlist.description {
|
||||||
|
pl_json["comment"] = serde_json::json!(desc);
|
||||||
|
}
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"playlist": pl_json,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/createPlaylist[.view]
|
||||||
|
pub async fn create_playlist(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let name = match get_query_param(&req, "name") {
|
||||||
|
Some(n) => n,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: name",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Collect songId params (can be repeated)
|
||||||
|
let qs = req.query_string();
|
||||||
|
let query_params: Vec<(String, String)> = serde_urlencoded::from_str(qs).unwrap_or_default();
|
||||||
|
let track_ids: Vec<i32> = query_params
|
||||||
|
.iter()
|
||||||
|
.filter(|(k, _)| k == "songId")
|
||||||
|
.filter_map(|(_, v)| parse_subsonic_id(v).map(|(_, id)| id))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
match queries::playlists::create(state.db.conn(), &name, None, Some(user.id), &track_ids).await
|
||||||
|
{
|
||||||
|
Ok(playlist) => {
|
||||||
|
let tracks = queries::playlists::get_tracks(state.db.conn(), playlist.id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
let duration: i32 = tracks
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.duration.map(|d| d as i32))
|
||||||
|
.sum();
|
||||||
|
let entry_list: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.map(|track| {
|
||||||
|
serde_json::to_value(SubsonicChild::from_track(track)).unwrap_or_default()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut pl_json = serde_json::json!({
|
||||||
|
"id": format!("pl-{}", playlist.id),
|
||||||
|
"name": playlist.name,
|
||||||
|
"owner": user.username,
|
||||||
|
"public": false,
|
||||||
|
"songCount": tracks.len(),
|
||||||
|
"duration": duration,
|
||||||
|
"created": playlist.created_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
"changed": playlist.updated_at.format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||||
|
"entry": entry_list,
|
||||||
|
});
|
||||||
|
if let Some(ref desc) = playlist.description {
|
||||||
|
pl_json["comment"] = serde_json::json!(desc);
|
||||||
|
}
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"playlist": pl_json,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(e) => response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_GENERIC,
|
||||||
|
&format!("failed to create playlist: {e}"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/deletePlaylist[.view]
|
||||||
|
pub async fn delete_playlist(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id_str = match get_query_param(&req, "id") {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_prefix, playlist_id) = match parse_subsonic_id(&id_str) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_NOT_FOUND,
|
||||||
|
"invalid playlist id",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match queries::playlists::delete(state.db.conn(), playlist_id).await {
|
||||||
|
Ok(()) => response::ok(¶ms.format, serde_json::json!({})),
|
||||||
|
Err(e) => response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_GENERIC,
|
||||||
|
&format!("failed to delete playlist: {e}"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
249
src/routes/subsonic/response.rs
Normal file
249
src/routes/subsonic/response.rs
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
use actix_web::HttpResponse;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
const SUBSONIC_VERSION: &str = "1.16.1";
|
||||||
|
const XMLNS: &str = "http://subsonic.org/restapi";
|
||||||
|
|
||||||
|
/// Build a successful Subsonic response in the requested format.
|
||||||
|
pub fn ok(format: &str, body: serde_json::Value) -> HttpResponse {
|
||||||
|
format_response(format, "ok", body, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a Subsonic error response.
|
||||||
|
pub fn error(format: &str, code: u32, message: &str) -> HttpResponse {
|
||||||
|
let err = serde_json::json!({
|
||||||
|
"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
format_response(format, "failed", err, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subsonic error codes.
|
||||||
|
pub const ERROR_GENERIC: u32 = 0;
|
||||||
|
pub const ERROR_MISSING_PARAM: u32 = 10;
|
||||||
|
pub const ERROR_NOT_AUTHENTICATED: u32 = 40;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub const ERROR_NOT_AUTHORIZED: u32 = 50;
|
||||||
|
pub const ERROR_NOT_FOUND: u32 = 70;
|
||||||
|
|
||||||
|
fn format_response(
|
||||||
|
format: &str,
|
||||||
|
status: &str,
|
||||||
|
body: serde_json::Value,
|
||||||
|
_type_attr: Option<&str>,
|
||||||
|
) -> HttpResponse {
|
||||||
|
match format {
|
||||||
|
"json" => format_json(status, body),
|
||||||
|
_ => format_xml(status, body),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_json(status: &str, body: serde_json::Value) -> HttpResponse {
|
||||||
|
let mut response = serde_json::json!({
|
||||||
|
"status": status,
|
||||||
|
"version": SUBSONIC_VERSION,
|
||||||
|
"type": "shanty",
|
||||||
|
"serverVersion": "0.1.0",
|
||||||
|
"openSubsonic": true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Merge body into response
|
||||||
|
if let serde_json::Value::Object(map) = body
|
||||||
|
&& let serde_json::Value::Object(ref mut resp_map) = response
|
||||||
|
{
|
||||||
|
for (k, v) in map {
|
||||||
|
resp_map.insert(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let wrapper = serde_json::json!({
|
||||||
|
"subsonic-response": response,
|
||||||
|
});
|
||||||
|
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.content_type("application/json")
|
||||||
|
.json(wrapper)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_xml(status: &str, body: serde_json::Value) -> HttpResponse {
|
||||||
|
let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
|
||||||
|
xml.push_str(&format!(
|
||||||
|
"<subsonic-response xmlns=\"{XMLNS}\" status=\"{status}\" version=\"{SUBSONIC_VERSION}\" type=\"shanty\" serverVersion=\"0.1.0\" openSubsonic=\"true\">"
|
||||||
|
));
|
||||||
|
|
||||||
|
if let serde_json::Value::Object(map) = &body {
|
||||||
|
for (key, value) in map {
|
||||||
|
json_to_xml(&mut xml, key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xml.push_str("</subsonic-response>");
|
||||||
|
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.content_type("application/xml; charset=UTF-8")
|
||||||
|
.body(xml)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert a JSON value into XML elements. The Subsonic XML format uses:
|
||||||
|
/// - Object keys become element names
|
||||||
|
/// - Primitive values in objects become attributes
|
||||||
|
/// - Arrays become repeated elements
|
||||||
|
/// - Nested objects become child elements
|
||||||
|
fn json_to_xml(xml: &mut String, tag: &str, value: &serde_json::Value) {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::Array(arr) => {
|
||||||
|
for item in arr {
|
||||||
|
json_to_xml(xml, tag, item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::Object(map) => {
|
||||||
|
xml.push_str(&format!("<{tag}"));
|
||||||
|
|
||||||
|
let mut children = Vec::new();
|
||||||
|
for (k, v) in map {
|
||||||
|
match v {
|
||||||
|
serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
|
||||||
|
children.push((k, v));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let val_str = match v {
|
||||||
|
serde_json::Value::String(s) => xml_escape(s),
|
||||||
|
serde_json::Value::Bool(b) => b.to_string(),
|
||||||
|
serde_json::Value::Number(n) => n.to_string(),
|
||||||
|
serde_json::Value::Null => String::new(),
|
||||||
|
_ => v.to_string(),
|
||||||
|
};
|
||||||
|
xml.push_str(&format!(" {k}=\"{val_str}\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if children.is_empty() {
|
||||||
|
xml.push_str("/>");
|
||||||
|
} else {
|
||||||
|
xml.push('>');
|
||||||
|
for (k, v) in children {
|
||||||
|
json_to_xml(xml, k, v);
|
||||||
|
}
|
||||||
|
xml.push_str(&format!("</{tag}>"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::String(s) => {
|
||||||
|
xml.push_str(&format!("<{tag}>{}</{tag}>", xml_escape(s)));
|
||||||
|
}
|
||||||
|
serde_json::Value::Number(n) => {
|
||||||
|
xml.push_str(&format!("<{tag}>{n}</{tag}>"));
|
||||||
|
}
|
||||||
|
serde_json::Value::Bool(b) => {
|
||||||
|
xml.push_str(&format!("<{tag}>{b}</{tag}>"));
|
||||||
|
}
|
||||||
|
serde_json::Value::Null => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xml_escape(s: &str) -> String {
|
||||||
|
s.replace('&', "&")
|
||||||
|
.replace('<', "<")
|
||||||
|
.replace('>', ">")
|
||||||
|
.replace('"', """)
|
||||||
|
.replace('\'', "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper to build a "child" (track) JSON for Subsonic responses.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SubsonicChild {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub parent: Option<String>,
|
||||||
|
pub is_dir: bool,
|
||||||
|
pub title: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub album: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub artist: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub track: Option<i32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub year: Option<i32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub genre: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub size: Option<i64>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub suffix: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub duration: Option<i32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub bit_rate: Option<i32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub path: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub disc_number: Option<i32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub album_id: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub artist_id: Option<String>,
|
||||||
|
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub media_type: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SubsonicChild {
|
||||||
|
pub fn from_track(track: &shanty_db::entities::track::Model) -> Self {
|
||||||
|
let suffix = std::path::Path::new(&track.file_path)
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
let content_type = suffix.as_deref().map(|s| {
|
||||||
|
match s {
|
||||||
|
"mp3" => "audio/mpeg",
|
||||||
|
"flac" => "audio/flac",
|
||||||
|
"ogg" | "opus" => "audio/ogg",
|
||||||
|
"m4a" | "aac" => "audio/mp4",
|
||||||
|
"wav" => "audio/wav",
|
||||||
|
"wma" => "audio/x-ms-wma",
|
||||||
|
_ => "audio/mpeg",
|
||||||
|
}
|
||||||
|
.to_string()
|
||||||
|
});
|
||||||
|
|
||||||
|
let path_display = format!(
|
||||||
|
"{}/{}",
|
||||||
|
track.artist.as_deref().unwrap_or("Unknown Artist"),
|
||||||
|
std::path::Path::new(&track.file_path)
|
||||||
|
.file_name()
|
||||||
|
.and_then(|f| f.to_str())
|
||||||
|
.unwrap_or("unknown")
|
||||||
|
);
|
||||||
|
|
||||||
|
SubsonicChild {
|
||||||
|
id: format!("tr-{}", track.id),
|
||||||
|
parent: track.album_id.map(|id| format!("al-{id}")),
|
||||||
|
is_dir: false,
|
||||||
|
title: track.title.clone().unwrap_or_else(|| "Unknown".to_string()),
|
||||||
|
album: track.album.clone(),
|
||||||
|
artist: track.artist.clone(),
|
||||||
|
track: track.track_number,
|
||||||
|
year: track.year,
|
||||||
|
genre: track.genre.clone(),
|
||||||
|
cover_art: track.album_id.map(|id| format!("al-{id}")),
|
||||||
|
size: Some(track.file_size),
|
||||||
|
content_type,
|
||||||
|
suffix,
|
||||||
|
duration: track.duration.map(|d| d as i32),
|
||||||
|
bit_rate: track.bitrate,
|
||||||
|
path: Some(path_display),
|
||||||
|
disc_number: track.disc_number,
|
||||||
|
album_id: track.album_id.map(|id| format!("al-{id}")),
|
||||||
|
artist_id: track.artist_id.map(|id| format!("ar-{id}")),
|
||||||
|
media_type: Some("music".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
124
src/routes/subsonic/search.rs
Normal file
124
src/routes/subsonic/search.rs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::{authenticate, get_query_param};
|
||||||
|
use super::response::{self, SubsonicChild};
|
||||||
|
|
||||||
|
/// GET /rest/search3[.view]
|
||||||
|
pub async fn search3(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let query = match get_query_param(&req, "query") {
|
||||||
|
Some(q) => q,
|
||||||
|
None => {
|
||||||
|
return response::error(
|
||||||
|
¶ms.format,
|
||||||
|
response::ERROR_MISSING_PARAM,
|
||||||
|
"missing required parameter: query",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let artist_count: u64 = get_query_param(&req, "artistCount")
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(20);
|
||||||
|
let album_count: u64 = get_query_param(&req, "albumCount")
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(20);
|
||||||
|
let song_count: u64 = get_query_param(&req, "songCount")
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(20);
|
||||||
|
|
||||||
|
// Search tracks (which gives us artists and albums too)
|
||||||
|
let tracks = queries::tracks::search(state.db.conn(), &query)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
// Collect unique artists from tracks
|
||||||
|
let mut seen_artists = std::collections::HashSet::new();
|
||||||
|
let mut artist_results: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for track in &tracks {
|
||||||
|
if let Some(artist_id) = track.artist_id
|
||||||
|
&& seen_artists.insert(artist_id)
|
||||||
|
&& artist_results.len() < artist_count as usize
|
||||||
|
&& let Ok(artist) = queries::artists::get_by_id(state.db.conn(), artist_id).await
|
||||||
|
{
|
||||||
|
let album_ct = queries::albums::get_by_artist(state.db.conn(), artist_id)
|
||||||
|
.await
|
||||||
|
.map(|a| a.len())
|
||||||
|
.unwrap_or(0);
|
||||||
|
artist_results.push(serde_json::json!({
|
||||||
|
"id": format!("ar-{}", artist.id),
|
||||||
|
"name": artist.name,
|
||||||
|
"albumCount": album_ct,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also search artists by name directly
|
||||||
|
let all_artists = queries::artists::list(state.db.conn(), 10000, 0)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
let query_lower = query.to_lowercase();
|
||||||
|
for artist in &all_artists {
|
||||||
|
if artist.name.to_lowercase().contains(&query_lower)
|
||||||
|
&& seen_artists.insert(artist.id)
|
||||||
|
&& artist_results.len() < artist_count as usize
|
||||||
|
{
|
||||||
|
let album_ct = queries::albums::get_by_artist(state.db.conn(), artist.id)
|
||||||
|
.await
|
||||||
|
.map(|a| a.len())
|
||||||
|
.unwrap_or(0);
|
||||||
|
artist_results.push(serde_json::json!({
|
||||||
|
"id": format!("ar-{}", artist.id),
|
||||||
|
"name": artist.name,
|
||||||
|
"albumCount": album_ct,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect unique albums from tracks
|
||||||
|
let mut seen_albums = std::collections::HashSet::new();
|
||||||
|
let mut album_results: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for track in &tracks {
|
||||||
|
if let Some(aid) = track.album_id
|
||||||
|
&& seen_albums.insert(aid)
|
||||||
|
&& album_results.len() < album_count as usize
|
||||||
|
&& let Ok(album) = queries::albums::get_by_id(state.db.conn(), aid).await
|
||||||
|
{
|
||||||
|
album_results.push(serde_json::json!({
|
||||||
|
"id": format!("al-{}", album.id),
|
||||||
|
"name": album.name,
|
||||||
|
"artist": album.album_artist,
|
||||||
|
"artistId": album.artist_id.map(|id| format!("ar-{id}")),
|
||||||
|
"coverArt": format!("al-{}", album.id),
|
||||||
|
"year": album.year,
|
||||||
|
"genre": album.genre,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Song results
|
||||||
|
let song_results: Vec<serde_json::Value> = tracks
|
||||||
|
.iter()
|
||||||
|
.take(song_count as usize)
|
||||||
|
.map(|track| serde_json::to_value(SubsonicChild::from_track(track)).unwrap_or_default())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"searchResult3": {
|
||||||
|
"artist": artist_results,
|
||||||
|
"album": album_results,
|
||||||
|
"song": song_results,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
35
src/routes/subsonic/system.rs
Normal file
35
src/routes/subsonic/system.rs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::authenticate;
|
||||||
|
use super::response;
|
||||||
|
|
||||||
|
/// GET /rest/ping[.view]
|
||||||
|
pub async fn ping(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
response::ok(¶ms.format, serde_json::json!({}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /rest/getLicense[.view]
|
||||||
|
pub async fn get_license(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, _user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"license": {
|
||||||
|
"valid": true,
|
||||||
|
"email": "shanty@localhost",
|
||||||
|
"licenseExpires": "2099-12-31T23:59:59",
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
42
src/routes/subsonic/user.rs
Normal file
42
src/routes/subsonic/user.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
use shanty_db::entities::user::UserRole;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
use super::helpers::authenticate;
|
||||||
|
use super::response;
|
||||||
|
|
||||||
|
/// GET /rest/getUser[.view]
|
||||||
|
pub async fn get_user(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let (params, user) = match authenticate(&req, &state).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(resp) => return resp,
|
||||||
|
};
|
||||||
|
|
||||||
|
let is_admin = user.role == UserRole::Admin;
|
||||||
|
|
||||||
|
response::ok(
|
||||||
|
¶ms.format,
|
||||||
|
serde_json::json!({
|
||||||
|
"user": {
|
||||||
|
"username": user.username,
|
||||||
|
"email": "",
|
||||||
|
"scrobblingEnabled": false,
|
||||||
|
"adminRole": is_admin,
|
||||||
|
"settingsRole": is_admin,
|
||||||
|
"downloadRole": true,
|
||||||
|
"uploadRole": false,
|
||||||
|
"playlistRole": true,
|
||||||
|
"coverArtRole": false,
|
||||||
|
"commentRole": false,
|
||||||
|
"podcastRole": false,
|
||||||
|
"streamRole": true,
|
||||||
|
"jukeboxRole": false,
|
||||||
|
"shareRole": false,
|
||||||
|
"videoConversionRole": false,
|
||||||
|
"folder": [1],
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,12 +3,12 @@ use actix_web::{HttpResponse, web};
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use shanty_db::entities::download_queue::DownloadStatus;
|
use shanty_db::entities::download_queue::DownloadStatus;
|
||||||
|
use shanty_db::entities::work_queue::WorkTaskType;
|
||||||
use shanty_db::queries;
|
use shanty_db::queries;
|
||||||
|
|
||||||
use crate::auth;
|
use crate::auth;
|
||||||
use crate::config::AppConfig;
|
use crate::config::AppConfig;
|
||||||
use crate::error::ApiError;
|
use crate::error::ApiError;
|
||||||
use crate::routes::artists::enrich_all_watched_artists;
|
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
|
||||||
pub fn configure(cfg: &mut web::ServiceConfig) {
|
pub fn configure(cfg: &mut web::ServiceConfig) {
|
||||||
@@ -24,6 +24,8 @@ pub fn configure(cfg: &mut web::ServiceConfig) {
|
|||||||
.service(web::resource("/monitor/status").route(web::get().to(get_monitor_status)))
|
.service(web::resource("/monitor/status").route(web::get().to(get_monitor_status)))
|
||||||
.service(web::resource("/scheduler/skip-pipeline").route(web::post().to(skip_pipeline)))
|
.service(web::resource("/scheduler/skip-pipeline").route(web::post().to(skip_pipeline)))
|
||||||
.service(web::resource("/scheduler/skip-monitor").route(web::post().to(skip_monitor)))
|
.service(web::resource("/scheduler/skip-monitor").route(web::post().to(skip_monitor)))
|
||||||
|
.service(web::resource("/mb-status").route(web::get().to(get_mb_status)))
|
||||||
|
.service(web::resource("/mb-import").route(web::post().to(trigger_mb_import)))
|
||||||
.service(
|
.service(
|
||||||
web::resource("/config")
|
web::resource("/config")
|
||||||
.route(web::get().to(get_config))
|
.route(web::get().to(get_config))
|
||||||
@@ -36,13 +38,13 @@ async fn get_status(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_auth(&session)?;
|
auth::require_auth(&session)?;
|
||||||
let summary = shanty_watch::library_summary(state.db.conn()).await?;
|
let conn = state.db.conn();
|
||||||
let pending_items =
|
|
||||||
queries::downloads::list(state.db.conn(), Some(DownloadStatus::Pending)).await?;
|
let summary = shanty_watch::library_summary(conn).await?;
|
||||||
|
let pending_items = queries::downloads::list(conn, Some(DownloadStatus::Pending)).await?;
|
||||||
let downloading_items =
|
let downloading_items =
|
||||||
queries::downloads::list(state.db.conn(), Some(DownloadStatus::Downloading)).await?;
|
queries::downloads::list(conn, Some(DownloadStatus::Downloading)).await?;
|
||||||
let failed_items =
|
let failed_items = queries::downloads::list(conn, Some(DownloadStatus::Failed)).await?;
|
||||||
queries::downloads::list(state.db.conn(), Some(DownloadStatus::Failed)).await?;
|
|
||||||
let tasks = state.tasks.list();
|
let tasks = state.tasks.list();
|
||||||
|
|
||||||
let mut queue_items = Vec::new();
|
let mut queue_items = Vec::new();
|
||||||
@@ -50,15 +52,38 @@ async fn get_status(
|
|||||||
queue_items.extend(pending_items.iter().cloned());
|
queue_items.extend(pending_items.iter().cloned());
|
||||||
queue_items.extend(failed_items.iter().take(5).cloned());
|
queue_items.extend(failed_items.iter().take(5).cloned());
|
||||||
|
|
||||||
let needs_tagging = queries::tracks::get_needing_metadata(state.db.conn()).await?;
|
let needs_tagging = queries::tracks::get_needing_metadata(conn).await?;
|
||||||
|
|
||||||
// Scheduled task info
|
// Work queue counts
|
||||||
let sched = state.scheduler.lock().await;
|
let work_queue = queries::work_queue::counts_all(conn).await.ok();
|
||||||
let scheduled_tasks = serde_json::json!({
|
|
||||||
"next_pipeline": sched.next_pipeline,
|
// Scheduler state from DB
|
||||||
"next_monitor": sched.next_monitor,
|
let scheduler_jobs = queries::scheduler_state::list_all(conn).await.unwrap_or_default();
|
||||||
});
|
let scheduler_json: serde_json::Value = scheduler_jobs
|
||||||
drop(sched);
|
.iter()
|
||||||
|
.map(|j| {
|
||||||
|
(
|
||||||
|
j.job_name.clone(),
|
||||||
|
serde_json::json!({
|
||||||
|
"last_run": j.last_run_at,
|
||||||
|
"next_run": j.next_run_at,
|
||||||
|
"last_result": j.last_result,
|
||||||
|
"enabled": j.enabled,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<serde_json::Map<String, serde_json::Value>>()
|
||||||
|
.into();
|
||||||
|
|
||||||
|
// Backward-compatible scheduled field (from scheduler_state DB)
|
||||||
|
let next_pipeline = scheduler_jobs
|
||||||
|
.iter()
|
||||||
|
.find(|j| j.job_name == "pipeline")
|
||||||
|
.and_then(|j| j.next_run_at);
|
||||||
|
let next_monitor = scheduler_jobs
|
||||||
|
.iter()
|
||||||
|
.find(|j| j.job_name == "monitor")
|
||||||
|
.and_then(|j| j.next_run_at);
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(serde_json::json!({
|
Ok(HttpResponse::Ok().json(serde_json::json!({
|
||||||
"library": summary,
|
"library": summary,
|
||||||
@@ -73,7 +98,12 @@ async fn get_status(
|
|||||||
"items": needs_tagging.iter().take(20).collect::<Vec<_>>(),
|
"items": needs_tagging.iter().take(20).collect::<Vec<_>>(),
|
||||||
},
|
},
|
||||||
"tasks": tasks,
|
"tasks": tasks,
|
||||||
"scheduled": scheduled_tasks,
|
"scheduled": {
|
||||||
|
"next_pipeline": next_pipeline,
|
||||||
|
"next_monitor": next_monitor,
|
||||||
|
},
|
||||||
|
"work_queue": work_queue,
|
||||||
|
"scheduler": scheduler_json,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,27 +112,16 @@ async fn trigger_index(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_auth(&session)?;
|
auth::require_auth(&session)?;
|
||||||
let task_id = state.tasks.register("index");
|
let payload = serde_json::json!({"scan_all": true});
|
||||||
let state = state.clone();
|
let item = queries::work_queue::enqueue(
|
||||||
let tid = task_id.clone();
|
state.db.conn(),
|
||||||
|
WorkTaskType::Index,
|
||||||
tokio::spawn(async move {
|
&payload.to_string(),
|
||||||
let cfg = state.config.read().await.clone();
|
None,
|
||||||
state
|
)
|
||||||
.tasks
|
.await?;
|
||||||
.update_progress(&tid, 0, 0, "Scanning library...");
|
state.workers.notify(WorkTaskType::Index);
|
||||||
let scan_config = shanty_index::ScanConfig {
|
Ok(HttpResponse::Accepted().json(serde_json::json!({ "work_item_id": item.id })))
|
||||||
root: cfg.library_path.clone(),
|
|
||||||
dry_run: false,
|
|
||||||
concurrency: cfg.indexing.concurrency,
|
|
||||||
};
|
|
||||||
match shanty_index::run_scan(state.db.conn(), &scan_config).await {
|
|
||||||
Ok(stats) => state.tasks.complete(&tid, format!("{stats}")),
|
|
||||||
Err(e) => state.tasks.fail(&tid, e.to_string()),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(HttpResponse::Accepted().json(serde_json::json!({ "task_id": task_id })))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn trigger_tag(
|
async fn trigger_tag(
|
||||||
@@ -110,35 +129,18 @@ async fn trigger_tag(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_auth(&session)?;
|
auth::require_auth(&session)?;
|
||||||
let task_id = state.tasks.register("tag");
|
let conn = state.db.conn();
|
||||||
let state = state.clone();
|
let untagged = queries::tracks::get_needing_metadata(conn).await?;
|
||||||
let tid = task_id.clone();
|
let mut count = 0;
|
||||||
|
for track in &untagged {
|
||||||
tokio::spawn(async move {
|
let payload = serde_json::json!({"track_id": track.id});
|
||||||
let cfg = state.config.read().await.clone();
|
queries::work_queue::enqueue(conn, WorkTaskType::Tag, &payload.to_string(), None).await?;
|
||||||
state
|
count += 1;
|
||||||
.tasks
|
|
||||||
.update_progress(&tid, 0, 0, "Preparing tagger...");
|
|
||||||
let mb = match shanty_tag::MusicBrainzClient::new() {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => {
|
|
||||||
state.tasks.fail(&tid, e.to_string());
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
if count > 0 {
|
||||||
let tag_config = shanty_tag::TagConfig {
|
state.workers.notify(WorkTaskType::Tag);
|
||||||
dry_run: false,
|
|
||||||
write_tags: cfg.tagging.write_tags,
|
|
||||||
confidence: cfg.tagging.confidence,
|
|
||||||
};
|
|
||||||
state.tasks.update_progress(&tid, 0, 0, "Tagging tracks...");
|
|
||||||
match shanty_tag::run_tagging(state.db.conn(), &mb, &tag_config, None).await {
|
|
||||||
Ok(stats) => state.tasks.complete(&tid, format!("{stats}")),
|
|
||||||
Err(e) => state.tasks.fail(&tid, e.to_string()),
|
|
||||||
}
|
}
|
||||||
});
|
Ok(HttpResponse::Accepted().json(serde_json::json!({ "enqueued": count })))
|
||||||
|
|
||||||
Ok(HttpResponse::Accepted().json(serde_json::json!({ "task_id": task_id })))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn trigger_organize(
|
async fn trigger_organize(
|
||||||
@@ -146,39 +148,31 @@ async fn trigger_organize(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_auth(&session)?;
|
auth::require_auth(&session)?;
|
||||||
let task_id = state.tasks.register("organize");
|
let conn = state.db.conn();
|
||||||
let state = state.clone();
|
let mut count = 0u64;
|
||||||
let tid = task_id.clone();
|
let mut offset = 0u64;
|
||||||
|
loop {
|
||||||
tokio::spawn(async move {
|
let tracks = queries::tracks::list(conn, 500, offset).await?;
|
||||||
let cfg = state.config.read().await.clone();
|
if tracks.is_empty() {
|
||||||
state
|
break;
|
||||||
.tasks
|
|
||||||
.update_progress(&tid, 0, 0, "Organizing files...");
|
|
||||||
let org_config = shanty_org::OrgConfig {
|
|
||||||
target_dir: cfg.library_path.clone(),
|
|
||||||
format: cfg.organization_format.clone(),
|
|
||||||
dry_run: false,
|
|
||||||
copy: false,
|
|
||||||
};
|
|
||||||
match shanty_org::organize_from_db(state.db.conn(), &org_config).await {
|
|
||||||
Ok(stats) => {
|
|
||||||
let promoted = queries::wanted::promote_downloaded_to_owned(state.db.conn())
|
|
||||||
.await
|
|
||||||
.unwrap_or(0);
|
|
||||||
let msg = if promoted > 0 {
|
|
||||||
format!("{stats} — {promoted} items marked as owned")
|
|
||||||
} else {
|
|
||||||
format!("{stats}")
|
|
||||||
};
|
|
||||||
state.tasks.complete(&tid, msg);
|
|
||||||
let _ = enrich_all_watched_artists(&state).await;
|
|
||||||
}
|
}
|
||||||
Err(e) => state.tasks.fail(&tid, e.to_string()),
|
for track in &tracks {
|
||||||
|
let payload = serde_json::json!({"track_id": track.id});
|
||||||
|
queries::work_queue::enqueue(
|
||||||
|
conn,
|
||||||
|
WorkTaskType::Organize,
|
||||||
|
&payload.to_string(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
count += 1;
|
||||||
}
|
}
|
||||||
});
|
offset += 500;
|
||||||
|
}
|
||||||
Ok(HttpResponse::Accepted().json(serde_json::json!({ "task_id": task_id })))
|
if count > 0 {
|
||||||
|
state.workers.notify(WorkTaskType::Organize);
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Accepted().json(serde_json::json!({ "enqueued": count })))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn trigger_pipeline(
|
async fn trigger_pipeline(
|
||||||
@@ -186,8 +180,8 @@ async fn trigger_pipeline(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_auth(&session)?;
|
auth::require_auth(&session)?;
|
||||||
let task_ids = crate::pipeline::spawn_pipeline(&state);
|
let pipeline_id = crate::pipeline::trigger_pipeline(&state).await?;
|
||||||
Ok(HttpResponse::Accepted().json(serde_json::json!({ "task_ids": task_ids })))
|
Ok(HttpResponse::Accepted().json(serde_json::json!({ "pipeline_id": pipeline_id })))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_task(
|
async fn get_task(
|
||||||
@@ -311,10 +305,13 @@ async fn skip_pipeline(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_admin(&session)?;
|
auth::require_admin(&session)?;
|
||||||
let mut sched = state.scheduler.lock().await;
|
// Push next_run_at forward by one interval
|
||||||
sched.skip_pipeline = true;
|
let cfg = state.config.read().await;
|
||||||
sched.next_pipeline = None;
|
let hours = cfg.scheduling.pipeline_interval_hours.max(1);
|
||||||
Ok(HttpResponse::Ok().json(serde_json::json!({"status": "skipped"})))
|
drop(cfg);
|
||||||
|
let next = chrono::Utc::now().naive_utc() + chrono::Duration::hours(i64::from(hours));
|
||||||
|
queries::scheduler_state::update_next_run(state.db.conn(), "pipeline", Some(next)).await?;
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({"status": "skipped", "next_run": next})))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn skip_monitor(
|
async fn skip_monitor(
|
||||||
@@ -322,8 +319,118 @@ async fn skip_monitor(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<HttpResponse, ApiError> {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
auth::require_admin(&session)?;
|
auth::require_admin(&session)?;
|
||||||
let mut sched = state.scheduler.lock().await;
|
let cfg = state.config.read().await;
|
||||||
sched.skip_monitor = true;
|
let hours = cfg.scheduling.monitor_interval_hours.max(1);
|
||||||
sched.next_monitor = None;
|
drop(cfg);
|
||||||
Ok(HttpResponse::Ok().json(serde_json::json!({"status": "skipped"})))
|
let next = chrono::Utc::now().naive_utc() + chrono::Duration::hours(i64::from(hours));
|
||||||
|
queries::scheduler_state::update_next_run(state.db.conn(), "monitor", Some(next)).await?;
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({"status": "skipped", "next_run": next})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_mb_status(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
session: Session,
|
||||||
|
) -> Result<HttpResponse, ApiError> {
|
||||||
|
auth::require_auth(&session)?;
|
||||||
|
let has_local = state.mb_client.has_local_db();
|
||||||
|
let stats = state.mb_client.local_stats();
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({
|
||||||
|
"has_local_db": has_local,
|
||||||
|
"stats": stats,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trigger_mb_import(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
session: Session,
|
||||||
|
) -> Result<HttpResponse, ApiError> {
|
||||||
|
auth::require_admin(&session)?;
|
||||||
|
let task_id = state.tasks.register("mb_import");
|
||||||
|
let tid = task_id.clone();
|
||||||
|
let config = state.config.read().await.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.update_progress(&tid, 0, 0, "Starting MusicBrainz import...");
|
||||||
|
|
||||||
|
let data_dir = shanty_config::data_dir().join("mb-dumps");
|
||||||
|
let db_path = config
|
||||||
|
.musicbrainz
|
||||||
|
.local_db_path
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| shanty_config::data_dir().join("shanty-mb.db"));
|
||||||
|
|
||||||
|
// Download dumps
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.update_progress(&tid, 0, 4, "Downloading dumps...");
|
||||||
|
if let Err(e) = std::fs::create_dir_all(&data_dir) {
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.fail(&tid, format!("Failed to create data dir: {e}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp = match shanty_data::mb_import::discover_latest_dump_folder().await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.fail(&tid, format!("Failed to discover latest dump: {e}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (i, filename) in shanty_data::mb_import::DUMP_FILES.iter().enumerate() {
|
||||||
|
state.tasks.update_progress(
|
||||||
|
&tid,
|
||||||
|
i as u64,
|
||||||
|
4 + 4,
|
||||||
|
&format!("Downloading {filename}..."),
|
||||||
|
);
|
||||||
|
if let Err(e) =
|
||||||
|
shanty_data::mb_import::download_dump(filename, ×tamp, &data_dir, |msg| {
|
||||||
|
tracing::info!("{msg}");
|
||||||
|
state.tasks.update_progress(&tid, i as u64, 8, msg);
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.fail(&tid, format!("Failed to download {filename}: {e}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run import
|
||||||
|
state
|
||||||
|
.tasks
|
||||||
|
.update_progress(&tid, 4, 8, "Importing into database...");
|
||||||
|
|
||||||
|
let tid_clone = tid.clone();
|
||||||
|
let state_clone = state.clone();
|
||||||
|
let result = tokio::task::spawn_blocking(move || {
|
||||||
|
shanty_data::mb_import::run_import_at_path(&db_path, &data_dir, |msg| {
|
||||||
|
tracing::info!("{msg}");
|
||||||
|
state_clone.tasks.update_progress(&tid_clone, 4, 8, msg);
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Ok(stats)) => {
|
||||||
|
tracing::info!(%stats, "MusicBrainz import complete");
|
||||||
|
state.tasks.complete(&tid, format!("{stats}"));
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
state.tasks.fail(&tid, format!("Import failed: {e}"));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
state.tasks.fail(&tid, format!("Import task panicked: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().json(serde_json::json!({ "task_id": task_id })))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,16 @@ pub struct SearchParams {
|
|||||||
offset: u64,
|
offset: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct WatchTrackRequest {
|
||||||
|
artist: Option<String>,
|
||||||
|
title: Option<String>,
|
||||||
|
mbid: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
pub fn configure(cfg: &mut web::ServiceConfig) {
|
pub fn configure(cfg: &mut web::ServiceConfig) {
|
||||||
cfg.service(web::resource("/tracks").route(web::get().to(list_tracks)))
|
cfg.service(web::resource("/tracks/watch").route(web::post().to(watch_track)))
|
||||||
|
.service(web::resource("/tracks").route(web::get().to(list_tracks)))
|
||||||
.service(web::resource("/tracks/{id}").route(web::get().to(get_track)));
|
.service(web::resource("/tracks/{id}").route(web::get().to(get_track)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,3 +58,32 @@ async fn get_track(
|
|||||||
let track = queries::tracks::get_by_id(state.db.conn(), id).await?;
|
let track = queries::tracks::get_by_id(state.db.conn(), id).await?;
|
||||||
Ok(HttpResponse::Ok().json(track))
|
Ok(HttpResponse::Ok().json(track))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn watch_track(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
session: Session,
|
||||||
|
body: web::Json<WatchTrackRequest>,
|
||||||
|
) -> Result<HttpResponse, ApiError> {
|
||||||
|
let (user_id, _, _) = auth::require_auth(&session)?;
|
||||||
|
if body.title.is_none() && body.mbid.is_none() {
|
||||||
|
return Err(ApiError::BadRequest(
|
||||||
|
"provide title or recording mbid".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let entry = shanty_watch::add_track(
|
||||||
|
state.db.conn(),
|
||||||
|
body.artist.as_deref(),
|
||||||
|
body.title.as_deref(),
|
||||||
|
body.mbid.as_deref(),
|
||||||
|
&state.mb_client,
|
||||||
|
Some(user_id),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(serde_json::json!({
|
||||||
|
"id": entry.id,
|
||||||
|
"status": entry.status,
|
||||||
|
"name": entry.name,
|
||||||
|
"artist_name": entry.artist_name,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|||||||
148
src/scheduler.rs
Normal file
148
src/scheduler.rs
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
//! Unified scheduler that manages all recurring background jobs.
|
||||||
|
//!
|
||||||
|
//! Replaces the separate pipeline_scheduler, monitor, and cookie_refresh spawn loops
|
||||||
|
//! with a single loop backed by persistent state in the `scheduler_state` DB table.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use actix_web::web;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
use shanty_db::queries;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Spawn the unified scheduler background loop.
|
||||||
|
pub fn spawn(state: web::Data<AppState>) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Initialize scheduler state rows in DB
|
||||||
|
for job_name in ["pipeline", "monitor", "cookie_refresh"] {
|
||||||
|
if let Err(e) =
|
||||||
|
queries::scheduler_state::get_or_create(state.db.conn(), job_name).await
|
||||||
|
{
|
||||||
|
tracing::error!(job = job_name, error = %e, "failed to init scheduler state");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Check each job
|
||||||
|
check_and_run_job(&state, "pipeline", run_pipeline_job).await;
|
||||||
|
check_and_run_job(&state, "monitor", run_monitor_job).await;
|
||||||
|
check_and_run_job(&state, "cookie_refresh", run_cookie_refresh_job).await;
|
||||||
|
|
||||||
|
// Poll every 30 seconds
|
||||||
|
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check_and_run_job<F, Fut>(state: &web::Data<AppState>, job_name: &str, run_fn: F)
|
||||||
|
where
|
||||||
|
F: FnOnce(web::Data<AppState>) -> Fut,
|
||||||
|
Fut: std::future::Future<Output = Result<String, String>>,
|
||||||
|
{
|
||||||
|
let job = match queries::scheduler_state::get_or_create(state.db.conn(), job_name).await {
|
||||||
|
Ok(j) => j,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(job = job_name, error = %e, "failed to read scheduler state");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Read config to check if enabled and get interval
|
||||||
|
let (config_enabled, interval_secs) = read_job_config(state, job_name).await;
|
||||||
|
|
||||||
|
// If config says disabled, ensure DB state reflects it
|
||||||
|
if !config_enabled {
|
||||||
|
if job.enabled {
|
||||||
|
let _ =
|
||||||
|
queries::scheduler_state::set_enabled(state.db.conn(), job_name, false).await;
|
||||||
|
let _ =
|
||||||
|
queries::scheduler_state::update_next_run(state.db.conn(), job_name, None).await;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If DB says disabled (e.g. user skipped), re-enable from config
|
||||||
|
if !job.enabled {
|
||||||
|
let _ = queries::scheduler_state::set_enabled(state.db.conn(), job_name, true).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = Utc::now().naive_utc();
|
||||||
|
|
||||||
|
// If no next_run_at is set, schedule one
|
||||||
|
if job.next_run_at.is_none() {
|
||||||
|
let next = now + chrono::Duration::seconds(interval_secs);
|
||||||
|
let _ =
|
||||||
|
queries::scheduler_state::update_next_run(state.db.conn(), job_name, Some(next)).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if it's time to run
|
||||||
|
let next_run = job.next_run_at.unwrap();
|
||||||
|
if now < next_run {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time to run!
|
||||||
|
tracing::info!(job = job_name, "scheduled job starting");
|
||||||
|
|
||||||
|
let result = run_fn(state.clone()).await;
|
||||||
|
|
||||||
|
let result_str = match &result {
|
||||||
|
Ok(msg) => {
|
||||||
|
tracing::info!(job = job_name, result = %msg, "scheduled job complete");
|
||||||
|
format!("ok: {msg}")
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(job = job_name, error = %e, "scheduled job failed");
|
||||||
|
format!("error: {e}")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update last run and schedule next
|
||||||
|
let _ = queries::scheduler_state::update_last_run(state.db.conn(), job_name, &result_str).await;
|
||||||
|
let next = Utc::now().naive_utc() + chrono::Duration::seconds(interval_secs);
|
||||||
|
let _ =
|
||||||
|
queries::scheduler_state::update_next_run(state.db.conn(), job_name, Some(next)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_job_config(state: &web::Data<AppState>, job_name: &str) -> (bool, i64) {
|
||||||
|
let cfg = state.config.read().await;
|
||||||
|
match job_name {
|
||||||
|
"pipeline" => (
|
||||||
|
cfg.scheduling.pipeline_enabled,
|
||||||
|
i64::from(cfg.scheduling.pipeline_interval_hours.max(1)) * 3600,
|
||||||
|
),
|
||||||
|
"monitor" => (
|
||||||
|
cfg.scheduling.monitor_enabled,
|
||||||
|
i64::from(cfg.scheduling.monitor_interval_hours.max(1)) * 3600,
|
||||||
|
),
|
||||||
|
"cookie_refresh" => (
|
||||||
|
cfg.download.cookie_refresh_enabled,
|
||||||
|
i64::from(cfg.download.cookie_refresh_hours.max(1)) * 3600,
|
||||||
|
),
|
||||||
|
_ => (false, 3600),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_pipeline_job(state: web::Data<AppState>) -> Result<String, String> {
|
||||||
|
let pipeline_id = crate::pipeline::trigger_pipeline(&state)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(format!("pipeline triggered: {pipeline_id}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_monitor_job(state: web::Data<AppState>) -> Result<String, String> {
|
||||||
|
let stats = crate::monitor::check_monitored_artists(&state)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(format!(
|
||||||
|
"{} artists checked, {} new releases, {} tracks added",
|
||||||
|
stats.artists_checked, stats.new_releases_found, stats.tracks_added
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_cookie_refresh_job(_state: web::Data<AppState>) -> Result<String, String> {
|
||||||
|
crate::cookie_refresh::run_refresh().await
|
||||||
|
}
|
||||||
19
src/state.rs
19
src/state.rs
@@ -1,39 +1,28 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::{Mutex, RwLock};
|
use tokio::sync::{Mutex, RwLock};
|
||||||
|
|
||||||
use shanty_data::MusicBrainzFetcher;
|
use shanty_data::HybridMusicBrainzFetcher;
|
||||||
use shanty_data::WikipediaFetcher;
|
use shanty_data::WikipediaFetcher;
|
||||||
use shanty_db::Database;
|
use shanty_db::Database;
|
||||||
use shanty_search::MusicBrainzSearch;
|
use shanty_search::MusicBrainzSearch;
|
||||||
|
|
||||||
use crate::config::AppConfig;
|
use crate::config::AppConfig;
|
||||||
use crate::tasks::TaskManager;
|
use crate::tasks::TaskManager;
|
||||||
|
use crate::workers::WorkerManager;
|
||||||
|
|
||||||
/// Tracks an active Firefox login session for YouTube auth.
|
/// Tracks an active Firefox login session for YouTube auth.
|
||||||
pub struct FirefoxLoginSession {
|
pub struct FirefoxLoginSession {
|
||||||
pub vnc_url: String,
|
pub vnc_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tracks next-run times for scheduled background tasks.
|
|
||||||
pub struct SchedulerInfo {
|
|
||||||
/// When the next pipeline run is scheduled (None if disabled).
|
|
||||||
pub next_pipeline: Option<chrono::NaiveDateTime>,
|
|
||||||
/// When the next monitor check is scheduled (None if disabled).
|
|
||||||
pub next_monitor: Option<chrono::NaiveDateTime>,
|
|
||||||
/// Skip the next pipeline run (one-shot, resets after skip).
|
|
||||||
pub skip_pipeline: bool,
|
|
||||||
/// Skip the next monitor run (one-shot, resets after skip).
|
|
||||||
pub skip_monitor: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub db: Database,
|
pub db: Database,
|
||||||
pub mb_client: MusicBrainzFetcher,
|
pub mb_client: HybridMusicBrainzFetcher,
|
||||||
pub search: MusicBrainzSearch,
|
pub search: MusicBrainzSearch,
|
||||||
pub wiki_fetcher: WikipediaFetcher,
|
pub wiki_fetcher: WikipediaFetcher,
|
||||||
pub config: Arc<RwLock<AppConfig>>,
|
pub config: Arc<RwLock<AppConfig>>,
|
||||||
pub config_path: Option<String>,
|
pub config_path: Option<String>,
|
||||||
pub tasks: TaskManager,
|
pub tasks: TaskManager,
|
||||||
|
pub workers: WorkerManager,
|
||||||
pub firefox_login: Mutex<Option<FirefoxLoginSession>>,
|
pub firefox_login: Mutex<Option<FirefoxLoginSession>>,
|
||||||
pub scheduler: Mutex<SchedulerInfo>,
|
|
||||||
}
|
}
|
||||||
|
|||||||
431
src/workers.rs
Normal file
431
src/workers.rs
Normal file
@@ -0,0 +1,431 @@
|
|||||||
|
//! Work queue workers that process pipeline items concurrently.
|
||||||
|
//!
|
||||||
|
//! Each task type (Download, Index, Tag, Organize) has a dedicated worker loop
|
||||||
|
//! that polls the work_queue table and processes items with bounded concurrency.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use actix_web::web;
|
||||||
|
use sea_orm::ActiveValue::Set;
|
||||||
|
use tokio::sync::{Notify, Semaphore};
|
||||||
|
|
||||||
|
use shanty_db::entities::download_queue::DownloadStatus;
|
||||||
|
use shanty_db::entities::wanted_item::WantedStatus;
|
||||||
|
use shanty_db::entities::work_queue::WorkTaskType;
|
||||||
|
use shanty_db::queries;
|
||||||
|
use shanty_dl::DownloadBackend;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Manages worker notification channels and spawns worker loops.
|
||||||
|
pub struct WorkerManager {
|
||||||
|
notifiers: HashMap<WorkTaskType, Arc<Notify>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for WorkerManager {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WorkerManager {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let mut notifiers = HashMap::new();
|
||||||
|
notifiers.insert(WorkTaskType::Download, Arc::new(Notify::new()));
|
||||||
|
notifiers.insert(WorkTaskType::Index, Arc::new(Notify::new()));
|
||||||
|
notifiers.insert(WorkTaskType::Tag, Arc::new(Notify::new()));
|
||||||
|
notifiers.insert(WorkTaskType::Organize, Arc::new(Notify::new()));
|
||||||
|
Self { notifiers }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wake the worker for a specific task type.
|
||||||
|
pub fn notify(&self, task_type: WorkTaskType) {
|
||||||
|
if let Some(n) = self.notifiers.get(&task_type) {
|
||||||
|
n.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn all worker loops and run startup recovery.
|
||||||
|
pub fn spawn_all(state: web::Data<AppState>) {
|
||||||
|
let state_clone = state.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Reset any items stuck in Running from a previous crash
|
||||||
|
match queries::work_queue::reset_stale_running(state_clone.db.conn()).await {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
tracing::info!(count, "reset stale running work queue items");
|
||||||
|
}
|
||||||
|
Err(e) => tracing::error!(error = %e, "failed to reset stale work queue items"),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Periodic cleanup of old completed items (every 6 hours)
|
||||||
|
let cleanup_state = state_clone.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(6 * 3600)).await;
|
||||||
|
let _ = queries::work_queue::cleanup_completed(cleanup_state.db.conn(), 7).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Spawn each worker type
|
||||||
|
spawn_worker(state.clone(), WorkTaskType::Download, 1);
|
||||||
|
spawn_worker(state.clone(), WorkTaskType::Index, 4);
|
||||||
|
spawn_worker(state.clone(), WorkTaskType::Tag, 2);
|
||||||
|
spawn_worker(state.clone(), WorkTaskType::Organize, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_worker(state: web::Data<AppState>, task_type: WorkTaskType, concurrency: usize) {
|
||||||
|
let notify = state
|
||||||
|
.workers
|
||||||
|
.notifiers
|
||||||
|
.get(&task_type)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| Arc::new(Notify::new()));
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
// Wait for notification or poll timeout
|
||||||
|
tokio::select! {
|
||||||
|
_ = notify.notified() => {}
|
||||||
|
_ = tokio::time::sleep(std::time::Duration::from_secs(5)) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Claim pending items
|
||||||
|
let items = match queries::work_queue::claim_next(
|
||||||
|
state.db.conn(),
|
||||||
|
task_type,
|
||||||
|
concurrency as u64,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(items) => items,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(task_type = %task_type, error = %e, "failed to claim work items");
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if items.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
|
||||||
|
for item in items {
|
||||||
|
let permit = semaphore.clone().acquire_owned().await.unwrap();
|
||||||
|
let state = state.clone();
|
||||||
|
let item_id = item.id;
|
||||||
|
let item_task_type = item.task_type;
|
||||||
|
let pipeline_id = item.pipeline_id.clone();
|
||||||
|
|
||||||
|
handles.push(tokio::spawn(async move {
|
||||||
|
let _permit = permit;
|
||||||
|
|
||||||
|
let result = match item_task_type {
|
||||||
|
WorkTaskType::Download => process_download(&state, &item).await,
|
||||||
|
WorkTaskType::Index => process_index(&state, &item).await,
|
||||||
|
WorkTaskType::Tag => process_tag(&state, &item).await,
|
||||||
|
WorkTaskType::Organize => process_organize(&state, &item).await,
|
||||||
|
};
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(downstream) => {
|
||||||
|
if let Err(e) =
|
||||||
|
queries::work_queue::complete(state.db.conn(), item_id).await
|
||||||
|
{
|
||||||
|
tracing::error!(id = item_id, error = %e, "failed to mark work item complete");
|
||||||
|
}
|
||||||
|
// Enqueue downstream items
|
||||||
|
for (task_type, payload) in downstream {
|
||||||
|
if let Err(e) = queries::work_queue::enqueue(
|
||||||
|
state.db.conn(),
|
||||||
|
task_type,
|
||||||
|
&payload,
|
||||||
|
pipeline_id.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(
|
||||||
|
error = %e,
|
||||||
|
"failed to enqueue downstream work item"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
state.workers.notify(task_type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(
|
||||||
|
id = item_id,
|
||||||
|
task_type = %item_task_type,
|
||||||
|
error = %error,
|
||||||
|
"work item failed"
|
||||||
|
);
|
||||||
|
if let Err(e) =
|
||||||
|
queries::work_queue::fail(state.db.conn(), item_id, &error).await
|
||||||
|
{
|
||||||
|
tracing::error!(id = item_id, error = %e, "failed to mark work item failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
for handle in handles {
|
||||||
|
let _ = handle.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Worker implementations ---
|
||||||
|
|
||||||
|
type WorkResult = Result<Vec<(WorkTaskType, String)>, String>;
|
||||||
|
|
||||||
|
async fn process_download(
|
||||||
|
state: &web::Data<AppState>,
|
||||||
|
item: &shanty_db::entities::work_queue::Model,
|
||||||
|
) -> WorkResult {
|
||||||
|
let payload: serde_json::Value =
|
||||||
|
serde_json::from_str(&item.payload_json).map_err(|e| e.to_string())?;
|
||||||
|
let dl_queue_id = payload
|
||||||
|
.get("download_queue_id")
|
||||||
|
.and_then(|v| v.as_i64())
|
||||||
|
.map(|v| v as i32);
|
||||||
|
|
||||||
|
let conn = state.db.conn();
|
||||||
|
|
||||||
|
// Get the download queue item — either specific ID or next pending
|
||||||
|
let dl_item = if let Some(id) = dl_queue_id {
|
||||||
|
queries::downloads::list(conn, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.into_iter()
|
||||||
|
.find(|i| i.id == id)
|
||||||
|
} else {
|
||||||
|
queries::downloads::get_next_pending(conn)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
};
|
||||||
|
|
||||||
|
let dl_item = match dl_item {
|
||||||
|
Some(item) => item,
|
||||||
|
None => return Ok(vec![]), // Nothing to download
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mark as downloading
|
||||||
|
queries::downloads::update_status(conn, dl_item.id, DownloadStatus::Downloading, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Build download backend from config
|
||||||
|
let cfg = state.config.read().await.clone();
|
||||||
|
let cookies = cfg.download.cookies_path.clone();
|
||||||
|
let format: shanty_dl::AudioFormat = cfg
|
||||||
|
.download
|
||||||
|
.format
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(shanty_dl::AudioFormat::Opus);
|
||||||
|
let source: shanty_dl::SearchSource = cfg
|
||||||
|
.download
|
||||||
|
.search_source
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(shanty_dl::SearchSource::YouTubeMusic);
|
||||||
|
let rate = if cookies.is_some() {
|
||||||
|
cfg.download.rate_limit_auth
|
||||||
|
} else {
|
||||||
|
cfg.download.rate_limit
|
||||||
|
};
|
||||||
|
|
||||||
|
let backend = shanty_dl::YtDlpBackend::new(rate, source, cookies.clone());
|
||||||
|
let backend_config = shanty_dl::BackendConfig {
|
||||||
|
output_dir: cfg.download_path.clone(),
|
||||||
|
format,
|
||||||
|
cookies_path: cookies,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Determine download target
|
||||||
|
let target = if let Some(ref url) = dl_item.source_url {
|
||||||
|
shanty_dl::DownloadTarget::Url(url.clone())
|
||||||
|
} else {
|
||||||
|
shanty_dl::DownloadTarget::Query(dl_item.query.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
// Execute download
|
||||||
|
let result = backend
|
||||||
|
.download(&target, &backend_config)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Mark download_queue entry as completed
|
||||||
|
queries::downloads::update_status(conn, dl_item.id, DownloadStatus::Completed, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Create track record if linked to a wanted item (same logic as shanty-dl queue.rs)
|
||||||
|
let mut downstream = Vec::new();
|
||||||
|
if let Some(wanted_item_id) = dl_item.wanted_item_id {
|
||||||
|
let wanted = queries::wanted::get_by_id(conn, wanted_item_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let file_size = std::fs::metadata(&result.file_path)
|
||||||
|
.map(|m| m.len() as i64)
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().naive_utc();
|
||||||
|
let track_active = shanty_db::entities::track::ActiveModel {
|
||||||
|
file_path: Set(result.file_path.to_string_lossy().to_string()),
|
||||||
|
title: Set(Some(result.title.clone())),
|
||||||
|
artist: Set(result.artist.clone()),
|
||||||
|
file_size: Set(file_size),
|
||||||
|
musicbrainz_id: Set(wanted.musicbrainz_id.clone()),
|
||||||
|
artist_id: Set(wanted.artist_id),
|
||||||
|
added_at: Set(now),
|
||||||
|
updated_at: Set(now),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let track = queries::tracks::upsert(conn, track_active)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
queries::wanted::update_status(conn, wanted_item_id, WantedStatus::Downloaded)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Create Tag work item for this track
|
||||||
|
let tag_payload = serde_json::json!({"track_id": track.id});
|
||||||
|
downstream.push((WorkTaskType::Tag, tag_payload.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = queries::cache::purge_prefix(conn, "artist_totals:").await;
|
||||||
|
Ok(downstream)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn process_index(
|
||||||
|
state: &web::Data<AppState>,
|
||||||
|
item: &shanty_db::entities::work_queue::Model,
|
||||||
|
) -> WorkResult {
|
||||||
|
let payload: serde_json::Value =
|
||||||
|
serde_json::from_str(&item.payload_json).map_err(|e| e.to_string())?;
|
||||||
|
let conn = state.db.conn();
|
||||||
|
let cfg = state.config.read().await.clone();
|
||||||
|
let mut downstream = Vec::new();
|
||||||
|
|
||||||
|
if payload.get("scan_all").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||||
|
// Full library scan
|
||||||
|
let scan_config = shanty_index::ScanConfig {
|
||||||
|
root: cfg.library_path.clone(),
|
||||||
|
dry_run: false,
|
||||||
|
concurrency: cfg.indexing.concurrency,
|
||||||
|
};
|
||||||
|
shanty_index::run_scan(conn, &scan_config)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Create Tag work items for all untagged tracks
|
||||||
|
let untagged = queries::tracks::get_needing_metadata(conn)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
for track in &untagged {
|
||||||
|
let tag_payload = serde_json::json!({"track_id": track.id});
|
||||||
|
downstream.push((WorkTaskType::Tag, tag_payload.to_string()));
|
||||||
|
}
|
||||||
|
} else if let Some(file_path) = payload.get("file_path").and_then(|v| v.as_str()) {
|
||||||
|
// Single file index
|
||||||
|
let path = std::path::PathBuf::from(file_path);
|
||||||
|
let track_id = shanty_index::index_file(conn, &path, false)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if let Some(id) = track_id {
|
||||||
|
let tag_payload = serde_json::json!({"track_id": id});
|
||||||
|
downstream.push((WorkTaskType::Tag, tag_payload.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(downstream)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn process_tag(
|
||||||
|
state: &web::Data<AppState>,
|
||||||
|
item: &shanty_db::entities::work_queue::Model,
|
||||||
|
) -> WorkResult {
|
||||||
|
let payload: serde_json::Value =
|
||||||
|
serde_json::from_str(&item.payload_json).map_err(|e| e.to_string())?;
|
||||||
|
let track_id = payload
|
||||||
|
.get("track_id")
|
||||||
|
.and_then(|v| v.as_i64())
|
||||||
|
.ok_or("missing track_id in payload")?
|
||||||
|
as i32;
|
||||||
|
|
||||||
|
let conn = state.db.conn();
|
||||||
|
let cfg = state.config.read().await.clone();
|
||||||
|
|
||||||
|
let track = queries::tracks::get_by_id(conn, track_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let tag_config = shanty_tag::TagConfig {
|
||||||
|
dry_run: false,
|
||||||
|
write_tags: cfg.tagging.write_tags,
|
||||||
|
confidence: cfg.tagging.confidence,
|
||||||
|
};
|
||||||
|
|
||||||
|
shanty_tag::tag_track(conn, &state.mb_client, &track, &tag_config)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Create Organize work item
|
||||||
|
let org_payload = serde_json::json!({"track_id": track_id});
|
||||||
|
Ok(vec![(WorkTaskType::Organize, org_payload.to_string())])
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn process_organize(
|
||||||
|
state: &web::Data<AppState>,
|
||||||
|
item: &shanty_db::entities::work_queue::Model,
|
||||||
|
) -> WorkResult {
|
||||||
|
let payload: serde_json::Value =
|
||||||
|
serde_json::from_str(&item.payload_json).map_err(|e| e.to_string())?;
|
||||||
|
let track_id = payload
|
||||||
|
.get("track_id")
|
||||||
|
.and_then(|v| v.as_i64())
|
||||||
|
.ok_or("missing track_id in payload")?
|
||||||
|
as i32;
|
||||||
|
|
||||||
|
let conn = state.db.conn();
|
||||||
|
let cfg = state.config.read().await.clone();
|
||||||
|
|
||||||
|
let org_config = shanty_org::OrgConfig {
|
||||||
|
target_dir: cfg.library_path.clone(),
|
||||||
|
format: cfg.organization_format.clone(),
|
||||||
|
dry_run: false,
|
||||||
|
copy: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
shanty_org::organize_track(conn, track_id, &org_config)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Promote this track's wanted item from Downloaded to Owned
|
||||||
|
let _ = queries::wanted::promote_downloaded_to_owned(conn).await;
|
||||||
|
|
||||||
|
// Check if pipeline is complete and trigger enrichment
|
||||||
|
if let Some(ref pipeline_id) = item.pipeline_id
|
||||||
|
&& let Ok(true) = queries::work_queue::pipeline_is_complete(conn, pipeline_id).await
|
||||||
|
{
|
||||||
|
tracing::info!(pipeline_id = %pipeline_id, "pipeline complete, triggering enrichment");
|
||||||
|
let state = state.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = crate::routes::artists::enrich_all_watched_artists(&state).await {
|
||||||
|
tracing::error!(error = %e, "post-pipeline enrichment failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(vec![])
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user