feat(server): custom HTTP headers for reverse-proxy gates (#1095) (#1156)

This commit is contained in:
cucadmuh
2026-06-22 16:25:28 +03:00
committed by GitHub
parent 2c9b2eeb46
commit 15cecb5d7d
83 changed files with 2452 additions and 327 deletions
+14 -1
View File
@@ -2,6 +2,8 @@ use tauri::{Emitter, Manager};
use psysonic_core::user_agent::subsonic_wire_user_agent;
use crate::file_transfer::apply_server_http_get;
pub fn resolve_hot_cache_root(
custom_dir: Option<String>,
app: &tauri::AppHandle,
@@ -340,7 +342,18 @@ pub async fn download_zip(
.build()
.map_err(|e| e.to_string())?;
let response = client.get(&url).send().await.map_err(|e| e.to_string())?;
let http_registry = app
.try_state::<std::sync::Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| std::sync::Arc::clone(&*s));
let response = apply_server_http_get(
&client,
http_registry.as_deref(),
None,
&url,
)
.send()
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
+12 -2
View File
@@ -1,8 +1,11 @@
use std::sync::Arc;
use psysonic_analysis::analysis_runtime::{enqueue_track_analysis, AnalysisBackfillPriority};
use psysonic_audio as audio;
use psysonic_core::user_agent::subsonic_wire_user_agent;
use tauri::Manager;
use crate::file_transfer::stream_to_file;
use crate::file_transfer::{apply_server_http_get, stream_to_file};
use super::downloads::{resolve_hot_cache_root, HotCacheDownloadResult};
use super::offline::enqueue_analysis_seed_from_file;
@@ -70,7 +73,14 @@ pub async fn download_track_hot_cache(
.build()
.map_err(|e| e.to_string())?;
let response = client.get(&url).send().await.map_err(|e| e.to_string())?;
let http_registry = app
.try_state::<Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| Arc::clone(&*s));
let response = apply_server_http_get(&client, http_registry.as_deref(), Some(&server_id), &url)
.send()
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
+13 -2
View File
@@ -22,7 +22,7 @@ use psysonic_library::repos::TrackRow;
use psysonic_library::{repos::TrackRepository, LibraryRuntime};
use tauri::{AppHandle, Manager, State};
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
use crate::file_transfer::{apply_server_http_get, finalize_streamed_download, subsonic_http_client};
use crate::{offline_cancel_flags, DownloadSemaphore};
use super::offline::enqueue_analysis_seed_from_file;
@@ -359,7 +359,18 @@ pub async fn download_track_local(
}
let client = subsonic_http_client(std::time::Duration::from_secs(120))?;
let response = client.get(&url).send().await.map_err(|e| e.to_string())?;
let http_registry = app
.try_state::<Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| Arc::clone(&*s));
let response = apply_server_http_get(
&client,
http_registry.as_deref(),
Some(&server_index_key),
&url,
)
.send()
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
+18 -7
View File
@@ -9,7 +9,7 @@ use psysonic_analysis::analysis_runtime::{
};
use crate::{offline_cancel_flags, DownloadSemaphore};
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
use crate::file_transfer::{apply_server_http_get, finalize_streamed_download, subsonic_http_client};
// ─── Offline Track Cache ──────────────────────────────────────────────────────
@@ -31,12 +31,15 @@ pub async fn enqueue_analysis_seed_from_file(
///
/// `cancel`, when supplied, aborts the in-flight stream with `Err("CANCELLED")`
/// (the `.part` file is cleaned up); `None` means the download is not cancellable.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn download_track_to_cache_dir(
cache_dir: &std::path::Path,
track_id: &str,
suffix: &str,
url: &str,
client: &reqwest::Client,
registry: Option<&psysonic_core::server_http::ServerHttpRegistry>,
server_ref: Option<&str>,
cancel: Option<&AtomicBool>,
) -> Result<std::path::PathBuf, String> {
tokio::fs::create_dir_all(cache_dir)
@@ -48,7 +51,10 @@ pub(crate) async fn download_track_to_cache_dir(
return Ok(file_path);
}
let response = client.get(url).send().await.map_err(|e| e.to_string())?;
let response = apply_server_http_get(client, registry, server_ref, url)
.send()
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
@@ -129,12 +135,17 @@ pub async fn download_track_offline(
}
let client = subsonic_http_client(std::time::Duration::from_secs(120))?;
let http_registry = app
.try_state::<Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| Arc::clone(&*s));
let final_path = download_track_to_cache_dir(
&cache_dir,
&track_id,
&suffix,
&url,
&client,
http_registry.as_deref(),
Some(&server_id),
cancel_flag.as_deref(),
)
.await?;
@@ -191,7 +202,7 @@ mod tests {
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/stream/track-1", server.uri());
let path = download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, None)
let path = download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, None, None, None)
.await
.unwrap();
assert!(path.exists());
@@ -211,7 +222,7 @@ mod tests {
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/should-not-be-hit", server.uri());
let path = download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, None)
let path = download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, None, None, None)
.await
.unwrap();
assert_eq!(path, pre_existing);
@@ -232,7 +243,7 @@ mod tests {
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/stream/missing", server.uri());
let err = download_track_to_cache_dir(&cache_dir, "missing", "flac", &url, &client, None)
let err = download_track_to_cache_dir(&cache_dir, "missing", "flac", &url, &client, None, None, None)
.await
.unwrap_err();
assert!(err.contains("HTTP 404"), "got {err}");
@@ -256,7 +267,7 @@ mod tests {
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/track", server.uri());
download_track_to_cache_dir(&cache_dir, "t", "mp3", &url, &client, None)
download_track_to_cache_dir(&cache_dir, "t", "mp3", &url, &client, None, None, None)
.await
.unwrap();
assert!(cache_dir.join("t.mp3").exists());
@@ -278,7 +289,7 @@ mod tests {
let cancel = AtomicBool::new(true);
let err =
download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, Some(&cancel))
download_track_to_cache_dir(&cache_dir, "track-1", "flac", &url, &client, None, None, Some(&cancel))
.await
.unwrap_err();
assert_eq!(err, "CANCELLED");
@@ -13,6 +13,20 @@ pub fn subsonic_http_client(timeout: Duration) -> Result<reqwest::Client, String
.map_err(|e| e.to_string())
}
pub fn apply_server_http_get(
client: &reqwest::Client,
registry: Option<&psysonic_core::server_http::ServerHttpRegistry>,
server_ref: Option<&str>,
url: &str,
) -> reqwest::RequestBuilder {
psysonic_core::server_http::apply_optional_registry_headers(
registry,
server_ref,
url,
client.get(url),
)
}
/// Streams an HTTP response body to `dest_path` in chunks. Never buffers the full
/// file in memory — keeps RAM flat regardless of file size.
///
@@ -1,11 +1,11 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tauri::Emitter;
use tauri::{Emitter, Manager};
use crate::sync_cancel_flags;
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
use crate::file_transfer::{apply_server_http_get, finalize_streamed_download, subsonic_http_client};
use super::device::{
build_track_path, get_removable_drives, is_path_on_mounted_volume, SyncBatchResult,
TrackSyncInfo,
@@ -107,6 +107,7 @@ pub struct SyncDeltaResult {
pub async fn fetch_subsonic_songs(
client: &reqwest::Client,
registry: Option<&psysonic_core::server_http::ServerHttpRegistry>,
auth: &SubsonicAuthPayload,
endpoint: &str,
id: &str,
@@ -121,7 +122,11 @@ pub async fn fetch_subsonic_songs(
("f", auth.f.as_str()),
("id", id),
];
let res = client.get(&url).query(&query).send().await.map_err(|e| e.to_string())?;
let res = apply_server_http_get(client, registry, None, &url)
.query(&query)
.send()
.await
.map_err(|e| e.to_string())?;
let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
parse_subsonic_songs(&json, endpoint)
}
@@ -239,8 +244,12 @@ pub async fn calculate_sync_payload(
deletion_ids: Vec<String>,
auth: SubsonicAuthPayload,
target_dir: String,
app: tauri::AppHandle,
) -> Result<SyncDeltaResult, String> {
let client = subsonic_http_client(std::time::Duration::from_secs(30))?;
let http_registry = app
.try_state::<Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| Arc::clone(&*s));
let mut add_bytes = 0;
let mut add_count = 0;
@@ -264,17 +273,19 @@ pub async fn calculate_sync_payload(
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
};
let cli = client.clone();
let reg_for_task = http_registry.clone();
let source_snapshot = source.clone();
let handle = tokio::spawn(async move {
let registry = reg_for_task.as_deref();
let mut res_tracks = Vec::new();
if source.source_type == "album" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
if let Ok(ts) = fetch_subsonic_songs(&cli, registry, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "playlist" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
if let Ok(ts) = fetch_subsonic_songs(&cli, registry, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "artist" {
let url = format!("{}/getArtist.view", auth_clone.base_url);
let query = vec![("u", auth_clone.u.as_str()), ("t", auth_clone.t.as_str()), ("s", auth_clone.s.as_str()), ("v", auth_clone.v.as_str()), ("c", auth_clone.c.as_str()), ("f", auth_clone.f.as_str()), ("id", &source.id)];
if let Ok(re) = cli.get(&url).query(&query).send().await {
if let Ok(re) = apply_server_http_get(&cli, registry, None, &url).query(&query).send().await {
if let Ok(js) = re.json::<serde_json::Value>().await {
if let Some(root) = js.get("subsonic-response").and_then(|r| r.get("artist")).and_then(|a| a.get("album")) {
let arr = root.as_array().cloned().unwrap_or_else(|| {
@@ -282,7 +293,7 @@ pub async fn calculate_sync_payload(
});
for al in arr {
if let Some(aid) = al.get("id").and_then(|i| i.as_str()) {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", aid).await {
if let Ok(ts) = fetch_subsonic_songs(&cli, registry, &auth_clone, "getAlbum.view", aid).await {
res_tracks.extend(ts);
}
}
@@ -303,12 +314,14 @@ pub async fn calculate_sync_payload(
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
};
let cli = client.clone();
let reg_for_task = http_registry.clone();
del_handles.push(tokio::spawn(async move {
let registry = reg_for_task.as_deref();
let mut res_tracks = Vec::new();
if source.source_type == "album" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
if let Ok(ts) = fetch_subsonic_songs(&cli, registry, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "playlist" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
if let Ok(ts) = fetch_subsonic_songs(&cli, registry, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
}
res_tracks
}));
@@ -437,6 +450,9 @@ pub async fn sync_batch_to_device(
// Shared reqwest client — reused across all downloads.
let client = subsonic_http_client(Duration::from_secs(300))?;
let http_registry = app
.try_state::<Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| Arc::clone(&*s));
// Concurrency limiter: max 2 parallel USB writes.
let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(2));
@@ -455,6 +471,7 @@ pub async fn sync_batch_to_device(
for track in tracks {
let sem = semaphore.clone();
let cli = client.clone();
let reg_for_task = http_registry.clone();
let app2 = app.clone();
let job = job_id.clone();
let dest = dest_dir.clone();
@@ -466,6 +483,7 @@ pub async fn sync_batch_to_device(
handles.push(tokio::spawn(async move {
let _permit = sem.acquire().await.expect("semaphore closed");
let registry = reg_for_task.as_deref();
// Bail out if cancelled while waiting in the semaphore queue.
if cancel.load(Ordering::Relaxed) { return; }
@@ -492,7 +510,7 @@ pub async fn sync_batch_to_device(
}
}
let response = match cli.get(&track.url).send().await {
let response = match apply_server_http_get(&cli, registry, None, &track.url).send().await {
Ok(r) if r.status().is_success() => r,
Ok(r) => {
f.fetch_add(1, Ordering::Relaxed);
@@ -819,7 +837,7 @@ mod tests {
let client = crate::file_transfer::subsonic_http_client(std::time::Duration::from_secs(5))
.unwrap();
let auth = fake_auth(server.uri());
let songs = fetch_subsonic_songs(&client, &auth, "getAlbum.view", "album-42")
let songs = fetch_subsonic_songs(&client, None, &auth, "getAlbum.view", "album-42")
.await
.unwrap();
assert_eq!(songs.len(), 2);
@@ -838,7 +856,7 @@ mod tests {
let client = crate::file_transfer::subsonic_http_client(std::time::Duration::from_secs(5))
.unwrap();
let auth = fake_auth(server.uri());
let result = fetch_subsonic_songs(&client, &auth, "getAlbum.view", "missing").await;
let result = fetch_subsonic_songs(&client, None, &auth, "getAlbum.view", "missing").await;
// 404 with HTML/empty body fails the JSON parse, surfacing as an Err — we
// just assert the function does not panic and propagates an error string.
assert!(result.is_err());
@@ -989,7 +1007,7 @@ mod tests {
let client = crate::file_transfer::subsonic_http_client(std::time::Duration::from_secs(5))
.unwrap();
let auth = fake_auth(server.uri());
let songs = fetch_subsonic_songs(&client, &auth, "getPlaylist.view", "p1")
let songs = fetch_subsonic_songs(&client, None, &auth, "getPlaylist.view", "p1")
.await
.unwrap();
assert_eq!(songs.len(), 1, "single-object response normalised to 1-element vec");
@@ -1,6 +1,6 @@
use tauri::Emitter;
use tauri::{Emitter, Manager};
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
use crate::file_transfer::{apply_server_http_get, finalize_streamed_download, subsonic_http_client};
// ─── Device Sync ─────────────────────────────────────────────────────────────
@@ -333,6 +333,8 @@ pub(crate) async fn sync_download_one_track(
suffix: &str,
url: &str,
client: &reqwest::Client,
registry: Option<&psysonic_core::server_http::ServerHttpRegistry>,
server_ref: Option<&str>,
) -> Result<bool, String> {
if dest_path.exists() {
return Ok(false);
@@ -342,7 +344,10 @@ pub(crate) async fn sync_download_one_track(
.await
.map_err(|e| e.to_string())?;
}
let response = client.get(url).send().await.map_err(|e| e.to_string())?;
let response = apply_server_http_get(client, registry, server_ref, url)
.send()
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
@@ -366,7 +371,19 @@ pub async fn sync_track_to_device(
let path_str = dest_path.to_string_lossy().to_string();
let client = subsonic_http_client(std::time::Duration::from_secs(300))?;
match sync_download_one_track(&dest_path, &track.suffix, &track.url, &client).await {
let http_registry = app
.try_state::<std::sync::Arc<psysonic_core::server_http::ServerHttpRegistry>>()
.map(|s| std::sync::Arc::clone(&*s));
match sync_download_one_track(
&dest_path,
&track.suffix,
&track.url,
&client,
http_registry.as_deref(),
None,
)
.await
{
Ok(false) => {
let _ = app.emit("device:sync:progress", serde_json::json!({
"jobId": job_id, "trackId": track.id, "status": "skipped", "path": path_str,
@@ -656,7 +673,7 @@ mod tests {
let dest = dir.path().join("Album").join("01 - track.flac");
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/track", server.uri());
let downloaded = sync_download_one_track(&dest, "flac", &url, &client)
let downloaded = sync_download_one_track(&dest, "flac", &url, &client, None, None)
.await
.unwrap();
assert!(downloaded, "fresh download must report Ok(true)");
@@ -672,7 +689,7 @@ mod tests {
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/should-not-be-hit", server.uri());
let downloaded = sync_download_one_track(&dest, "mp3", &url, &client)
let downloaded = sync_download_one_track(&dest, "mp3", &url, &client, None, None)
.await
.unwrap();
assert!(!downloaded, "pre-existing file must be reported as skipped");
@@ -692,7 +709,7 @@ mod tests {
let dest = dir.path().join("track.opus");
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/missing", server.uri());
let err = sync_download_one_track(&dest, "opus", &url, &client)
let err = sync_download_one_track(&dest, "opus", &url, &client, None, None)
.await
.unwrap_err();
assert!(err.contains("HTTP 403"));
@@ -714,7 +731,7 @@ mod tests {
assert!(!dest.parent().unwrap().exists());
let client = subsonic_http_client(std::time::Duration::from_secs(5)).unwrap();
let url = format!("{}/t", server.uri());
sync_download_one_track(&dest, "mp3", &url, &client)
sync_download_one_track(&dest, "mp3", &url, &client, None, None)
.await
.unwrap();
assert!(dest.exists());