mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-22 14:35:41 +00:00
refactor: extract psysonic-syncfs crate (M4/7)
Moves all on-disk cache + device-sync code out of the top crate:
crates/psysonic-syncfs/ new lib crate
src/cache/{offline,hot,downloads,fs_utils} unchanged behaviour
src/sync/{batch,device} (no tray.rs — that's UI)
src/file_transfer.rs shared HTTP helpers
src/lib.rs + DownloadSemaphore type
+ sync_cancel_flags fn
The shell crate keeps `lib_commands/sync/tray.rs` (OS tray icon — UI
concern, will move to shell-tauri at M7) but drops the rest of
`lib_commands/cache/` and the syncfs sibling files.
Tauri command quirk surfaced and resolved: `#[tauri::command]` puts its
`__cmd__*` and `__tauri_command_name_*` helper macros at the *exact*
module of the function, and `pub use` doesn't carry them across module
boundaries. invoke_handler! in lib.rs now references each syncfs
command via its full deepest path
(`psysonic_syncfs::cache::offline::download_track_offline`, etc.) so
Tauri's macros resolve at the right scope. Same approach the audio
crate already uses (`audio::commands::audio_play`).
Cross-crate ref migrations applied via batch sed:
crate::audio::* → psysonic_audio::*
crate::analysis_runtime::* → psysonic_analysis::analysis_runtime::*
crate::analysis_cache::* → psysonic_analysis::analysis_cache::*
crate::subsonic_wire_user_agent → psysonic_core::user_agent::*
super::super::file_transfer:: → crate::file_transfer::
Behaviour preserving. Cargo check + clippy --workspace clean.
This commit is contained in:
@@ -0,0 +1,532 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tauri::Emitter;
|
||||
|
||||
use crate::sync_cancel_flags;
|
||||
|
||||
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
|
||||
use super::device::{
|
||||
build_track_path, get_removable_drives, is_path_on_mounted_volume, SyncBatchResult,
|
||||
TrackSyncInfo,
|
||||
};
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_device_dir_files(dir: String) -> Result<Vec<String>, String> {
|
||||
let root = std::path::PathBuf::from(&dir);
|
||||
if !root.exists() {
|
||||
return Err("VOLUME_NOT_FOUND".to_string());
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut stack = vec![root];
|
||||
while let Some(current) = stack.pop() {
|
||||
let mut rd = match tokio::fs::read_dir(¤t).await {
|
||||
Ok(r) => r,
|
||||
Err(_) => continue,
|
||||
};
|
||||
while let Ok(Some(entry)) = rd.next_entry().await {
|
||||
let path = entry.path();
|
||||
// Skip hidden dirs (e.g. .Trash-1000, .Ventoy, .fseventsd)
|
||||
let is_hidden = path.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.map(|n| n.starts_with('.'))
|
||||
.unwrap_or(false);
|
||||
if is_hidden { continue; }
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else {
|
||||
files.push(path.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
/// Deletes a file from the device and prunes empty parent directories
|
||||
/// (up to 2 levels: album folder, then artist folder).
|
||||
#[tauri::command]
|
||||
pub async fn delete_device_file(path: String) -> Result<(), String> {
|
||||
let p = std::path::PathBuf::from(&path);
|
||||
if p.exists() {
|
||||
tokio::fs::remove_file(&p).await.map_err(|e| e.to_string())?;
|
||||
prune_empty_parents(&p, 2).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prune empty parent directories up to `levels` levels above `file_path`.
|
||||
pub async fn prune_empty_parents(file_path: &std::path::Path, levels: usize) {
|
||||
let mut current = file_path.parent().map(|d| d.to_path_buf());
|
||||
for _ in 0..levels {
|
||||
let Some(dir) = current else { break };
|
||||
let is_empty = std::fs::read_dir(&dir)
|
||||
.map(|mut rd| rd.next().is_none())
|
||||
.unwrap_or(false);
|
||||
if is_empty {
|
||||
let _ = tokio::fs::remove_dir(&dir).await;
|
||||
current = dir.parent().map(|d| d.to_path_buf());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SubsonicAuthPayload {
|
||||
base_url: String,
|
||||
u: String,
|
||||
t: String,
|
||||
s: String,
|
||||
v: String,
|
||||
c: String,
|
||||
f: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Clone)]
|
||||
pub struct DeviceSyncSourcePayload {
|
||||
#[serde(rename = "type")]
|
||||
source_type: String,
|
||||
id: String,
|
||||
/// Playlist display name — only present for playlist sources, used when
|
||||
/// computing the playlist-folder path on the device.
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncDeltaResult {
|
||||
add_bytes: u64,
|
||||
add_count: u32,
|
||||
del_bytes: u64,
|
||||
del_count: u32,
|
||||
available_bytes: u64,
|
||||
tracks: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub async fn fetch_subsonic_songs(
|
||||
client: &reqwest::Client,
|
||||
auth: &SubsonicAuthPayload,
|
||||
endpoint: &str,
|
||||
id: &str,
|
||||
) -> Result<Vec<serde_json::Value>, String> {
|
||||
let url = format!("{}/{}", auth.base_url, endpoint);
|
||||
let query = vec![
|
||||
("u", auth.u.as_str()),
|
||||
("t", auth.t.as_str()),
|
||||
("s", auth.s.as_str()),
|
||||
("v", auth.v.as_str()),
|
||||
("c", auth.c.as_str()),
|
||||
("f", auth.f.as_str()),
|
||||
("id", id),
|
||||
];
|
||||
let res = client.get(&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())?;
|
||||
|
||||
let root = json.get("subsonic-response").ok_or("No subsonic-response".to_string())?;
|
||||
let songs = if endpoint == "getAlbum.view" {
|
||||
root.get("album").and_then(|a| a.get("song"))
|
||||
} else if endpoint == "getPlaylist.view" {
|
||||
root.get("playlist").and_then(|p| p.get("entry"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(arr) = songs.and_then(|s| s.as_array()) {
|
||||
return Ok(arr.clone());
|
||||
} else if let Some(obj) = songs.and_then(|s| s.as_object()) {
|
||||
return Ok(vec![serde_json::Value::Object(obj.clone())]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn calculate_sync_payload(
|
||||
sources: Vec<DeviceSyncSourcePayload>,
|
||||
deletion_ids: Vec<String>,
|
||||
auth: SubsonicAuthPayload,
|
||||
target_dir: String,
|
||||
) -> Result<SyncDeltaResult, String> {
|
||||
let client = subsonic_http_client(std::time::Duration::from_secs(30))?;
|
||||
|
||||
let mut add_bytes = 0;
|
||||
let mut add_count = 0;
|
||||
let mut del_bytes = 0;
|
||||
let mut del_count = 0;
|
||||
|
||||
let mut sync_tracks = Vec::new();
|
||||
let (mut del_sources, mut add_sources) = (Vec::new(), Vec::new());
|
||||
for s in sources {
|
||||
if deletion_ids.contains(&s.id) {
|
||||
del_sources.push(s);
|
||||
} else {
|
||||
add_sources.push(s);
|
||||
}
|
||||
}
|
||||
|
||||
let mut handles: Vec<(DeviceSyncSourcePayload, tokio::task::JoinHandle<Vec<serde_json::Value>>)> = Vec::new();
|
||||
for source in add_sources {
|
||||
let auth_clone = SubsonicAuthPayload {
|
||||
base_url: auth.base_url.clone(), u: auth.u.clone(), t: auth.t.clone(), s: auth.s.clone(),
|
||||
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
|
||||
};
|
||||
let cli = client.clone();
|
||||
let source_snapshot = source.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
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); }
|
||||
} 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); }
|
||||
} 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(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().map(|a| a.clone()).unwrap_or_else(|| {
|
||||
root.as_object().map(|o| vec![serde_json::Value::Object(o.clone())]).unwrap_or_else(|| vec![])
|
||||
});
|
||||
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 {
|
||||
res_tracks.extend(ts);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
res_tracks
|
||||
});
|
||||
handles.push((source_snapshot, handle));
|
||||
}
|
||||
|
||||
let mut del_handles = Vec::new();
|
||||
for source in del_sources {
|
||||
let auth_clone = SubsonicAuthPayload {
|
||||
base_url: auth.base_url.clone(), u: auth.u.clone(), t: auth.t.clone(), s: auth.s.clone(),
|
||||
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
|
||||
};
|
||||
let cli = client.clone();
|
||||
del_handles.push(tokio::spawn(async move {
|
||||
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); }
|
||||
} 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); }
|
||||
}
|
||||
res_tracks
|
||||
}));
|
||||
}
|
||||
|
||||
// Dedup key is (source_id, track_id) rather than just track_id — a track
|
||||
// appearing in both an album and a playlist needs to end up on the device
|
||||
// in both locations (album tree + playlist folder).
|
||||
let mut seen_by_source: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
|
||||
for (source, handle) in handles {
|
||||
if let Ok(ts) = handle.await {
|
||||
let is_playlist = source.source_type == "playlist";
|
||||
let mut playlist_position: u32 = 0;
|
||||
for track in ts {
|
||||
if let Some(tid) = track.get("id").and_then(|i| i.as_str()) {
|
||||
let key = (source.id.clone(), tid.to_string());
|
||||
if seen_by_source.contains(&key) { continue; }
|
||||
seen_by_source.insert(key);
|
||||
if is_playlist { playlist_position += 1; }
|
||||
let pl_name = if is_playlist { source.name.clone() } else { None };
|
||||
let pl_idx = if is_playlist { Some(playlist_position) } else { None };
|
||||
|
||||
let already_exists = {
|
||||
let suffix = track.get("suffix").and_then(|s| s.as_str()).unwrap_or("mp3");
|
||||
let artist_raw = track.get("artist").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let album_artist = track.get("albumArtist")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or(artist_raw);
|
||||
let sync_info = TrackSyncInfo {
|
||||
id: tid.to_string(),
|
||||
url: String::new(),
|
||||
suffix: suffix.to_string(),
|
||||
artist: artist_raw.to_string(),
|
||||
album_artist: album_artist.to_string(),
|
||||
album: track.get("album").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||
title: track.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||
track_number: track.get("track").and_then(|v| v.as_u64()).map(|n| n as u32),
|
||||
duration: track.get("duration").and_then(|v| v.as_u64()).map(|n| n as u32),
|
||||
playlist_name: pl_name.clone(),
|
||||
playlist_index: pl_idx,
|
||||
};
|
||||
let relative = build_track_path(&sync_info);
|
||||
let file_name = format!("{}.{}", relative, suffix);
|
||||
std::path::Path::new(&target_dir).join(&file_name).exists()
|
||||
};
|
||||
if !already_exists {
|
||||
add_count += 1;
|
||||
let size = track.get("size").and_then(|s| s.as_u64()).unwrap_or_else(|| {
|
||||
track.get("duration").and_then(|d| d.as_u64()).unwrap_or(0) * 320_000 / 8
|
||||
});
|
||||
add_bytes += size;
|
||||
// Embed playlist context in the track JSON so the frontend
|
||||
// can pass it back to sync_batch_to_device without re-computing it.
|
||||
let mut track_with_ctx = track.clone();
|
||||
if let Some(obj) = track_with_ctx.as_object_mut() {
|
||||
if let Some(name) = &pl_name {
|
||||
obj.insert("_playlistName".to_string(), serde_json::Value::String(name.clone()));
|
||||
}
|
||||
if let Some(idx) = pl_idx {
|
||||
obj.insert("_playlistIndex".to_string(), serde_json::Value::Number(idx.into()));
|
||||
}
|
||||
}
|
||||
sync_tracks.push(track_with_ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for handle in del_handles {
|
||||
if let Ok(ts) = handle.await {
|
||||
for track in ts {
|
||||
del_count += 1;
|
||||
let size = track.get("size").and_then(|s| s.as_u64()).unwrap_or_else(|| {
|
||||
track.get("duration").and_then(|d| d.as_u64()).unwrap_or(0) * 320_000 / 8
|
||||
});
|
||||
del_bytes += size;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut available_bytes = 0;
|
||||
for drive in get_removable_drives() {
|
||||
if target_dir.starts_with(&drive.mount_point) {
|
||||
available_bytes = drive.available_space;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SyncDeltaResult {
|
||||
add_bytes, add_count, del_bytes, del_count, available_bytes, tracks: sync_tracks,
|
||||
})
|
||||
}
|
||||
|
||||
/// Signals a running `sync_batch_to_device` job to stop after its current tracks finish.
|
||||
#[tauri::command]
|
||||
pub fn cancel_device_sync(job_id: String, app: tauri::AppHandle) {
|
||||
if let Ok(flags) = sync_cancel_flags().lock() {
|
||||
if let Some(flag) = flags.get(&job_id) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let _ = app.emit("device:sync:cancelled", serde_json::json!({ "jobId": job_id }));
|
||||
}
|
||||
|
||||
/// Downloads a batch of tracks to a USB/SD device with controlled concurrency.
|
||||
/// At most 2 parallel writes run simultaneously to prevent I/O choking on USB.
|
||||
/// Emits throttled `device:sync:progress` events (max once per 500ms) and a
|
||||
/// final `device:sync:complete` event with the summary.
|
||||
#[tauri::command]
|
||||
pub async fn sync_batch_to_device(
|
||||
tracks: Vec<TrackSyncInfo>,
|
||||
dest_dir: String,
|
||||
job_id: String,
|
||||
expected_bytes: u64,
|
||||
app: tauri::AppHandle,
|
||||
) -> Result<SyncBatchResult, String> {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
let dest_root = std::path::PathBuf::from(&dest_dir);
|
||||
if !dest_root.exists() {
|
||||
return Err("VOLUME_NOT_FOUND".to_string());
|
||||
}
|
||||
// Safety: verify dest_dir is on an actual mounted volume, not the root FS.
|
||||
// This catches the case where a USB drive was unmounted but the empty
|
||||
// mount-point directory still exists — writing there fills the root partition.
|
||||
if !is_path_on_mounted_volume(&dest_root) {
|
||||
return Err("NOT_MOUNTED_VOLUME".to_string());
|
||||
}
|
||||
|
||||
// Safety: Ensure target logic hasn't exceeded physical volume capacities securely stopping dead bytes natively.
|
||||
let drives = get_removable_drives();
|
||||
let dest_canon = dest_root.canonicalize().unwrap_or_else(|_| dest_root.clone());
|
||||
let dest_str = dest_canon.to_string_lossy();
|
||||
|
||||
for drive in drives {
|
||||
if dest_str.starts_with(&drive.mount_point) {
|
||||
// Buffer of ~10 MB padding boundary natively mapped
|
||||
if expected_bytes > drive.available_space.saturating_sub(10_000_000) {
|
||||
return Err(format!("NOT_ENOUGH_SPACE"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Register a cancellation flag for this job.
|
||||
let cancel_flag = Arc::new(AtomicBool::new(false));
|
||||
if let Ok(mut flags) = sync_cancel_flags().lock() {
|
||||
flags.insert(job_id.clone(), cancel_flag.clone());
|
||||
}
|
||||
|
||||
// Shared reqwest client — reused across all downloads.
|
||||
let client = subsonic_http_client(Duration::from_secs(300))?;
|
||||
|
||||
// Concurrency limiter: max 2 parallel USB writes.
|
||||
let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(2));
|
||||
|
||||
// Counters.
|
||||
let done = std::sync::Arc::new(AtomicU32::new(0));
|
||||
let skipped = std::sync::Arc::new(AtomicU32::new(0));
|
||||
let failed = std::sync::Arc::new(AtomicU32::new(0));
|
||||
|
||||
// Throttled event emission (max once per 500ms).
|
||||
let last_emit = std::sync::Arc::new(Mutex::new(Instant::now()));
|
||||
let total = tracks.len() as u32;
|
||||
|
||||
let mut handles = Vec::with_capacity(tracks.len());
|
||||
|
||||
for track in tracks {
|
||||
let sem = semaphore.clone();
|
||||
let cli = client.clone();
|
||||
let app2 = app.clone();
|
||||
let job = job_id.clone();
|
||||
let dest = dest_dir.clone();
|
||||
let d = done.clone();
|
||||
let s = skipped.clone();
|
||||
let f = failed.clone();
|
||||
let le = last_emit.clone();
|
||||
let cancel = cancel_flag.clone();
|
||||
|
||||
handles.push(tokio::spawn(async move {
|
||||
let _permit = sem.acquire().await.expect("semaphore closed");
|
||||
|
||||
// Bail out if cancelled while waiting in the semaphore queue.
|
||||
if cancel.load(Ordering::Relaxed) { return; }
|
||||
|
||||
let relative = build_track_path(&track);
|
||||
let file_name = format!("{}.{}", relative, track.suffix);
|
||||
let dest_path = std::path::Path::new(&dest).join(&file_name);
|
||||
let path_str = dest_path.to_string_lossy().to_string();
|
||||
|
||||
let status;
|
||||
if dest_path.exists() {
|
||||
s.fetch_add(1, Ordering::Relaxed);
|
||||
status = "skipped";
|
||||
} else {
|
||||
// Ensure parent directories exist.
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
if let Err(e) = tokio::fs::create_dir_all(parent).await {
|
||||
f.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = app2.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job, "trackId": track.id, "status": "error",
|
||||
"error": e.to_string(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let response = match cli.get(&track.url).send().await {
|
||||
Ok(r) if r.status().is_success() => r,
|
||||
Ok(r) => {
|
||||
f.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = app2.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job, "trackId": track.id, "status": "error",
|
||||
"error": format!("HTTP {}", r.status().as_u16()),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
f.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = app2.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job, "trackId": track.id, "status": "error",
|
||||
"error": e.to_string(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let part_path = dest_path.with_extension(format!("{}.part", track.suffix));
|
||||
if let Err(e) = finalize_streamed_download(response, &dest_path, &part_path).await {
|
||||
f.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = app2.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job, "trackId": track.id, "status": "error",
|
||||
"error": e,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
d.fetch_add(1, Ordering::Relaxed);
|
||||
status = "done";
|
||||
}
|
||||
|
||||
// Throttled progress event — max once per 500ms.
|
||||
let should_emit = {
|
||||
let mut guard = le.lock().await;
|
||||
if guard.elapsed() >= Duration::from_millis(500) {
|
||||
*guard = Instant::now();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
if should_emit {
|
||||
let _ = app2.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job, "trackId": track.id, "status": status, "path": path_str,
|
||||
"done": d.load(Ordering::Relaxed),
|
||||
"skipped": s.load(Ordering::Relaxed),
|
||||
"failed": f.load(Ordering::Relaxed),
|
||||
"total": total,
|
||||
}));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
// Wait for all tasks to complete.
|
||||
for handle in handles {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
// Clean up the cancellation flag.
|
||||
let was_cancelled = cancel_flag.load(Ordering::Relaxed);
|
||||
if let Ok(mut flags) = sync_cancel_flags().lock() {
|
||||
flags.remove(&job_id);
|
||||
}
|
||||
|
||||
let result = SyncBatchResult {
|
||||
done: done.load(Ordering::Relaxed),
|
||||
skipped: skipped.load(Ordering::Relaxed),
|
||||
failed: failed.load(Ordering::Relaxed),
|
||||
};
|
||||
|
||||
// Final event so the frontend always sees 100%.
|
||||
let _ = app.emit("device:sync:complete", serde_json::json!({
|
||||
"jobId": job_id,
|
||||
"done": result.done,
|
||||
"skipped": result.skipped,
|
||||
"failed": result.failed,
|
||||
"total": total,
|
||||
"cancelled": was_cancelled,
|
||||
}));
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Deletes multiple files from the device in one call and prunes empty parent
|
||||
/// directories. Returns the number of files successfully deleted.
|
||||
#[tauri::command]
|
||||
pub async fn delete_device_files(paths: Vec<String>) -> Result<u32, String> {
|
||||
let mut deleted: u32 = 0;
|
||||
for path in &paths {
|
||||
let p = std::path::PathBuf::from(path);
|
||||
if p.exists() {
|
||||
if tokio::fs::remove_file(&p).await.is_ok() {
|
||||
deleted += 1;
|
||||
prune_empty_parents(&p, 2).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(deleted)
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
use tauri::Emitter;
|
||||
|
||||
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
|
||||
|
||||
// ─── Device Sync ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Information about a single mounted removable drive.
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
pub struct RemovableDrive {
|
||||
pub name: String,
|
||||
pub mount_point: String,
|
||||
pub available_space: u64,
|
||||
pub total_space: u64,
|
||||
pub file_system: String,
|
||||
pub is_removable: bool,
|
||||
}
|
||||
|
||||
/// Returns all currently mounted removable drives.
|
||||
/// On Linux these are typically USB sticks / SD cards under /media or /run/media.
|
||||
/// On macOS they appear under /Volumes. On Windows they are separate drive letters.
|
||||
#[tauri::command]
|
||||
pub fn get_removable_drives() -> Vec<RemovableDrive> {
|
||||
use sysinfo::Disks;
|
||||
let disks = Disks::new_with_refreshed_list();
|
||||
disks
|
||||
.list()
|
||||
.iter()
|
||||
.filter(|d| d.is_removable())
|
||||
.map(|d| RemovableDrive {
|
||||
name: d.name().to_string_lossy().to_string(),
|
||||
mount_point: d.mount_point().to_string_lossy().to_string(),
|
||||
available_space: d.available_space(),
|
||||
total_space: d.total_space(),
|
||||
file_system: d.file_system().to_string_lossy().to_string(),
|
||||
is_removable: true,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Writes a `psysonic-sync.json` manifest to the root of the target directory.
|
||||
/// The file records which sources (albums/playlists/artists) are synced to this
|
||||
/// device so that another machine can pick them up without relying on localStorage.
|
||||
#[tauri::command]
|
||||
pub fn write_device_manifest(dest_dir: String, sources: serde_json::Value) -> Result<(), String> {
|
||||
let path = std::path::Path::new(&dest_dir).join("psysonic-sync.json");
|
||||
// Manifest v2: fixed "{AlbumArtist}/{Album}/{TrackNum} - {Title}.{ext}" schema,
|
||||
// no user-configurable filename template. Readers still accept v1 manifests.
|
||||
let payload = serde_json::json!({
|
||||
"version": 2,
|
||||
"schema": "fixed-v1",
|
||||
"sources": sources
|
||||
});
|
||||
let json = serde_json::to_string_pretty(&payload).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Reads `psysonic-sync.json` from the target directory.
|
||||
/// Returns the parsed JSON value, or null if the file doesn't exist.
|
||||
#[tauri::command]
|
||||
pub fn read_device_manifest(dest_dir: String) -> Option<serde_json::Value> {
|
||||
let path = std::path::Path::new(&dest_dir).join("psysonic-sync.json");
|
||||
let content = std::fs::read_to_string(&path).ok()?;
|
||||
serde_json::from_str(&content).ok()
|
||||
}
|
||||
|
||||
/// Per-entry result for `rename_device_files`.
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct RenameResult {
|
||||
#[serde(rename = "oldPath")]
|
||||
old_path: String,
|
||||
#[serde(rename = "newPath")]
|
||||
new_path: String,
|
||||
ok: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Atomically renames files on the device from their old path to the new fixed-
|
||||
/// schema path. Intended for the migration flow when switching away from the
|
||||
/// user-configurable template. All paths are relative to `target_dir`.
|
||||
///
|
||||
/// After renaming, removes any directories left empty under `target_dir`
|
||||
/// (so stale `{OldArtist}/{OldAlbum}/` trees don't linger).
|
||||
///
|
||||
/// Returns a per-entry result so the UI can show which renames succeeded
|
||||
/// and which failed. Does not roll back on partial failure — each `fs::rename`
|
||||
/// is atomic, so nothing can be half-renamed.
|
||||
#[tauri::command]
|
||||
pub fn rename_device_files(
|
||||
target_dir: String,
|
||||
pairs: Vec<(String, String)>,
|
||||
) -> Result<Vec<RenameResult>, String> {
|
||||
let root = std::path::PathBuf::from(&target_dir);
|
||||
if !root.exists() {
|
||||
return Err("VOLUME_NOT_FOUND".to_string());
|
||||
}
|
||||
if !is_path_on_mounted_volume(&root) {
|
||||
return Err("NOT_MOUNTED_VOLUME".to_string());
|
||||
}
|
||||
|
||||
let mut results = Vec::with_capacity(pairs.len());
|
||||
for (old_rel, new_rel) in pairs {
|
||||
let old_abs = root.join(&old_rel);
|
||||
let new_abs = root.join(&new_rel);
|
||||
|
||||
let entry = if old_rel == new_rel {
|
||||
// Nothing to do, count as success so the UI can show "already correct".
|
||||
RenameResult { old_path: old_rel, new_path: new_rel, ok: true, error: None }
|
||||
} else if !old_abs.exists() {
|
||||
RenameResult {
|
||||
old_path: old_rel, new_path: new_rel,
|
||||
ok: false, error: Some("source not found".to_string()),
|
||||
}
|
||||
} else if new_abs.exists() {
|
||||
RenameResult {
|
||||
old_path: old_rel, new_path: new_rel,
|
||||
ok: false, error: Some("target already exists".to_string()),
|
||||
}
|
||||
} else {
|
||||
// Ensure target parent exists.
|
||||
if let Some(parent) = new_abs.parent() {
|
||||
if let Err(e) = std::fs::create_dir_all(parent) {
|
||||
results.push(RenameResult {
|
||||
old_path: old_rel, new_path: new_rel,
|
||||
ok: false, error: Some(format!("mkdir: {}", e)),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match std::fs::rename(&old_abs, &new_abs) {
|
||||
Ok(_) => RenameResult { old_path: old_rel, new_path: new_rel, ok: true, error: None },
|
||||
Err(e) => RenameResult {
|
||||
old_path: old_rel, new_path: new_rel,
|
||||
ok: false, error: Some(e.to_string()),
|
||||
},
|
||||
}
|
||||
};
|
||||
results.push(entry);
|
||||
}
|
||||
|
||||
// Clean up directories emptied by the renames. Walk depth-first and remove
|
||||
// any dir whose only remaining contents were the files we moved out.
|
||||
fn remove_empty_dirs(dir: &std::path::Path, root: &std::path::Path) {
|
||||
if dir == root { return; }
|
||||
let rd = match std::fs::read_dir(dir) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return,
|
||||
};
|
||||
let mut empty = true;
|
||||
let mut children: Vec<std::path::PathBuf> = Vec::new();
|
||||
for entry in rd.flatten() {
|
||||
let p = entry.path();
|
||||
if p.is_dir() { children.push(p); } else { empty = false; }
|
||||
}
|
||||
for child in children {
|
||||
remove_empty_dirs(&child, root);
|
||||
}
|
||||
// Re-check after recursion cleared subdirs.
|
||||
let still_empty = std::fs::read_dir(dir).map(|r| r.count() == 0).unwrap_or(false);
|
||||
if empty && still_empty {
|
||||
let _ = std::fs::remove_dir(dir);
|
||||
}
|
||||
}
|
||||
remove_empty_dirs(&root, &root);
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Writes an Extended-M3U playlist at `{dest_dir}/Playlists/{name}/{name}.m3u8`.
|
||||
/// References are sibling filenames (just `01 - Artist - Title.ext`) so the
|
||||
/// playlist is self-contained — moving/copying the folder anywhere keeps it
|
||||
/// working. Tracks are expected to be in playlist order (index starts at 1).
|
||||
#[tauri::command]
|
||||
pub fn write_playlist_m3u8(
|
||||
dest_dir: String,
|
||||
playlist_name: String,
|
||||
tracks: Vec<TrackSyncInfo>,
|
||||
) -> Result<(), String> {
|
||||
let safe_name = sanitize_or(&playlist_name, "Unnamed Playlist");
|
||||
let playlist_dir = std::path::Path::new(&dest_dir).join("Playlists").join(&safe_name);
|
||||
std::fs::create_dir_all(&playlist_dir).map_err(|e| e.to_string())?;
|
||||
let file_path = playlist_dir.join(format!("{}.m3u8", safe_name));
|
||||
|
||||
let mut body = String::from("#EXTM3U\n");
|
||||
for (i, track) in tracks.iter().enumerate() {
|
||||
let idx = (i as u32) + 1;
|
||||
let duration = track.duration.map(|d| d as i64).unwrap_or(-1);
|
||||
let display_artist = if track.artist.trim().is_empty() { &track.album_artist[..] } else { &track.artist[..] };
|
||||
let title = track.title.trim();
|
||||
body.push_str(&format!("#EXTINF:{},{} - {}\n", duration, display_artist.trim(), title));
|
||||
// Sibling filename — same shape as build_track_path's playlist branch.
|
||||
let artist_safe = sanitize_or(display_artist, "Unknown Artist");
|
||||
let title_safe = sanitize_or(title, "Unknown Title");
|
||||
body.push_str(&format!("{:02} - {} - {}.{}\n", idx, artist_safe, title_safe, track.suffix));
|
||||
}
|
||||
std::fs::write(&file_path, body).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Checks whether `path` sits on top of an active mount point (i.e. not the root
|
||||
/// filesystem). This prevents accidentally writing to `/media/usb` after the
|
||||
/// USB drive has been unmounted — at that point the path would fall through to `/`
|
||||
/// and fill the root partition.
|
||||
pub fn is_path_on_mounted_volume(path: &std::path::Path) -> bool {
|
||||
use sysinfo::Disks;
|
||||
let disks = Disks::new_with_refreshed_list();
|
||||
let canonical = match path.canonicalize() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return false, // path doesn't exist or isn't accessible
|
||||
};
|
||||
// On Windows, canonicalize() prepends "\\?\" (extended-path prefix).
|
||||
// Strip it so that "\\?\E:\Music" compares correctly against mount point "E:\".
|
||||
let canonical_raw = canonical.to_string_lossy().into_owned();
|
||||
#[cfg(target_os = "windows")]
|
||||
let canonical_str = canonical_raw.strip_prefix(r"\\?\").unwrap_or(&canonical_raw).to_string();
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let canonical_str = canonical_raw;
|
||||
// Find the longest mount-point prefix that matches this path.
|
||||
// Exclude the root "/" (or "C:\" on Windows) so we never "match" a fallback.
|
||||
let mut best_len: usize = 0;
|
||||
for disk in disks.list() {
|
||||
let mp = disk.mount_point().to_string_lossy().to_string();
|
||||
// Skip root mount points (Linux "/" and non-removable Windows drive roots like "C:\").
|
||||
// Do NOT skip removable Windows drives (e.g. "E:\") — those are valid sync targets.
|
||||
let is_windows_root = mp.len() == 3 && mp.ends_with(":\\") && !disk.is_removable();
|
||||
if mp == "/" || is_windows_root {
|
||||
continue;
|
||||
}
|
||||
if canonical_str.starts_with(&mp) && mp.len() > best_len {
|
||||
best_len = mp.len();
|
||||
}
|
||||
}
|
||||
best_len > 0
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Clone)]
|
||||
pub struct TrackSyncInfo {
|
||||
pub id: String,
|
||||
pub url: String,
|
||||
pub suffix: String,
|
||||
/// Track artist — used in Extended M3U (#EXTINF) entries so playlists display
|
||||
/// the actual performer rather than the album artist.
|
||||
pub artist: String,
|
||||
/// Album artist — used for the top-level folder so compilation albums stay together.
|
||||
/// Falls back to `artist` in the frontend when the server has no albumArtist tag.
|
||||
#[serde(rename = "albumArtist")]
|
||||
pub album_artist: String,
|
||||
pub album: String,
|
||||
pub title: String,
|
||||
#[serde(rename = "trackNumber")]
|
||||
pub track_number: Option<u32>,
|
||||
/// Duration in seconds — needed for Extended M3U (#EXTINF) playlist entries.
|
||||
#[serde(default)]
|
||||
pub duration: Option<u32>,
|
||||
/// When set, the track belongs to a playlist source and is placed under
|
||||
/// `Playlists/{name}/` with `playlist_index` as its filename prefix.
|
||||
/// Same track synced from both an album and a playlist source ends up twice
|
||||
/// on the device — once in the album tree, once in the playlist folder.
|
||||
#[serde(default, rename = "playlistName")]
|
||||
pub playlist_name: Option<String>,
|
||||
#[serde(default, rename = "playlistIndex")]
|
||||
pub playlist_index: Option<u32>,
|
||||
}
|
||||
|
||||
/// Summary returned by `sync_batch_to_device` after all tracks are processed.
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
pub struct SyncBatchResult {
|
||||
pub done: u32,
|
||||
pub skipped: u32,
|
||||
pub failed: u32,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct SyncTrackResult {
|
||||
pub path: String,
|
||||
pub skipped: bool,
|
||||
}
|
||||
|
||||
/// Replaces characters that are invalid in file/directory names on Windows and
|
||||
/// most Unix filesystems with an underscore, and trims leading/trailing dots and
|
||||
/// spaces which cause issues on Windows. Underscore (not deletion) so that "AC/DC"
|
||||
/// and "ACDC" don't collapse into the same folder.
|
||||
pub fn sanitize_path_component(s: &str) -> String {
|
||||
const INVALID: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
|
||||
let sanitized: String = s
|
||||
.chars()
|
||||
.map(|c| if INVALID.contains(&c) || c.is_control() { '_' } else { c })
|
||||
.collect();
|
||||
sanitized.trim_matches(|c| c == '.' || c == ' ').to_string()
|
||||
}
|
||||
|
||||
/// Sanitize and replace empty results with a placeholder — prevents paths like
|
||||
/// `//01 - .flac` when metadata is missing.
|
||||
pub fn sanitize_or(s: &str, fallback: &str) -> String {
|
||||
let cleaned = sanitize_path_component(s);
|
||||
if cleaned.is_empty() { fallback.to_string() } else { cleaned }
|
||||
}
|
||||
|
||||
/// Builds the fixed device path for a track. When the track carries a playlist
|
||||
/// context it goes into the playlist folder, otherwise into the album tree.
|
||||
///
|
||||
/// Album-tree: `{AlbumArtist}/{Album}/{TrackNum:02d} - {Title}.{ext}`
|
||||
/// Playlist: `Playlists/{PlaylistName}/{PlaylistIndex:02d} - {Artist} - {Title}.{ext}`
|
||||
pub fn build_track_path(track: &TrackSyncInfo) -> String {
|
||||
let relative = match (&track.playlist_name, track.playlist_index) {
|
||||
(Some(name), Some(idx)) => {
|
||||
let playlist = sanitize_or(name, "Unnamed Playlist");
|
||||
let artist = sanitize_or(&track.artist, "Unknown Artist");
|
||||
let title = sanitize_or(&track.title, "Unknown Title");
|
||||
format!("Playlists/{}/{:02} - {} - {}", playlist, idx, artist, title)
|
||||
}
|
||||
_ => {
|
||||
let album_artist = sanitize_or(&track.album_artist, "Unknown Artist");
|
||||
let album = sanitize_or(&track.album, "Unknown Album");
|
||||
let title = sanitize_or(&track.title, "Unknown Title");
|
||||
let track_num = track.track_number.map(|n| format!("{:02}", n)).unwrap_or_else(|| "00".to_string());
|
||||
format!("{}/{}/{} - {}", album_artist, album, track_num, title)
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
let relative = relative.replace('/', "\\");
|
||||
relative
|
||||
}
|
||||
|
||||
/// Downloads a single track to a USB/SD device using the configured filename template.
|
||||
/// Emits `device:sync:progress` events with `{ jobId, trackId, status, path? }`.
|
||||
#[tauri::command]
|
||||
pub async fn sync_track_to_device(
|
||||
track: TrackSyncInfo,
|
||||
dest_dir: String,
|
||||
job_id: String,
|
||||
app: tauri::AppHandle,
|
||||
) -> Result<SyncTrackResult, String> {
|
||||
let relative = build_track_path(&track);
|
||||
let file_name = format!("{}.{}", relative, track.suffix);
|
||||
let dest_path = std::path::Path::new(&dest_dir).join(&file_name);
|
||||
let path_str = dest_path.to_string_lossy().to_string();
|
||||
|
||||
if dest_path.exists() {
|
||||
let _ = app.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job_id, "trackId": track.id, "status": "skipped", "path": path_str,
|
||||
}));
|
||||
return Ok(SyncTrackResult { path: path_str, skipped: true });
|
||||
}
|
||||
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
let client = subsonic_http_client(std::time::Duration::from_secs(300))?;
|
||||
|
||||
let response = client.get(&track.url).send().await.map_err(|e| e.to_string())?;
|
||||
if !response.status().is_success() {
|
||||
let msg = format!("HTTP {}", response.status().as_u16());
|
||||
let _ = app.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job_id, "trackId": track.id, "status": "error", "error": msg,
|
||||
}));
|
||||
return Err(msg);
|
||||
}
|
||||
|
||||
let part_path = dest_path.with_extension(format!("{}.part", track.suffix));
|
||||
if let Err(e) = finalize_streamed_download(response, &dest_path, &part_path).await {
|
||||
let _ = app.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job_id, "trackId": track.id, "status": "error", "error": e,
|
||||
}));
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let _ = app.emit("device:sync:progress", serde_json::json!({
|
||||
"jobId": job_id, "trackId": track.id, "status": "done", "path": path_str,
|
||||
}));
|
||||
Ok(SyncTrackResult { path: path_str, skipped: false })
|
||||
}
|
||||
|
||||
/// Computes the expected file paths for a batch of tracks under the fixed schema.
|
||||
/// Used by the cleanup flow to find orphans.
|
||||
#[tauri::command]
|
||||
pub fn compute_sync_paths(tracks: Vec<TrackSyncInfo>, dest_dir: String) -> Vec<String> {
|
||||
tracks.iter().map(|track| {
|
||||
let relative = build_track_path(track);
|
||||
let file_name = format!("{}.{}", relative, track.suffix);
|
||||
std::path::Path::new(&dest_dir)
|
||||
.join(&file_name)
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}).collect()
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod batch;
|
||||
pub mod device;
|
||||
Reference in New Issue
Block a user