mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Mini player, direct file links, backups and polish
- Mini player with optional cover art, blurred backdrop, reorderable queue and always-on-top - Direct .mp3/.wav/.flac/.mp4 links are verified and read for real bitrate, tags and cover - Lyrics soften with distance from the sung line; hovering brings a line into focus - Browser sign-in check with clear guidance, plus cookies.txt file support - Backup and restore of settings, stats, liked songs and artist photos - Uninstaller keeps data by default and offers a backup before deleting it - Stalled partial downloads clear automatically when downloads finish - Window border follows the app theme; images can no longer be dragged out - Fix search results rendering as [object Object]
This commit is contained in:
+128
@@ -0,0 +1,128 @@
|
||||
// atmosphere · backup.rs · Saves and restores settings, library, stats, liked songs and artist photos as one .zip
|
||||
use crate::engine::data_dir;
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use serde_json::Value;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
const DATA_FILES: &[&str] = &["library.json", "stats.json", "artists.json", "hidden.json", "history.json", "archive.txt"];
|
||||
const MARKER: &str = "atmosphere-backup.json";
|
||||
|
||||
fn artist_photos(data: &Path) -> Vec<String> {
|
||||
let Ok(bytes) = std::fs::read(data.join("artists.json")) else { return Vec::new() };
|
||||
let v: Value = serde_json::from_slice(&bytes).unwrap_or_default();
|
||||
v.as_object()
|
||||
.map(|m| m.values().filter_map(|a| a["image"].as_str().map(|s| format!("{s}.jpg"))).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn safe_name(name: &str) -> bool {
|
||||
!name.is_empty() && !name.contains("..") && !name.contains('\\') && !name.starts_with('/') && !name.contains(':')
|
||||
}
|
||||
|
||||
pub fn create(dest: &Path) -> Result<usize> {
|
||||
create_from(&data_dir(), &crate::settings::path(), dest)
|
||||
}
|
||||
|
||||
pub fn restore(src: &Path) -> Result<usize> {
|
||||
restore_into(&data_dir(), &crate::settings::path(), src)
|
||||
}
|
||||
|
||||
fn create_from(data: &Path, settings: &Path, dest: &Path) -> Result<usize> {
|
||||
let tmp = dest.with_extension("zip.part");
|
||||
let file = std::fs::File::create(&tmp).with_context(|| format!("Couldn't write to {}", dest.display()))?;
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let put = |zip: &mut zip::ZipWriter<std::fs::File>, name: &str, data: &[u8]| -> Result<()> {
|
||||
zip.start_file(name, opts)?;
|
||||
zip.write_all(data)?;
|
||||
Ok(())
|
||||
};
|
||||
let mut count = 0;
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
put(&mut zip, MARKER, serde_json::json!({ "app": "atmosphere", "version": env!("CARGO_PKG_VERSION"), "created": stamp }).to_string().as_bytes())?;
|
||||
if let Ok(bytes) = std::fs::read(settings) {
|
||||
put(&mut zip, "settings.json", &bytes)?;
|
||||
count += 1;
|
||||
}
|
||||
for name in DATA_FILES {
|
||||
if let Ok(bytes) = std::fs::read(data.join(name)) {
|
||||
put(&mut zip, name, &bytes)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
for photo in artist_photos(data) {
|
||||
if let Ok(bytes) = std::fs::read(data.join("art").join(&photo)) {
|
||||
put(&mut zip, &format!("art/{photo}"), &bytes)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
zip.finish()?;
|
||||
std::fs::rename(&tmp, dest).or_else(|_| std::fs::copy(&tmp, dest).map(|_| ()).and_then(|_| std::fs::remove_file(&tmp)))?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn restore_into(data: &Path, settings: &Path, src: &Path) -> Result<usize> {
|
||||
let file = std::fs::File::open(src).context("Couldn't open that backup")?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|_| anyhow!("That file isn't an Atmosphere backup."))?;
|
||||
if zip.by_name(MARKER).is_err() {
|
||||
bail!("That file isn't an Atmosphere backup.");
|
||||
}
|
||||
let mut count = 0;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i)?;
|
||||
let name = entry.name().map(|n| n.to_string()).unwrap_or_default();
|
||||
if !entry.is_file() || !safe_name(&name) || name == MARKER {
|
||||
continue;
|
||||
}
|
||||
let target = if name == "settings.json" {
|
||||
settings.to_path_buf()
|
||||
} else if DATA_FILES.contains(&name.as_str()) {
|
||||
data.join(&name)
|
||||
} else if let Some(photo) = name.strip_prefix("art/").filter(|p: &&str| !p.contains('/') && p.ends_with(".jpg")) {
|
||||
data.join("art").join(photo)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
entry.read_to_end(&mut bytes)?;
|
||||
if let Some(dir) = target.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(&target, bytes)?;
|
||||
count += 1;
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backup_round_trips_and_rejects_strangers() {
|
||||
let root = std::env::temp_dir().join(format!("atmo-backup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("art")).unwrap();
|
||||
std::fs::write(root.join("stats.json"), br#"{"liked":["a"]}"#).unwrap();
|
||||
std::fs::write(root.join("artists.json"), br#"{"x":{"name":"X","image":"p1"}}"#).unwrap();
|
||||
std::fs::write(root.join("art").join("p1.jpg"), b"jpg").unwrap();
|
||||
std::fs::write(root.join("art").join("cover.jpg"), b"thumb").unwrap();
|
||||
let zip_path = root.join("b.zip");
|
||||
let set = root.join("cfg").join("settings.json");
|
||||
std::fs::create_dir_all(set.parent().unwrap()).unwrap();
|
||||
std::fs::write(&set, b"{}").unwrap();
|
||||
assert!(create_from(&root, &set, &zip_path).unwrap() >= 4);
|
||||
std::fs::remove_file(&set).unwrap();
|
||||
std::fs::remove_file(root.join("stats.json")).unwrap();
|
||||
std::fs::remove_file(root.join("art").join("p1.jpg")).unwrap();
|
||||
assert!(restore_into(&root, &set, &zip_path).unwrap() >= 4);
|
||||
assert!(set.exists());
|
||||
assert_eq!(std::fs::read(root.join("stats.json")).unwrap(), br#"{"liked":["a"]}"#);
|
||||
assert!(root.join("art").join("p1.jpg").exists());
|
||||
std::fs::write(root.join("not.zip"), b"nope").unwrap();
|
||||
assert!(restore_into(&root, &set, &root.join("not.zip")).is_err());
|
||||
assert!(!safe_name("../x") && !safe_name("C:x") && safe_name("art/p.jpg"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
// atmosphere · direct.rs · Reads real details from direct audio/video file links using ffprobe
|
||||
use crate::engine::{self, Tools};
|
||||
use crate::media::{Entry, MediaInfo};
|
||||
use crate::settings::Settings;
|
||||
use anyhow::{bail, Result};
|
||||
use base64::Engine as _;
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
const UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36";
|
||||
const NOT_MEDIA: &str = "That link didn't open as an audio or video file. Make sure it points straight at the file and that anyone can open it without signing in.";
|
||||
|
||||
pub fn is_direct(v: &Value) -> bool {
|
||||
v["direct"].as_bool().unwrap_or(false) && v["_type"].as_str().is_none_or(|t| t == "video")
|
||||
}
|
||||
|
||||
fn ffprobe(tools: &Tools) -> Option<PathBuf> {
|
||||
let exe = if cfg!(windows) { "ffprobe.exe" } else { "ffprobe" };
|
||||
tools.ffmpeg.as_ref().and_then(|f| f.parent()).map(|d| d.join(exe)).filter(|p| p.is_file()).or_else(|| engine::find_tool("ffprobe"))
|
||||
}
|
||||
|
||||
fn net_args(settings: &Settings) -> Vec<String> {
|
||||
let mut a: Vec<String> = ["-user_agent", UA, "-rw_timeout", "20000000"].map(String::from).into();
|
||||
let proxy = settings.proxy.trim();
|
||||
if proxy.starts_with("http://") {
|
||||
a.extend(["-http_proxy".into(), proxy.into()]);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn tag(tags: &[&Value], key: &str) -> Option<String> {
|
||||
tags.iter().find_map(|t| {
|
||||
t.as_object()?
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case(key))
|
||||
.and_then(|(_, v)| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn leading_num(s: &str) -> Option<u32> {
|
||||
s.split(['/', ' ']).next()?.trim().parse().ok()
|
||||
}
|
||||
|
||||
fn kbps(v: &Value) -> Option<u32> {
|
||||
v.as_str().and_then(|b| b.parse::<f64>().ok()).filter(|b| *b > 0.0).map(|b| (b / 1000.0).round() as u32)
|
||||
}
|
||||
|
||||
fn is_lossless(codec: &str) -> bool {
|
||||
codec.starts_with("pcm_") || ["flac", "alac", "wavpack", "ape", "tta", "mlp", "truehd"].contains(&codec)
|
||||
}
|
||||
|
||||
fn codec_label(codec: &str) -> String {
|
||||
match codec {
|
||||
c if c.starts_with("pcm_") => "pcm".into(),
|
||||
"mp3" | "mp3float" => "mp3".into(),
|
||||
"aac" => "aac".into(),
|
||||
c => c.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(program: &Path, args: &[String]) -> Option<Vec<u8>> {
|
||||
let child = engine::command(program).args(args).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true).output();
|
||||
match tokio::time::timeout(Duration::from_secs(45), child).await {
|
||||
Ok(Ok(out)) if out.status.success() && !out.stdout.is_empty() => Some(out.stdout),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn cover(tools: &Tools, settings: &Settings, url: &str) -> Option<String> {
|
||||
let ff = tools.ffmpeg.as_ref()?;
|
||||
let mut args = vec!["-v".into(), "error".into()];
|
||||
args.extend(net_args(settings));
|
||||
args.extend(["-i", url, "-map", "0:v:0", "-frames:v", "1", "-c:v", "mjpeg", "-q:v", "3", "-f", "image2pipe", "pipe:1"].map(String::from));
|
||||
let jpg = run(ff, &args).await?;
|
||||
let img = image::load_from_memory(&jpg).ok()?;
|
||||
let img = if img.width() > 600 { img.thumbnail(600, 600) } else { img };
|
||||
let mut out = Vec::new();
|
||||
img.to_rgb8().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Jpeg).ok()?;
|
||||
Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(out)))
|
||||
}
|
||||
|
||||
pub async fn enrich(tools: &Tools, settings: &Settings, v: &Value, entry: &mut Entry) -> Result<()> {
|
||||
let url = entry.url.clone();
|
||||
let Some(probe) = ffprobe(tools) else {
|
||||
entry.platform = "File link".into();
|
||||
return Ok(());
|
||||
};
|
||||
let mut args = vec!["-v".into(), "error".into(), "-print_format".into(), "json".into(), "-show_format".into(), "-show_streams".into()];
|
||||
args.extend(net_args(settings));
|
||||
args.push(url.clone());
|
||||
let Some(out) = run(&probe, &args).await else { bail!(NOT_MEDIA) };
|
||||
let info: Value = serde_json::from_slice(&out).unwrap_or_default();
|
||||
let streams = info["streams"].as_array().cloned().unwrap_or_default();
|
||||
let is_pic = |s: &Value| s["disposition"]["attached_pic"].as_i64() == Some(1);
|
||||
let audio = streams.iter().find(|s| s["codec_type"] == "audio");
|
||||
let video: Vec<&Value> = streams.iter().filter(|s| s["codec_type"] == "video" && !is_pic(s)).collect();
|
||||
let has_art = streams.iter().any(|s| s["codec_type"] == "video" && is_pic(s));
|
||||
if audio.is_none() && video.is_empty() {
|
||||
bail!(NOT_MEDIA);
|
||||
}
|
||||
let format = &info["format"];
|
||||
let mut tag_sources = vec![&format["tags"]];
|
||||
if let Some(a) = audio {
|
||||
tag_sources.push(&a["tags"]);
|
||||
}
|
||||
let codec = audio.and_then(|a| a["codec_name"].as_str()).unwrap_or("");
|
||||
let lossless = !codec.is_empty() && is_lossless(codec);
|
||||
let abr = if lossless {
|
||||
None
|
||||
} else {
|
||||
audio.and_then(|a| kbps(&a["bit_rate"])).or_else(|| video.is_empty().then(|| kbps(&format["bit_rate"])).flatten())
|
||||
};
|
||||
let mut heights: Vec<u32> = video.iter().filter_map(|s| s["height"].as_u64().map(|h| h as u32)).collect();
|
||||
heights.sort_unstable_by(|a, b| b.cmp(a));
|
||||
heights.dedup();
|
||||
let ext = v["ext"].as_str().map(str::to_string).or_else(|| url.rsplit('.').next().map(|e| e.split(['?', '#']).next().unwrap_or(e).to_ascii_lowercase()));
|
||||
entry.media = Some(MediaInfo {
|
||||
has_video: !video.is_empty(),
|
||||
heights,
|
||||
best_abr: abr,
|
||||
best_codec: (!codec.is_empty()).then(|| codec_label(codec)),
|
||||
lossless,
|
||||
original: true,
|
||||
original_lossless: lossless,
|
||||
original_ext: ext,
|
||||
});
|
||||
entry.detailed = true;
|
||||
entry.availability = "ok".into();
|
||||
entry.platform = "File link".into();
|
||||
if let Some(d) = format["duration"].as_str().and_then(|d| d.parse::<f64>().ok()) {
|
||||
entry.duration_ms = Some((d * 1000.0) as u64);
|
||||
}
|
||||
if let Some(t) = tag(&tag_sources, "title") {
|
||||
entry.title = t;
|
||||
}
|
||||
if let Some(a) = tag(&tag_sources, "artist") {
|
||||
entry.artist = a.clone();
|
||||
entry.uploader = a;
|
||||
}
|
||||
entry.album = tag(&tag_sources, "album").or(entry.album.take());
|
||||
entry.album_artist = tag(&tag_sources, "album_artist").or_else(|| tag(&tag_sources, "albumartist")).or(entry.album_artist.take());
|
||||
entry.genre = tag(&tag_sources, "genre").or(entry.genre.take());
|
||||
entry.composer = tag(&tag_sources, "composer").or(entry.composer.take());
|
||||
entry.track_number = tag(&tag_sources, "track").as_deref().and_then(leading_num).or(entry.track_number);
|
||||
entry.disc_number = tag(&tag_sources, "disc").as_deref().and_then(leading_num).or(entry.disc_number);
|
||||
if let Some(date) = tag(&tag_sources, "date").or_else(|| tag(&tag_sources, "year")) {
|
||||
entry.year = date.get(..4).and_then(|y| y.parse().ok()).or(entry.year);
|
||||
if date.len() >= 10 {
|
||||
entry.release_date = Some(date[..10].to_string());
|
||||
}
|
||||
}
|
||||
if entry.lyrics.is_none() {
|
||||
entry.lyrics = tag(&tag_sources, "lyrics").or_else(|| tag(&tag_sources, "unsyncedlyrics"));
|
||||
}
|
||||
if entry.thumbnail.is_none() && has_art {
|
||||
entry.thumbnail = cover(tools, settings, &url).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_tags_case_insensitively_and_numbers() {
|
||||
let t = serde_json::json!({ "TITLE": "Song", "Track": "3/12" });
|
||||
assert_eq!(tag(&[&t], "title").as_deref(), Some("Song"));
|
||||
assert_eq!(tag(&[&t], "track").as_deref().and_then(leading_num), Some(3));
|
||||
assert!(is_lossless("pcm_s16le") && is_lossless("flac") && !is_lossless("mp3"));
|
||||
assert_eq!(kbps(&serde_json::json!("320000")), Some(320));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn live_direct_mp3_reports_its_real_bitrate() {
|
||||
let tools = engine::locate("", "").unwrap();
|
||||
let settings = Settings::default();
|
||||
let mut e = Entry { url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3".into(), ..Default::default() };
|
||||
enrich(&tools, &settings, &serde_json::json!({ "ext": "mp3" }), &mut e).await.unwrap();
|
||||
let m = e.media.unwrap();
|
||||
assert_eq!((m.best_abr, m.best_codec.as_deref(), m.original), (Some(192), Some("mp3"), true));
|
||||
assert!(e.duration_ms.unwrap() > 370_000);
|
||||
let mut bad = Entry { url: "https://example.com/".into(), ..Default::default() };
|
||||
assert!(enrich(&tools, &settings, &serde_json::json!({}), &mut bad).await.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_direct_files_only() {
|
||||
assert!(is_direct(&serde_json::json!({ "direct": true, "_type": "video" })));
|
||||
assert!(!is_direct(&serde_json::json!({ "_type": "video" })));
|
||||
assert!(!is_direct(&serde_json::json!({ "direct": true, "_type": "playlist" })));
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -204,7 +204,15 @@ impl Downloader {
|
||||
Err(e) => job.emit("error", Some(format!("{e:#}")), None),
|
||||
}
|
||||
this.flags.lock().unwrap().remove(&p.id);
|
||||
this.queue.lock().unwrap().running -= 1;
|
||||
let idle = {
|
||||
let mut q = this.queue.lock().unwrap();
|
||||
q.running -= 1;
|
||||
q.running == 0 && q.pending.is_empty()
|
||||
};
|
||||
if idle {
|
||||
let s = this.settings.lock().unwrap().clone();
|
||||
let _ = tauri::async_runtime::spawn_blocking(move || crate::storage::clear_stalled(&s)).await;
|
||||
}
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
@@ -758,8 +766,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn builds_stems_and_escapes_templates() {
|
||||
let mut settings = Settings::default();
|
||||
settings.output_dir = "out".into();
|
||||
let settings = Settings { output_dir: "out".into(), ..Default::default() };
|
||||
let meta = TagFields { title: "100% Night".into(), track_number: Some(3), track_total: Some(120), ..Default::default() };
|
||||
let req = JobRequest { entry: entry(None, false, vec![]), meta, folder: Some("Nova - Glass: Vol 1".into()), trim: None, playlist: None };
|
||||
let stem = file_stem(&settings, &req);
|
||||
|
||||
@@ -82,6 +82,10 @@ fn resolve(custom: &str, name: &str) -> (Option<PathBuf>, bool) {
|
||||
(on_path(name), false)
|
||||
}
|
||||
|
||||
pub fn find_tool(name: &str) -> Option<PathBuf> {
|
||||
resolve("", name).0
|
||||
}
|
||||
|
||||
pub fn command(program: &Path) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.stdin(Stdio::null()).env("PYTHONIOENCODING", "utf-8").env("PYTHONUTF8", "1");
|
||||
|
||||
+1
-2
@@ -573,8 +573,7 @@ mod tests {
|
||||
println!("{title}: provider={:?} synced={:?} words={:?} lines={:?} tried={:?}", l.map(|x| &x.provider), l.map(|x| x.synced), l.map(|x| x.word_synced), l.map(|x| x.lines.len()), f.tried.iter().map(|t| format!("{}: {}", t.provider, t.outcome)).collect::<Vec<_>>());
|
||||
assert!(l.is_some_and(|x| x.synced));
|
||||
}
|
||||
let mut only_netease = Settings::default();
|
||||
only_netease.lyrics_providers = vec![ProviderCfg { id: "netease".into(), enabled: true }];
|
||||
let only_netease = Settings { lyrics_providers: vec![ProviderCfg { id: "netease".into(), enabled: true }], ..Default::default() };
|
||||
let q = Query { title: "Get Lucky".into(), artist: "Daft Punk".into(), duration_ms: Some(248_000), ..Default::default() };
|
||||
let f = find(&http, &only_netease, &q, true).await.unwrap();
|
||||
let l = f.lyrics.as_ref();
|
||||
|
||||
+94
@@ -1,6 +1,8 @@
|
||||
// atmosphere · main.rs · App entry point: shared state, the rights gate and every command the UI can call.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod backup;
|
||||
mod direct;
|
||||
mod downloader;
|
||||
mod engine;
|
||||
mod history;
|
||||
@@ -279,11 +281,88 @@ fn storage_clean(state: State<'_, AppState>, ids: Vec<String>) -> Cleaned {
|
||||
Cleaned { files, bytes }
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn backup_save(app: AppHandle, name: String) -> CmdResult<Option<(String, usize)>> {
|
||||
let a = app.clone();
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || {
|
||||
let mut d = a.dialog().file().set_title("Back up Atmosphere").set_file_name(&name).add_filter("Atmosphere backup", &["zip"]);
|
||||
if let Some(docs) = dirs::document_dir() {
|
||||
d = d.set_directory(docs);
|
||||
}
|
||||
d.blocking_save_file()
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let Some(path) = picked.and_then(|p| p.into_path().ok()) else { return Ok(None) };
|
||||
let p = path.clone();
|
||||
let n = tauri::async_runtime::spawn_blocking(move || backup::create(&p)).await.map_err(|e| e.to_string())?.map_err(err)?;
|
||||
Ok(Some((path.to_string_lossy().into_owned(), n)))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn backup_pick(app: AppHandle) -> CmdResult<Option<String>> {
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || app.dialog().file().set_title("Restore from a backup").add_filter("Atmosphere backup", &["zip"]).blocking_pick_file())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(picked.and_then(|p| p.into_path().ok()).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn backup_restore(app: AppHandle, state: State<'_, AppState>, path: String) -> CmdResult<()> {
|
||||
if state.dl.busy() {
|
||||
return Err("Wait for downloads to finish before restoring.".into());
|
||||
}
|
||||
tauri::async_runtime::spawn_blocking(move || backup::restore(std::path::Path::new(&path))).await.map_err(|e| e.to_string())?.map_err(err)?;
|
||||
app.restart();
|
||||
}
|
||||
|
||||
fn parse_hex(color: &str) -> Option<(u8, u8, u8)> {
|
||||
let c = color.trim().trim_start_matches('#');
|
||||
if c.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
let v = u32::from_str_radix(c, 16).ok()?;
|
||||
Some(((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn frame_color(window: tauri::WebviewWindow, color: String) {
|
||||
let Some((r, g, b)) = parse_hex(&color) else { return };
|
||||
#[cfg(windows)]
|
||||
if let Ok(hwnd) = window.hwnd() {
|
||||
use windows_sys::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_BORDER_COLOR};
|
||||
let colorref: u32 = (r as u32) | ((g as u32) << 8) | ((b as u32) << 16);
|
||||
unsafe {
|
||||
DwmSetWindowAttribute(hwnd.0 as _, DWMWA_BORDER_COLOR as _, &colorref as *const u32 as _, 4);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (window, r, g, b);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn startup_cleanup(state: State<'_, AppState>) -> Option<Cleaned> {
|
||||
state.startup_cleanup.lock().unwrap().take().filter(|(n, _)| *n > 0).map(|(files, bytes)| Cleaned { files, bytes })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn signin_check(state: State<'_, AppState>, browser: String, file: String) -> CmdResult<String> {
|
||||
let mut s = state.snapshot();
|
||||
s.cookies_browser = browser;
|
||||
s.cookies_file = file;
|
||||
media::check_signin(&s).await.map_err(err)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pick_cookies_file(app: AppHandle) -> CmdResult<Option<String>> {
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || {
|
||||
app.dialog().file().set_title("Choose a cookies.txt file").add_filter("Cookies", &["txt"]).blocking_pick_file()
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(picked.and_then(|p| p.into_path().ok()).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pick_text_file(app: AppHandle) -> CmdResult<Option<String>> {
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || {
|
||||
@@ -320,6 +399,14 @@ fn read_clipboard(app: AppHandle, state: State<'_, AppState>) -> Option<String>
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if let Some(i) = args.iter().position(|a| a == "--backup") {
|
||||
let code = match args.get(i + 1) {
|
||||
Some(dest) => i32::from(backup::create(std::path::Path::new(dest)).is_err()),
|
||||
None => 2,
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
let settings = Arc::new(Mutex::new(settings::load()));
|
||||
let http = reqwest::Client::builder()
|
||||
.user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION")))
|
||||
@@ -347,6 +434,12 @@ fn main() {
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
signin_check,
|
||||
frame_color,
|
||||
backup_save,
|
||||
backup_pick,
|
||||
backup_restore,
|
||||
pick_cookies_file,
|
||||
get_settings,
|
||||
accept_rights,
|
||||
revoke_rights,
|
||||
@@ -409,6 +502,7 @@ fn main() {
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.dl.cancel_all();
|
||||
storage::clear_stalled(&state.snapshot());
|
||||
}
|
||||
storage::wipe_temp();
|
||||
}
|
||||
|
||||
+124
-5
@@ -387,7 +387,45 @@ fn release_artist(kind: &str, fallback: &str, entries: &[Entry]) -> String {
|
||||
fallback.to_string()
|
||||
}
|
||||
|
||||
fn browser_label(id: &str) -> String {
|
||||
match id.to_ascii_lowercase().as_str() {
|
||||
"chrome" => "Chrome".into(),
|
||||
"chromium" => "Chromium".into(),
|
||||
"edge" => "Edge".into(),
|
||||
"firefox" => "Firefox".into(),
|
||||
"brave" => "Brave".into(),
|
||||
"opera" => "Opera".into(),
|
||||
"vivaldi" => "Vivaldi".into(),
|
||||
"safari" => "Safari".into(),
|
||||
"whale" => "Whale".into(),
|
||||
_ => "your browser".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie_error(stderr: &str) -> Option<String> {
|
||||
let lower = stderr.to_lowercase();
|
||||
if !lower.contains("cookie") {
|
||||
return None;
|
||||
}
|
||||
static FROM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)extracting cookies from (\w+)").unwrap());
|
||||
let b = FROM.captures(stderr).map(|c| browser_label(&c[1])).unwrap_or_else(|| "your browser".into());
|
||||
if lower.contains("could not copy") || lower.contains("permission denied") || lower.contains("database is locked") {
|
||||
Some(format!("{b} keeps its sign-in locked while it's running. Quit {b} completely (check the system tray too), then try again. Firefox can stay open, or use a cookies.txt file instead."))
|
||||
} else if lower.contains("could not find") && lower.contains("cookies database") {
|
||||
Some(format!("Couldn't find a {b} profile on this computer. Choose the browser you actually sign in with."))
|
||||
} else if lower.contains("decrypt") || lower.contains("dpapi") || lower.contains("app-bound") || lower.contains("keyring") {
|
||||
Some(format!("{b} encrypts its sign-in so other apps can't read it. Firefox works, or export a cookies.txt file from {b} and choose it here."))
|
||||
} else if lower.contains("netscape") || lower.contains("cookiefile") || (lower.contains("cookies") && lower.contains("no such file")) {
|
||||
Some("That cookies file couldn't be read. It needs to be a cookies.txt export in Netscape format.".into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn humanize(stderr: &str) -> String {
|
||||
if let Some(c) = cookie_error(stderr) {
|
||||
return c;
|
||||
}
|
||||
let err = stderr
|
||||
.lines()
|
||||
.rev()
|
||||
@@ -418,9 +456,18 @@ pub fn base_args(settings: &Settings, tools: &Tools) -> Vec<String> {
|
||||
args.push("--ffmpeg-location".into());
|
||||
args.push(ff.to_string_lossy().into_owned());
|
||||
}
|
||||
if !settings.cookies_browser.trim().is_empty() {
|
||||
args.push("--cookies-from-browser".into());
|
||||
args.push(settings.cookies_browser.trim().into());
|
||||
match settings.cookies_browser.trim() {
|
||||
"" => {}
|
||||
"file" => {
|
||||
if !settings.cookies_file.trim().is_empty() {
|
||||
args.push("--cookies".into());
|
||||
args.push(settings.cookies_file.trim().into());
|
||||
}
|
||||
}
|
||||
browser => {
|
||||
args.push("--cookies-from-browser".into());
|
||||
args.push(browser.into());
|
||||
}
|
||||
}
|
||||
if !settings.proxy.trim().is_empty() {
|
||||
args.push("--proxy".into());
|
||||
@@ -504,7 +551,17 @@ impl Prober {
|
||||
args.extend(["-J", "--flat-playlist", "--", link].map(String::from));
|
||||
let v = run_json(&tools, args).await?;
|
||||
let id = format!("c{}", NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst));
|
||||
let collection = collection_from(&v, id.clone(), link);
|
||||
let mut collection = collection_from(&v, id.clone(), link);
|
||||
if crate::direct::is_direct(&v) {
|
||||
if let Some(entry) = collection.entries.first_mut() {
|
||||
crate::direct::enrich(&tools, settings, &v, entry).await?;
|
||||
collection.title = entry.title.clone();
|
||||
collection.artist = entry.artist.clone();
|
||||
collection.thumbnail = entry.thumbnail.clone();
|
||||
collection.platform = entry.platform.clone();
|
||||
collection.year = entry.year;
|
||||
}
|
||||
}
|
||||
if collection.enriching {
|
||||
self.enrich(app.clone(), settings.clone(), tools, collection.clone(), v);
|
||||
}
|
||||
@@ -533,7 +590,12 @@ impl Prober {
|
||||
let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?;
|
||||
let mut args = base_args(settings, &tools);
|
||||
args.extend(["-J", "--no-playlist", "--", url].map(String::from));
|
||||
Ok(entry_from_info(&run_json(&tools, args).await?, index))
|
||||
let v = run_json(&tools, args).await?;
|
||||
let mut entry = entry_from_info(&v, index);
|
||||
if crate::direct::is_direct(&v) {
|
||||
crate::direct::enrich(&tools, settings, &v, &mut entry).await?;
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
pub fn cancel(&self, id: &str) {
|
||||
@@ -673,3 +735,60 @@ mod tests {
|
||||
assert!(humanize("ERROR: [youtube] abc: Private video. Sign in").contains("browser sign-in"));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn count_cookie_lines(text: &str) -> usize {
|
||||
text.lines()
|
||||
.map(|l| l.strip_prefix("#HttpOnly_").unwrap_or(l))
|
||||
.filter(|l| !l.starts_with('#') && l.split('\t').count() == 7)
|
||||
.count()
|
||||
}
|
||||
|
||||
pub async fn check_signin(settings: &Settings) -> Result<String> {
|
||||
match settings.cookies_browser.trim() {
|
||||
"" => bail!("Choose a browser or a cookies file first."),
|
||||
"file" => {
|
||||
let path = settings.cookies_file.trim();
|
||||
if path.is_empty() {
|
||||
bail!("Choose your cookies.txt file first.");
|
||||
}
|
||||
let text = tokio::fs::read_to_string(path).await.map_err(|_| anyhow!("That cookies file couldn't be opened."))?;
|
||||
match count_cookie_lines(&text) {
|
||||
0 => bail!("That file has no cookies in it. Export a cookies.txt file in Netscape format while you're signed in."),
|
||||
n => Ok(format!("Found {n} cookies in that file. You're set.")),
|
||||
}
|
||||
}
|
||||
browser => {
|
||||
let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?;
|
||||
let mut args = base_args(settings, &tools);
|
||||
args.extend(["--simulate", "--no-playlist", "--", "https://example.com/"].map(String::from));
|
||||
let run = engine::command(&tools.ytdlp).args(&args).stdout(Stdio::null()).stderr(Stdio::piped()).kill_on_drop(true).output();
|
||||
let out = tokio::time::timeout(std::time::Duration::from_secs(60), run).await.map_err(|_| anyhow!("Checking took too long. Try again."))??;
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
static OK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)extracted (\d+) cookies from").unwrap());
|
||||
if let Some(c) = OK.captures(&err) {
|
||||
return Ok(format!("Read your {} sign-in ({} cookies). You're set.", browser_label(browser), &c[1]));
|
||||
}
|
||||
bail!(cookie_error(&err).unwrap_or_else(|| format!("Couldn't read the {} sign-in. {}", browser_label(browser), humanize(&err))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod signin_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn explains_locked_and_encrypted_browsers() {
|
||||
let locked = "Extracting cookies from brave\nERROR: Could not copy Chrome cookie database. See https://github.com/yt-dlp/yt-dlp/issues/7271";
|
||||
assert!(humanize(locked).starts_with("Brave keeps its sign-in locked"));
|
||||
let enc = "Extracting cookies from chrome\nERROR: Failed to decrypt with DPAPI";
|
||||
assert!(cookie_error(enc).unwrap().starts_with("Chrome encrypts"));
|
||||
assert!(cookie_error("ERROR: Unsupported URL").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_netscape_cookie_lines() {
|
||||
let t = "# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tTRUE\t0\ta\tb\n#HttpOnly_.x.com\tTRUE\t/\tTRUE\t0\tc\td\nnot a cookie";
|
||||
assert_eq!(count_cookie_lines(t), 2);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -59,6 +59,7 @@ pub struct Settings {
|
||||
pub subtitle_langs: String,
|
||||
pub embed_chapters: bool,
|
||||
pub cookies_browser: String,
|
||||
pub cookies_file: String,
|
||||
pub proxy: String,
|
||||
pub rate_limit: String,
|
||||
pub ytdlp_path: String,
|
||||
@@ -98,6 +99,7 @@ impl Default for Settings {
|
||||
subtitle_langs: "en".into(),
|
||||
embed_chapters: true,
|
||||
cookies_browser: String::new(),
|
||||
cookies_file: String::new(),
|
||||
proxy: String::new(),
|
||||
rate_limit: String::new(),
|
||||
ytdlp_path: String::new(),
|
||||
@@ -135,6 +137,7 @@ pub struct SettingsPatch {
|
||||
pub subtitle_langs: Option<String>,
|
||||
pub embed_chapters: Option<bool>,
|
||||
pub cookies_browser: Option<String>,
|
||||
pub cookies_file: Option<String>,
|
||||
pub proxy: Option<String>,
|
||||
pub rate_limit: Option<String>,
|
||||
pub ytdlp_path: Option<String>,
|
||||
@@ -171,7 +174,7 @@ impl Settings {
|
||||
($($f:ident),*) => { $( if let Some(v) = p.$f { self.$f = v; } )* };
|
||||
}
|
||||
set!(save_as, embed_metadata, collection_folders, number_tracks, skip_downloaded, sponsorblock, embed_subtitles, embed_chapters, watch_clipboard);
|
||||
set!(cookies_browser, proxy, rate_limit, ytdlp_path, ffmpeg_path, subtitle_langs, musixmatch_key, playlist_copy, lyrics_on_download, custom_lyrics, fx_presets);
|
||||
set!(cookies_browser, cookies_file, proxy, rate_limit, ytdlp_path, ffmpeg_path, subtitle_langs, musixmatch_key, playlist_copy, lyrics_on_download, custom_lyrics, fx_presets);
|
||||
if let Some(v) = p.library_folders {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.library_folders = v.into_iter().map(|f| f.trim().to_string()).filter(|f| !f.is_empty() && seen.insert(f.clone())).collect();
|
||||
@@ -211,7 +214,7 @@ impl Settings {
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> PathBuf {
|
||||
pub fn path() -> PathBuf {
|
||||
match crate::engine::portable_root() {
|
||||
Some(root) => root.join("settings.json"),
|
||||
None => dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("atmosphere").join("settings.json"),
|
||||
|
||||
+6
-4
@@ -67,16 +67,14 @@ fn mb(bytes: u64) -> String {
|
||||
format!("{:.1} MB", bytes as f64 / 1_048_576.0)
|
||||
}
|
||||
|
||||
pub fn report(settings: &Settings, lib: &Snapshot, busy: bool) -> Vec<Item> {
|
||||
pub fn report(_settings: &Settings, lib: &Snapshot, busy: bool) -> Vec<Item> {
|
||||
let temp = all_files(&temp_root());
|
||||
let stall = if busy { Vec::new() } else { stalled(settings) };
|
||||
let orphans = orphan_art(lib);
|
||||
let lyrics = all_files(&data_dir().join("lyrics"));
|
||||
let art = all_files(&data_dir().join("art"));
|
||||
let engine = all_files(&bin_dir());
|
||||
vec![
|
||||
Item { id: "temp".into(), label: "Temporary files".into(), detail: "Pieces of downloads in progress. Wiped automatically on launch and exit.".into(), bytes: size(&temp), count: temp.len(), cleanable: !busy },
|
||||
Item { id: "stalled".into(), label: "Stalled partial downloads".into(), detail: if busy { "Checked when no downloads are running.".into() } else { "Unfinished pieces left in your download or playlist folders.".into() }, bytes: size(&stall), count: stall.len(), cleanable: !busy },
|
||||
Item { id: "temp".into(), label: "Temporary files".into(), detail: "Pieces of downloads in progress. Wiped automatically, along with any stalled partial downloads.".into(), bytes: size(&temp), count: temp.len(), cleanable: !busy },
|
||||
Item { id: "orphan-art".into(), label: "Unused cover art".into(), detail: "Artwork for songs no longer in your library.".into(), bytes: size(&orphans), count: orphans.len(), cleanable: true },
|
||||
Item { id: "lyrics".into(), label: "Lyrics cache".into(), detail: "Lyrics fetched online; they're fetched again when needed.".into(), bytes: size(&lyrics), count: lyrics.len(), cleanable: true },
|
||||
Item { id: "art".into(), label: "Cover art in use".into(), detail: format!("Thumbnails for your library ({}).", mb(size(&art).saturating_sub(size(&orphans)))), bytes: size(&art).saturating_sub(size(&orphans)), count: art.len().saturating_sub(orphans.len()), cleanable: false },
|
||||
@@ -122,6 +120,10 @@ pub fn clean(settings: &Settings, lib: &Snapshot, ids: &[String], busy: bool) ->
|
||||
total
|
||||
}
|
||||
|
||||
pub fn clear_stalled(settings: &Settings) -> (usize, u64) {
|
||||
remove_all(&stalled(settings))
|
||||
}
|
||||
|
||||
pub fn startup(settings: &Settings) -> (usize, u64) {
|
||||
let a = wipe_temp();
|
||||
let b = remove_all(&stalled(settings));
|
||||
|
||||
Reference in New Issue
Block a user