Changing the music folder offers to move everything

- Move everything: files are moved (renamed on the same drive, copied across drives),
  with play counts, likes, history, playlists and linked folders carried over
- Or keep them where they are: the old folder stays in your library
- Name clashes keep both files; identical duplicates aren't copied twice
- Refused while downloads are running
This commit is contained in:
Christian
2026-11-19 01:18:09 -05:00
parent f081ca4a45
commit 9de1d3f117
5 changed files with 264 additions and 4 deletions
+136
View File
@@ -729,3 +729,139 @@ pub async fn artist_apply(state: State<'_, AppState>, name: String, photo: Optio
}
Ok(state.library.apply_artist_info(&name, found, true))
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FolderReport {
files: usize,
bytes: u64,
}
#[tauri::command]
pub async fn folder_report(path: String) -> FolderReport {
tauri::async_runtime::spawn_blocking(move || {
let mut files = 0;
let mut bytes = 0;
for e in walkdir::WalkDir::new(&path).into_iter().flatten().filter(|e| e.file_type().is_file()) {
files += 1;
bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
}
FolderReport { files, bytes }
})
.await
.unwrap_or(FolderReport { files: 0, bytes: 0 })
}
fn move_one(src: &Path, dest: &Path) -> std::io::Result<()> {
if let Some(dir) = dest.parent() {
std::fs::create_dir_all(dir)?;
}
if std::fs::rename(src, dest).is_ok() {
return Ok(());
}
std::fs::copy(src, dest)?;
std::fs::remove_file(src)
}
pub fn move_tree(from: &Path, to: &Path, mut progress: impl FnMut(usize, usize)) -> (usize, Vec<String>) {
let files: Vec<PathBuf> = walkdir::WalkDir::new(from).into_iter().flatten().filter(|e| e.file_type().is_file()).map(|e| e.into_path()).collect();
let total = files.len();
let mut moved = 0;
let mut failed = Vec::new();
for (i, src) in files.iter().enumerate() {
let Ok(rel) = src.strip_prefix(from) else { continue };
let mut dest = to.join(rel);
if dest.exists() {
let same = std::fs::metadata(&dest).ok().map(|m| m.len()) == std::fs::metadata(src).ok().map(|m| m.len());
if same {
if std::fs::remove_file(src).is_ok() {
moved += 1;
}
progress(i + 1, total);
continue;
}
let stem = dest.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let ext = dest.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
let mut n = 2;
while dest.exists() {
dest = dest.with_file_name(format!("{stem} ({n}){ext}"));
n += 1;
}
}
match move_one(src, &dest) {
Ok(()) => moved += 1,
Err(e) => failed.push(format!("{} ({e})", rel.display())),
}
if i % 10 == 0 || i + 1 == total {
progress(i + 1, total);
}
}
let mut dirs: Vec<PathBuf> = walkdir::WalkDir::new(from).into_iter().flatten().filter(|e| e.file_type().is_dir()).map(|e| e.into_path()).collect();
dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
for d in dirs {
let _ = std::fs::remove_dir(d);
}
(moved, failed)
}
#[tauri::command]
pub async fn move_music(app: AppHandle, state: State<'_, AppState>, to: String) -> CmdResult<serde_json::Value> {
if state.dl.busy() {
return Err("Wait for downloads to finish before moving your music.".into());
}
let s = state.snapshot();
let from = PathBuf::from(&s.output_dir);
let dest = PathBuf::from(&to);
if dest.starts_with(&from) || from.starts_with(&dest) {
return Err("Choose a folder that isn't inside the current one (or the other way round).".into());
}
std::fs::create_dir_all(&dest).map_err(|e| e.to_string())?;
let emitter = app.clone();
let (f2, d2) = (from.clone(), dest.clone());
let (moved, failed) = tauri::async_runtime::spawn_blocking(move || {
move_tree(&f2, &d2, |done, total| {
let _ = emitter.emit("atmosphere://move", serde_json::json!({ "done": done, "total": total }));
})
})
.await
.map_err(|e| e.to_string())?;
state.library.remap_paths(&from, &dest);
let remap = |p: &str| -> String { Path::new(p).strip_prefix(&from).map(|r| dest.join(r).to_string_lossy().into_owned()).unwrap_or_else(|_| p.to_string()) };
let view = state.update(|st| {
st.output_dir = dest.to_string_lossy().into_owned();
st.playlists_dir = remap(&st.playlists_dir);
let mut seen = std::collections::HashSet::new();
st.library_folders = st.library_folders.iter().map(|f| remap(f)).filter(|f| seen.insert(f.clone())).collect();
})?;
spawn_scan(app.clone());
start_watch(app.clone());
changed(&app);
Ok(serde_json::json!({ "moved": moved, "failed": failed, "outputDir": view.output_dir }))
}
#[cfg(test)]
mod move_tests {
use super::*;
#[test]
fn moves_a_tree_and_keeps_both_on_name_clashes() {
let root = std::env::temp_dir().join(format!("atmo-move-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (a, b) = (root.join("old"), root.join("new"));
std::fs::create_dir_all(a.join("Albums").join("X")).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(a.join("Albums").join("X").join("1.mp3"), b"one").unwrap();
std::fs::write(a.join("same.mp3"), b"same").unwrap();
std::fs::write(b.join("same.mp3"), b"same").unwrap();
std::fs::write(a.join("clash.mp3"), b"mine").unwrap();
std::fs::write(b.join("clash.mp3"), b"theirs!").unwrap();
let (moved, failed) = move_tree(&a, &b, |_, _| {});
assert!(failed.is_empty());
assert_eq!(moved, 3);
assert!(b.join("Albums").join("X").join("1.mp3").exists());
assert_eq!(std::fs::read(b.join("clash (2).mp3")).unwrap(), b"mine");
assert_eq!(std::fs::read(b.join("clash.mp3")).unwrap(), b"theirs!");
assert!(!a.join("Albums").exists());
let _ = std::fs::remove_dir_all(&root);
}
}
+74
View File
@@ -932,6 +932,58 @@ impl Library {
Ok(())
}
pub fn remap_paths(&self, from: &Path, to: &Path) -> usize {
let mut moved: HashMap<String, String> = HashMap::new();
{
let mut tracks = self.tracks.write().unwrap();
let old: Vec<Track> = tracks.values().filter(|t| Path::new(&t.path).starts_with(from)).cloned().collect();
for mut t in old {
let Ok(rel) = Path::new(&t.path).strip_prefix(from).map(Path::to_path_buf) else { continue };
let new_path = to.join(rel).to_string_lossy().into_owned();
let new_id = hash(&new_path);
tracks.remove(&t.id);
moved.insert(t.id.clone(), new_id.clone());
t.path = new_path;
t.id = new_id;
tracks.insert(t.id.clone(), t);
}
}
if moved.is_empty() {
return 0;
}
{
let mut s = self.stats.write().unwrap();
let remap = |id: &String| moved.get(id).cloned().unwrap_or_else(|| id.clone());
s.plays = s.plays.drain().map(|(k, v)| (remap(&k), v)).collect();
s.last_played = s.last_played.drain().map(|(k, v)| (remap(&k), v)).collect();
s.liked = s.liked.drain().map(|k| remap(&k)).collect();
for l in s.listens.iter_mut() {
l.id = remap(&l.id);
}
store("stats.json", &*s);
}
{
let mut hidden = self.hidden.write().unwrap();
let next: HashSet<String> = hidden
.drain()
.map(|p| Path::new(&p).strip_prefix(from).map(|r| to.join(r).to_string_lossy().into_owned()).unwrap_or(p))
.collect();
*hidden = next;
store("hidden.json", &*hidden);
}
{
let mut linked = self.linked.write().unwrap();
for l in linked.iter_mut() {
if let Ok(r) = Path::new(&l.path).strip_prefix(from) {
l.path = to.join(r).to_string_lossy().into_owned();
}
}
store("linked.json", &*linked);
}
self.persist();
moved.len()
}
pub fn set_gain(&self, id: &str, gain: f32) {
let changed = self.tracks.write().unwrap().get_mut(id).map(|t| t.gain_db = Some(gain)).is_some();
if changed {
@@ -1052,6 +1104,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn moving_the_music_folder_keeps_likes_and_plays() {
let root = std::env::temp_dir().join(format!("atmo-remap-{}-{}", std::process::id(), now()));
std::env::set_var("ATMOSPHERE_DATA_DIR", root.join("data"));
let (old, new) = (root.join("old"), root.join("new"));
wav(&old.join("Albums").join("one.wav"), 2);
let lib = Library::load();
lib.scan(std::slice::from_ref(&old), &old.join("Playlists"), |_, _| {}).unwrap();
let id = lib.snapshot(&old).tracks[0].id.clone();
lib.like(&id, true);
lib.played(&id);
std::fs::create_dir_all(new.join("Albums")).unwrap();
std::fs::rename(old.join("Albums").join("one.wav"), new.join("Albums").join("one.wav")).unwrap();
assert_eq!(lib.remap_paths(&old, &new), 1);
let snap = lib.snapshot(&new);
let t = &snap.tracks[0];
assert!(t.path.starts_with(&*new.to_string_lossy()));
assert!(snap.liked.contains(&t.id));
assert_eq!(snap.plays.get(&t.id), Some(&1));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn playlist_order_roundtrip() {
let dir = std::env::temp_dir().join(format!("atmo-test-{}", now()));
+2
View File
@@ -548,6 +548,8 @@ fn main() {
libcmd::track_loudness,
libcmd::tracks_edit,
libcmd::open_files,
libcmd::folder_report,
libcmd::move_music,
libcmd::startup_files,
libcmd::import_file,
libcmd::artist_fetch,
+44 -1
View File
@@ -1151,10 +1151,53 @@ function bindCommit() {
async function chooseFolder() {
const path = await invoke("pick_folder").catch(() => null);
if (!path) return;
const old = state.settings.outputDir;
if (!path || path === old) return;
const report = await invoke("folder_report", { path: old }).catch(() => ({ files: 0, bytes: 0 }));
if (!report.files) {
state.settings = await invoke("save_settings", { patch: { outputDir: path } });
updateCommit();
renderSettings();
return;
}
const body = h("div", { class: "stack" },
h("p", {}, `Your current folder has ${plural(report.files, "file")} (${fmtBytes(report.bytes)}).`),
h("div", { class: "move-paths" }, h("code", {}, old), icon("arrow-right"), h("code", {}, path)),
h("p", { class: "muted small" }, "Moving keeps your play counts, likes, history and playlists. If you keep them where they are, Atmosphere still shows them in your library."));
const choice = await modal("Move your music to the new folder?", body, [{ label: "Keep them where they are", value: "keep" }, { label: "Move everything", value: "move", primary: true }]);
if (!choice) return;
if (choice === "keep") {
const folders = [...new Set([...(state.settings.libraryFolders || []), old, path])];
state.settings = await invoke("save_settings", { patch: { outputDir: path, libraryFolders: folders } });
updateCommit();
renderSettings();
invoke("library_scan").catch(() => {});
return;
}
const bar = h("div", { class: "update-bar" }, h("span", { class: "update-fill" }));
const label = h("p", { class: "muted small" }, "Starting…");
const wrap = h("div", { class: "modal-wrap" }, h("div", { class: "modal", role: "dialog", "aria-modal": "true", "aria-label": "Moving music" }, h("h2", {}, "Moving your music"), bar, label));
document.body.append(wrap);
const off = await listen("atmosphere://move", (e) => {
const { done, total } = e.payload || {};
if (total) {
bar.firstChild.style.width = `${((done / total) * 100).toFixed(1)}%`;
label.textContent = `${done} of ${plural(total, "file")}`;
}
});
try {
const r = await invoke("move_music", { to: path });
state.settings = await invoke("get_settings");
toast(r.failed.length ? `Moved ${plural(r.moved, "file")}. ${r.failed.length} couldn't be moved and stayed put.` : `Moved ${plural(r.moved, "file")} to the new folder`, r.failed.length ? "err" : "ok");
await loadLibrary();
} catch (e) {
toast(errText(e), "err");
} finally {
off();
wrap.remove();
updateCommit();
renderSettings();
}
}
function updateCommit() {
+5
View File
@@ -1165,3 +1165,8 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa
.pick-page.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
.pick-page.dim { opacity: 0.6; }
.pick-page span { font-size: 12px; color: var(--text-2); }
/* moving folders */
.move-paths { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--s2); align-items: center; }
.move-paths code { font-size: 12px; padding: 6px 8px; border-radius: 8px; background: var(--surface-2, var(--surface)); border: 1px solid var(--hairline); overflow-wrap: anywhere; }
.move-paths .i { color: var(--text-3); }