Atmosphere: music library, player and downloader

Native Rust + Tauri 2 app for Windows, macOS and Linux.

- Library with songs, albums, artist profiles, liked songs and folder-based playlists
- Player with EQ, presets, filters, reverb, 8D, independent pitch and tempo
- Synced and word-synced lyrics (local, LRCLIB, NetEase, Musixmatch API, custom)
- TV mode with second-screen output
- Downloader built on yt-dlp and ffmpeg with honest format choices and tagging
- Listening stats with shareable social-size cards
- Portable mode, temp-file cleanup, branded installers
This commit is contained in:
Christian
2026-11-18 17:44:07 -05:00
commit 1fcd3a85f7
131 changed files with 16725 additions and 0 deletions
+771
View File
@@ -0,0 +1,771 @@
// atmosphere · downloader.rs · Ordered download queue driving yt-dlp: format choice, progress, cancellation, tagging and history.
use crate::engine::{self, Tools};
use crate::history::{History, Record};
use crate::library::Library;
use crate::media::{self, Entry};
use crate::settings::{snap_bitrate, SaveAs, Settings};
use crate::tagging::{self, TagFields};
use anyhow::{anyhow, bail, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
pub const EVENT: &str = "atmosphere://job";
const EMIT_INTERVAL: Duration = Duration::from_millis(150);
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Trim {
pub start: String,
pub end: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JobRequest {
pub entry: Entry,
#[serde(default)]
pub meta: TagFields,
pub folder: Option<String>,
#[serde(default)]
pub trim: Option<Trim>,
#[serde(default)]
pub playlist: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveOptions {
pub save_as: SaveAs,
pub mp3_bitrate: u32,
pub video_height: u32,
pub video_container: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JobEvent {
pub id: u64,
pub state: &'static str,
pub progress: f64,
pub received: u64,
pub total: Option<u64>,
pub speed: u64,
pub stage: u32,
pub format: Option<String>,
pub message: Option<String>,
pub path: Option<String>,
}
#[derive(Debug)]
pub struct Cancelled;
impl std::fmt::Display for Cancelled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("cancelled")
}
}
impl std::error::Error for Cancelled {}
struct Pending {
id: u64,
req: JobRequest,
save: SaveOptions,
flag: Arc<AtomicBool>,
}
struct Queue {
pending: VecDeque<Pending>,
running: usize,
limit: usize,
}
pub struct Downloader {
app: AppHandle,
history: Arc<History>,
library: Arc<Library>,
http: reqwest::Client,
settings: Arc<Mutex<Settings>>,
queue: Mutex<Queue>,
flags: Mutex<HashMap<u64, Arc<AtomicBool>>>,
next: AtomicU64,
}
pub const LIBRARY_EVENT: &str = "atmosphere://library";
async fn after_download(app: &AppHandle, library: &Library, http: &reqwest::Client, settings: &Settings, req: &JobRequest, path: &Path) {
let playlists = PathBuf::from(&settings.playlists_dir);
let attached = req.meta.lyrics.trim();
if !attached.is_empty() {
if crate::lyrics::is_timed(attached) {
let _ = tokio::fs::write(path.with_extension("lrc"), attached).await;
}
} else if settings.lyrics_on_download && tagging_ext(path) {
let q = crate::lyrics::Query {
title: if req.meta.title.trim().is_empty() { req.entry.title.clone() } else { req.meta.title.clone() },
artist: if req.meta.artist.trim().is_empty() { req.entry.artist.clone() } else { req.meta.artist.clone() },
album: req.meta.album.clone(),
duration_ms: req.entry.duration_ms,
path: None,
};
if let Ok(Some(l)) = crate::lyrics::find(http, settings, &q, false).await.map(|f| f.lyrics) {
if l.synced {
let _ = tokio::fs::write(path.with_extension("lrc"), crate::lyrics::to_lrc(&l)).await;
}
}
}
let _ = library.add_file(path, &playlists);
if let Some(name) = req.playlist.as_deref().filter(|n| !n.trim().is_empty()) {
let _ = library.playlist_add(&playlists, name, &[path.to_path_buf()], !settings.playlist_copy);
}
let _ = app.emit(LIBRARY_EVENT, serde_json::json!({ "type": "changed" }));
}
fn tagging_ext(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| crate::library::AUDIO_EXT.contains(&e.to_ascii_lowercase().as_str()))
}
impl Downloader {
pub fn new(app: AppHandle, settings: Arc<Mutex<Settings>>, history: Arc<History>, library: Arc<Library>, http: reqwest::Client) -> Self {
let limit = settings.lock().unwrap().concurrency.max(1) as usize;
Self {
app,
history,
library,
http,
settings,
queue: Mutex::new(Queue { pending: VecDeque::new(), running: 0, limit }),
flags: Mutex::new(HashMap::new()),
next: AtomicU64::new(1),
}
}
pub fn set_concurrency(self: &Arc<Self>, n: u8) {
self.queue.lock().unwrap().limit = n.max(1) as usize;
self.pump();
}
pub fn enqueue(self: &Arc<Self>, reqs: Vec<JobRequest>, save: SaveOptions) -> Vec<u64> {
let mut ids = Vec::with_capacity(reqs.len());
{
let mut q = self.queue.lock().unwrap();
let mut flags = self.flags.lock().unwrap();
for req in reqs {
let id = self.next.fetch_add(1, Ordering::SeqCst);
let flag = Arc::new(AtomicBool::new(false));
flags.insert(id, flag.clone());
q.pending.push_back(Pending { id, req, save: save.clone(), flag });
ids.push(id);
}
}
self.pump();
ids
}
fn pump(self: &Arc<Self>) {
loop {
let next = {
let mut q = self.queue.lock().unwrap();
if q.running >= q.limit {
None
} else {
let p = q.pending.pop_front();
if p.is_some() {
q.running += 1;
}
p
}
};
let Some(p) = next else { break };
let this = self.clone();
tauri::async_runtime::spawn(async move {
let settings = this.settings.lock().unwrap().clone();
let mut job = Job::new(this.app.clone(), p.id, p.flag.clone());
let result = match job.check() {
Ok(()) => job.run(&settings, &p.req, &p.save).await,
Err(e) => Err(e),
};
match result {
Ok(Some(path)) => {
this.history.add(Record::new(&p.req, &path, job.format.clone()));
after_download(&this.app, &this.library, &this.http, &settings, &p.req, &path).await;
}
Ok(None) => {}
Err(e) if e.is::<Cancelled>() => job.emit("cancelled", None, None),
Err(e) => job.emit("error", Some(format!("{e:#}")), None),
}
this.flags.lock().unwrap().remove(&p.id);
this.queue.lock().unwrap().running -= 1;
this.pump();
});
}
}
fn drop_pending(&self, pred: impl Fn(&Pending) -> bool) {
let removed: Vec<Pending> = {
let mut q = self.queue.lock().unwrap();
let (gone, keep): (Vec<_>, Vec<_>) = q.pending.drain(..).partition(|p| pred(p));
q.pending = keep.into();
gone
};
let mut flags = self.flags.lock().unwrap();
for p in removed {
flags.remove(&p.id);
Job::new(self.app.clone(), p.id, p.flag).emit("cancelled", None, None);
}
}
pub fn cancel(&self, id: u64) {
if let Some(f) = self.flags.lock().unwrap().get(&id) {
f.store(true, Ordering::SeqCst);
}
self.drop_pending(|p| p.id == id);
}
pub fn busy(&self) -> bool {
let q = self.queue.lock().unwrap();
q.running > 0 || !q.pending.is_empty()
}
pub fn cancel_all(&self) {
self.flags.lock().unwrap().values().for_each(|f| f.store(true, Ordering::SeqCst));
self.drop_pending(|_| true);
}
}
struct Job {
app: AppHandle,
id: u64,
flag: Arc<AtomicBool>,
state: &'static str,
progress: f64,
received: u64,
total: Option<u64>,
speed: u64,
stage: u32,
last_emit: Instant,
format: Option<String>,
}
impl Job {
fn new(app: AppHandle, id: u64, flag: Arc<AtomicBool>) -> Self {
Self {
app,
id,
flag,
state: "queued",
progress: 0.0,
received: 0,
total: None,
speed: 0,
stage: 0,
last_emit: Instant::now(),
format: None,
}
}
fn check(&self) -> Result<()> {
if self.flag.load(Ordering::SeqCst) {
return Err(anyhow!(Cancelled));
}
Ok(())
}
fn emit(&mut self, state: &'static str, message: Option<String>, path: Option<&Path>) {
self.state = state;
self.last_emit = Instant::now();
let _ = self.app.emit(
EVENT,
JobEvent {
id: self.id,
state,
progress: self.progress,
received: self.received,
total: self.total,
speed: self.speed,
stage: self.stage,
format: self.format.clone(),
message,
path: path.map(|p| p.to_string_lossy().into_owned()),
},
);
}
async fn run(&mut self, settings: &Settings, req: &JobRequest, save: &SaveOptions) -> Result<Option<PathBuf>> {
self.emit("preparing", None, None);
let entry = &req.entry;
match entry.availability.as_str() {
"drm" => bail!("This stream is DRM-encrypted, so it was skipped. If it's your own track, turn on downloads for it in the platform's track settings (or enable “Use my browser sign-in”), then choose Original file to get your uploaded master."),
"preview" => bail!("Only a preview is available for this item, so it was skipped."),
_ => {}
}
let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?;
let dir = target_dir(settings, req);
tokio::fs::create_dir_all(&dir).await.map_err(|e| anyhow!("Couldn't create the output folder ({e})"))?;
let stem = file_stem(settings, req);
let plan = plan(entry, save, tools.ffmpeg.is_some())?;
self.format = Some(plan.label.clone());
if let Some(ext) = &plan.known_ext {
let target = dir.join(format!("{stem}.{ext}"));
if target.exists() {
self.progress = 1.0;
self.emit("skipped", Some("Already in your library".into()), Some(&target));
return Ok(None);
}
}
let job_temp = engine::temp_root().join(format!("job-{}", self.id));
let _ = tokio::fs::create_dir_all(&job_temp).await;
let args = build_args(settings, &tools, req, &plan, &dir, &stem, &job_temp);
let outcome = self.execute(&tools, args, &dir, &stem).await;
let _ = tokio::fs::remove_dir_all(&job_temp).await;
let path = match outcome? {
Some(p) => p,
None => {
self.progress = 1.0;
self.emit("skipped", Some("Downloaded before, so it was skipped. Turn off “Skip anything downloaded before” to fetch it again.".into()), None);
return Ok(None);
}
};
let mut notes = plan.notes.clone();
if settings.embed_metadata {
self.emit("tagging", None, None);
if let Err(e) = tagging::apply(&path, &req.meta, &req.entry.url, tools.ffmpeg.as_deref()).await {
notes.push(format!("Saved, but your metadata edits couldn't be written ({e})."));
}
}
self.progress = 1.0;
let note = (!notes.is_empty()).then(|| notes.join(" "));
self.emit("done", note, Some(&path));
Ok(Some(path))
}
async fn execute(&mut self, tools: &Tools, args: Vec<String>, dir: &Path, stem: &str) -> Result<Option<PathBuf>> {
let mut child = engine::command(&tools.ytdlp)
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| anyhow!("Couldn't start yt-dlp ({e})"))?;
let (tx, mut rx) = mpsc::unbounded_channel::<(bool, String)>();
for (is_err, pipe) in [(false, child.stdout.take().map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Unpin + Send>)), (true, child.stderr.take().map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Unpin + Send>))] {
if let Some(pipe) = pipe {
let tx = tx.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(pipe).lines();
while let Ok(Some(l)) = lines.next_line().await {
let _ = tx.send((is_err, l));
}
});
}
}
drop(tx);
let mut final_path = None;
let mut errors: Vec<String> = Vec::new();
let started = Instant::now();
loop {
tokio::select! {
msg = rx.recv() => {
let Some((is_err, line)) = msg else { break };
if is_err {
if line.contains("ERROR") || errors.len() < 40 { errors.push(line); }
continue;
}
if let Some(json) = line.strip_prefix("ATMOSP ") {
self.on_progress(json, started);
} else if let Some(p) = line.strip_prefix("ATMOSF ") {
final_path = Some(PathBuf::from(p.trim()));
}
}
_ = tokio::time::sleep(Duration::from_millis(200)) => {}
}
if self.flag.load(Ordering::SeqCst) {
let _ = child.kill().await;
cleanup(dir, stem).await;
return Err(anyhow!(Cancelled));
}
}
let status = child.wait().await?;
if !status.success() {
cleanup(dir, stem).await;
let err = errors.iter().rev().find(|l| l.contains("ERROR")).cloned().unwrap_or_else(|| errors.join("\n"));
bail!(media::humanize(&err));
}
Ok(final_path.filter(|p| p.exists()))
}
fn on_progress(&mut self, json: &str, started: Instant) {
let Ok(v) = serde_json::from_str::<Value>(json) else { return };
match v["status"].as_str() {
Some("downloading") => {
if self.state != "downloading" {
self.state = "downloading";
self.last_emit = Instant::now() - EMIT_INTERVAL;
}
self.received = v["downloaded_bytes"].as_u64().unwrap_or(self.received);
self.total = v["total_bytes"].as_u64().or_else(|| v["total_bytes_estimate"].as_f64().map(|t| t as u64));
self.speed = v["speed"].as_f64().map(|s| s as u64).unwrap_or_else(|| (self.received as f64 / started.elapsed().as_secs_f64().max(0.1)) as u64);
self.progress = match (self.total, v["fragment_index"].as_u64(), v["fragment_count"].as_u64()) {
(Some(t), _, _) if t > 0 => (self.received as f64 / t as f64).min(1.0),
(_, Some(i), Some(c)) if c > 0 => i as f64 / c as f64,
_ => self.progress,
};
if self.last_emit.elapsed() >= EMIT_INTERVAL {
self.emit("downloading", None, None);
}
}
Some("finished") => {
self.stage += 1;
self.progress = 1.0;
self.emit("processing", None, None);
}
_ => {}
}
}
}
#[derive(Debug, Clone)]
struct Plan {
format: String,
sort: Option<String>,
extract: Option<(String, Option<u32>)>,
merge: Option<String>,
video: bool,
known_ext: Option<String>,
label: String,
notes: Vec<String>,
}
fn plan(entry: &Entry, save: &SaveOptions, has_ffmpeg: bool) -> Result<Plan> {
let media = entry.media.clone().unwrap_or_default();
let from_original = media.original && media.original_lossless;
let source_abr = if from_original || media.lossless { None } else { media.best_abr };
let stream = media
.best_codec
.as_deref()
.map(|c| match media.best_abr {
Some(a) => format!("{} {a} kbps", c.to_uppercase()),
None => c.to_uppercase(),
})
.unwrap_or_else(|| "best available".into());
let original_label = format!("original {}", media.original_ext.as_deref().unwrap_or("file").to_uppercase());
let src = if from_original { original_label.clone() } else { stream.clone() };
let lossless_source = from_original || media.lossless;
let source_format = if from_original { "download/bestaudio/best" } else { "bestaudio/best" };
let mut notes = Vec::new();
let needs_ffmpeg = |what: &str| -> Result<()> {
if has_ffmpeg {
Ok(())
} else {
bail!("{what} needs ffmpeg. Install it from Settings → Engine.")
}
};
let audio = |format: &str| Plan {
format: format.into(),
sort: None,
extract: has_ffmpeg.then(|| ("best".into(), None)),
merge: None,
video: false,
known_ext: None,
label: format!("Best audio · {stream}"),
notes: Vec::new(),
};
Ok(match save.save_as {
SaveAs::Original => {
if media.original {
let mut p = audio("download/bestaudio/best");
p.extract = None;
p.label = format!("Original file{}", media.original_ext.as_deref().map(|e| format!(" · {}", e.to_uppercase())).unwrap_or_default());
p
} else {
let mut p = audio("bestaudio/best");
notes.push("The uploader hasn't offered an original file, so the best stream was saved instead.".into());
p.notes = notes;
p
}
}
SaveAs::Best => audio("bestaudio/best"),
SaveAs::Mp3 => {
needs_ffmpeg("Saving as MP3")?;
let kbps = snap_bitrate(save.mp3_bitrate, source_abr);
if kbps < save.mp3_bitrate {
notes.push(format!("Encoded at {kbps} kbps to match the source ({src}); a higher bitrate wouldn't add quality."));
}
let floor = kbps.saturating_sub(8);
Plan {
format: if from_original { source_format.into() } else { format!("bestaudio[acodec^=mp3][abr>={floor}]/bestaudio/best") },
sort: None,
extract: Some(("mp3".into(), Some(kbps))),
merge: None,
video: false,
known_ext: Some("mp3".into()),
label: format!("MP3 {kbps} kbps · from {src}"),
notes,
}
}
SaveAs::M4a => {
needs_ffmpeg("Saving as M4A")?;
Plan {
format: "bestaudio[acodec^=mp4a]/bestaudio/best".into(),
sort: None,
extract: Some(("m4a".into(), source_abr.map(|a| a.max(128)))),
merge: None,
video: false,
known_ext: Some("m4a".into()),
label: format!("M4A (AAC) · from {src}"),
notes,
}
}
SaveAs::Flac | SaveAs::Wav => {
let ext = save.save_as.audio_format().unwrap_or("flac");
needs_ffmpeg(&format!("Saving as {}", ext.to_uppercase()))?;
if !lossless_source {
notes.push(format!("{} is lossless, but it can't add quality beyond the {src} source.", ext.to_uppercase()));
}
Plan {
format: source_format.into(),
sort: None,
extract: Some((ext.into(), None)),
merge: None,
video: false,
known_ext: Some(ext.into()),
label: format!("{} · from {src}", ext.to_uppercase()),
notes,
}
}
SaveAs::Video => {
if !media.has_video && entry.detailed {
bail!("This item has no video. Choose an audio option instead.");
}
needs_ffmpeg("Saving video")?;
let available = media.heights.first().copied();
let h = match (save.video_height, available) {
(0, _) => None,
(want, Some(max)) if want > max => {
notes.push(format!("{want}p isn't available; saved the highest available ({max}p)."));
Some(max)
}
(want, _) => Some(want),
};
let container = match save.video_container.as_str() {
"mkv" | "webm" => save.video_container.clone(),
_ => "mp4".into(),
};
let res = h.map(|h| format!("res:{h},")).unwrap_or_default();
let sort = if container == "mp4" { format!("{res}vcodec:h264,acodec:aac") } else { res.trim_end_matches(',').to_string() };
Plan {
format: "bv*+ba/b".into(),
sort: (!sort.is_empty()).then_some(sort),
extract: None,
merge: Some(container.clone()),
video: true,
known_ext: Some(container.clone()),
label: format!("Video {} · {}", h.map(|h| format!("{h}p")).unwrap_or_else(|| "best".into()), container.to_uppercase()),
notes,
}
}
})
}
fn template_escape(s: &str) -> String {
s.replace('%', "%%")
}
fn build_args(settings: &Settings, tools: &Tools, req: &JobRequest, plan: &Plan, dir: &Path, stem: &str, temp: &Path) -> Vec<String> {
let mut a = media::base_args(settings, tools);
let push = |a: &mut Vec<String>, items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
push(&mut a, &["--newline", "--progress", "--no-playlist", "--no-mtime", "--no-overwrites", "--concurrent-fragments", "4"]);
push(&mut a, &["--progress-template", "download:ATMOSP %(progress)j", "--print", "after_move:ATMOSF %(filepath)s"]);
push(&mut a, &["-P", &dir.to_string_lossy(), "-P", &format!("temp:{}", temp.to_string_lossy()), "-o", &format!("{}.%(ext)s", template_escape(stem))]);
push(&mut a, &["-f", &plan.format]);
if let Some(sort) = &plan.sort {
push(&mut a, &["-S", sort]);
}
if let Some((fmt, kbps)) = &plan.extract {
push(&mut a, &["-x", "--audio-format", fmt]);
if let Some(k) = kbps {
push(&mut a, &["--audio-quality", &format!("{k}K")]);
}
}
if let Some(container) = &plan.merge {
push(&mut a, &["--merge-output-format", container, "--remux-video", container]);
}
let has_ff = tools.ffmpeg.is_some();
if settings.embed_metadata {
push(&mut a, &["--embed-metadata"]);
let wav = plan.extract.as_ref().is_some_and(|(f, _)| f == "wav");
if has_ff && !wav {
push(&mut a, &["--embed-thumbnail", "--convert-thumbnails", "jpg"]);
}
}
if settings.embed_chapters && has_ff {
push(&mut a, &["--embed-chapters"]);
}
if plan.video && settings.embed_subtitles && has_ff {
push(&mut a, &["--write-subs", "--sub-langs", settings.subtitle_langs.trim(), "--embed-subs"]);
}
if settings.sponsorblock && has_ff && req.entry.platform == "YouTube" {
let cats = if plan.video { "sponsor,selfpromo,interaction" } else { "sponsor,selfpromo,interaction,music_offtopic" };
push(&mut a, &["--sponsorblock-remove", cats]);
}
if let Some(t) = req.trim.as_ref().filter(|t| !t.start.trim().is_empty() || !t.end.trim().is_empty()) {
let start = if t.start.trim().is_empty() { "0" } else { t.start.trim() };
let end = if t.end.trim().is_empty() { "inf" } else { t.end.trim() };
push(&mut a, &["--download-sections", &format!("*{start}-{end}")]);
if has_ff {
push(&mut a, &["--force-keyframes-at-cuts"]);
}
}
if settings.skip_downloaded {
push(&mut a, &["--download-archive", &engine::data_dir().join("archive.txt").to_string_lossy()]);
}
if !settings.rate_limit.trim().is_empty() {
push(&mut a, &["--limit-rate", settings.rate_limit.trim()]);
}
push(&mut a, &["--", &req.entry.url]);
a
}
async fn cleanup(dir: &Path, stem: &str) {
let Ok(mut rd) = tokio::fs::read_dir(dir).await else { return };
while let Ok(Some(e)) = rd.next_entry().await {
let name = e.file_name().to_string_lossy().into_owned();
let leftover = [".part", ".ytdl", ".temp", ".webp", ".jpg", ".png"].iter().any(|x| name.ends_with(x)) || name.contains(".part-Frag");
if name.starts_with(stem) && leftover {
let _ = tokio::fs::remove_file(e.path()).await;
}
}
}
fn target_dir(settings: &Settings, req: &JobRequest) -> PathBuf {
let base = PathBuf::from(&settings.output_dir);
match (&req.folder, settings.collection_folders) {
(Some(name), true) if !name.trim().is_empty() => base.join(sanitize(name)),
_ => base,
}
}
fn file_stem(settings: &Settings, req: &JobRequest) -> String {
let m = &req.meta;
let title = if m.title.trim().is_empty() { &req.entry.title } else { &m.title };
let artist = if m.artist.trim().is_empty() { &req.entry.artist } else { &m.artist };
let width = m.track_total.map_or(2, |n| n.to_string().len().max(2));
let index = m.track_number.map(|i| format!("{i:0width$}"));
let year = m.date.get(..4).unwrap_or_default().to_string();
let template = &settings.filename_template;
let mut name = template
.replace("{artist}", artist)
.replace("{title}", title)
.replace("{album}", &m.album)
.replace("{albumartist}", &m.album_artist)
.replace("{collection}", req.folder.as_deref().unwrap_or(""))
.replace("{genre}", &m.genre)
.replace("{year}", &year)
.replace("{platform}", &req.entry.platform)
.replace("{index}", index.as_deref().unwrap_or(""));
if settings.number_tracks && req.folder.is_some() && !template.contains("{index}") {
if let Some(i) = index {
name = format!("{i} - {name}");
}
}
sanitize(&name)
}
pub fn sanitize(input: &str) -> String {
let cleaned: String = input.chars().map(|c| if c.is_control() || r#"<>:"/\|?*"#.contains(c) { '_' } else { c }).collect();
let mut out = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
out = out.trim_matches(|c: char| c == '.' || c == ' ' || c == '-').to_string();
if out.chars().count() > 150 {
out = out.chars().take(150).collect::<String>().trim_end().to_string();
}
let upper = out.split('.').next().unwrap_or_default().to_ascii_uppercase();
let reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| ((upper.starts_with("COM") || upper.starts_with("LPT")) && upper.len() == 4 && upper.as_bytes()[3].is_ascii_digit());
if reserved {
out.insert(0, '_');
}
if out.is_empty() {
"untitled".into()
} else {
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::media::MediaInfo;
fn entry(abr: Option<u32>, lossless: bool, heights: Vec<u32>) -> Entry {
Entry {
title: "Night Drive".into(),
artist: "Nova".into(),
url: "https://example.com/x".into(),
detailed: true,
availability: "ok".into(),
media: Some(MediaInfo { best_abr: abr, best_codec: Some("aac".into()), lossless, has_video: !heights.is_empty(), heights, ..Default::default() }),
..Default::default()
}
}
fn save(save_as: SaveAs, kbps: u32, h: u32) -> SaveOptions {
SaveOptions { save_as, mp3_bitrate: kbps, video_height: h, video_container: "mp4".into() }
}
#[test]
fn mp3_bitrate_never_exceeds_source() {
let p = plan(&entry(Some(160), false, vec![]), &save(SaveAs::Mp3, 320, 0), true).unwrap();
assert_eq!(p.extract, Some(("mp3".into(), Some(160))));
assert!(p.label.starts_with("MP3 160 kbps"));
assert_eq!(p.notes.len(), 1);
let p = plan(&entry(None, true, vec![]), &save(SaveAs::Mp3, 320, 0), true).unwrap();
assert_eq!(p.extract, Some(("mp3".into(), Some(320))));
}
#[test]
fn lossless_original_lifts_the_mp3_cap_honestly() {
let mut e = entry(Some(160), false, vec![]);
if let Some(m) = e.media.as_mut() {
m.original = true;
m.original_lossless = true;
m.original_ext = Some("wav".into());
}
let p = plan(&e, &save(SaveAs::Mp3, 320, 0), true).unwrap();
assert_eq!(p.extract, Some(("mp3".into(), Some(320))));
assert!(p.format.starts_with("download/"));
assert!(p.label.contains("original WAV"));
let plain = plan(&entry(Some(160), false, vec![]), &save(SaveAs::Flac, 320, 0), true).unwrap();
assert_eq!(plain.notes.len(), 1);
}
#[test]
fn video_plans_respect_available_heights() {
let p = plan(&entry(Some(128), false, vec![720, 480]), &save(SaveAs::Video, 1080, 1080), true).unwrap();
assert!(p.label.contains("720p"));
assert_eq!(p.sort.as_deref(), Some("res:720,vcodec:h264,acodec:aac"));
assert!(plan(&entry(Some(128), false, vec![]), &save(SaveAs::Video, 0, 1080), true).is_err());
assert!(plan(&entry(Some(128), false, vec![720]), &save(SaveAs::Mp3, 320, 0), false).is_err());
}
#[test]
fn builds_stems_and_escapes_templates() {
let mut settings = Settings::default();
settings.output_dir = "out".into();
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);
assert_eq!(stem, "003 - Nova - 100% Night");
assert_eq!(template_escape(&stem), "003 - Nova - 100%% Night");
assert_eq!(target_dir(&settings, &req), PathBuf::from("out").join("Nova - Glass_ Vol 1"));
assert_eq!(sanitize("con"), "_con");
}
}
+306
View File
@@ -0,0 +1,306 @@
// atmosphere · engine.rs · Locates, installs and runs the yt-dlp and ffmpeg tools that power every download.
use anyhow::{anyhow, bail, Context, Result};
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::process::Command;
#[cfg(windows)]
const EXE: &str = ".exe";
#[cfg(not(windows))]
const EXE: &str = "";
const YTDLP_RELEASE: &str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download";
const FFMPEG_RELEASE: &str = "https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest";
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolInfo {
pub path: Option<String>,
pub version: Option<String>,
pub managed: bool,
}
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolStatus {
pub ytdlp: ToolInfo,
pub ffmpeg: ToolInfo,
pub can_install_ffmpeg: bool,
}
pub fn bin_dir() -> PathBuf {
data_dir().join("bin")
}
pub fn portable_root() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
let dir = exe.parent()?;
["portable", "portable.txt", ".portable"].iter().any(|m| dir.join(m).is_file()).then(|| dir.join("AtmosphereData"))
}
pub fn data_dir() -> PathBuf {
if let Some(dir) = std::env::var_os("ATMOSPHERE_DATA_DIR") {
return PathBuf::from(dir);
}
portable_root().unwrap_or_else(|| dirs::data_local_dir().unwrap_or_else(|| PathBuf::from(".")).join("atmosphere"))
}
pub fn temp_root() -> PathBuf {
data_dir().join("temp")
}
fn search_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
if cfg!(unix) {
let home = dirs::home_dir().unwrap_or_default();
for extra in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/snap/bin", "/opt/local/bin"] {
dirs.push(PathBuf::from(extra));
}
dirs.push(home.join(".local/bin"));
dirs.push(home.join("bin"));
}
dirs
}
fn on_path(name: &str) -> Option<PathBuf> {
let file = format!("{name}{EXE}");
search_dirs().into_iter().map(|d| d.join(&file)).find(|c| c.is_file())
}
fn resolve(custom: &str, name: &str) -> (Option<PathBuf>, bool) {
if !custom.trim().is_empty() {
let p = PathBuf::from(custom.trim());
return (p.is_file().then_some(p), false);
}
let managed = bin_dir().join(format!("{name}{EXE}"));
if managed.is_file() {
return (Some(managed), true);
}
(on_path(name), false)
}
pub fn command(program: &Path) -> Command {
let mut cmd = Command::new(program);
cmd.stdin(Stdio::null()).env("PYTHONIOENCODING", "utf-8").env("PYTHONUTF8", "1");
#[cfg(windows)]
cmd.creation_flags(0x0800_0000);
cmd
}
async fn version_of(path: &Path, args: &[&str]) -> Option<String> {
let out = command(path).args(args).stdout(Stdio::piped()).stderr(Stdio::null()).output().await.ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let line = text.lines().next()?.trim();
let v = line.strip_prefix("ffmpeg version ").map(|r| r.split_whitespace().next().unwrap_or(r)).unwrap_or(line);
(!v.is_empty()).then(|| v.to_string())
}
pub struct Tools {
pub ytdlp: PathBuf,
pub ffmpeg: Option<PathBuf>,
}
pub fn locate(ytdlp_custom: &str, ffmpeg_custom: &str) -> Result<Tools> {
let (ytdlp, _) = resolve(ytdlp_custom, "yt-dlp");
let ytdlp = ytdlp.ok_or_else(|| anyhow!("yt-dlp isn't set up yet. Open Settings → Engine to install it."))?;
let (ffmpeg, _) = resolve(ffmpeg_custom, "ffmpeg");
Ok(Tools { ytdlp, ffmpeg })
}
pub async fn status(ytdlp_custom: &str, ffmpeg_custom: &str) -> ToolStatus {
let (yp, ym) = resolve(ytdlp_custom, "yt-dlp");
let (fp, fm) = resolve(ffmpeg_custom, "ffmpeg");
let yv = match &yp {
Some(p) => version_of(p, &["--version"]).await,
None => None,
};
let fv = match &fp {
Some(p) => version_of(p, &["-version"]).await,
None => None,
};
ToolStatus {
ytdlp: ToolInfo { path: yp.map(|p| p.to_string_lossy().into_owned()), version: yv, managed: ym },
ffmpeg: ToolInfo { path: fp.map(|p| p.to_string_lossy().into_owned()), version: fv, managed: fm },
can_install_ffmpeg: ffmpeg_asset().is_some(),
}
}
fn ytdlp_asset() -> &'static str {
match (std::env::consts::OS, std::env::consts::ARCH) {
("windows", _) => "yt-dlp.exe",
("macos", _) => "yt-dlp_macos",
("linux", "aarch64") => "yt-dlp_linux_aarch64",
_ => "yt-dlp_linux",
}
}
fn ffmpeg_asset() -> Option<&'static str> {
match (std::env::consts::OS, std::env::consts::ARCH) {
("windows", "aarch64") => Some("ffmpeg-master-latest-winarm64-gpl.zip"),
("windows", _) => Some("ffmpeg-master-latest-win64-gpl.zip"),
("linux", "aarch64") => Some("ffmpeg-master-latest-linuxarm64-gpl.tar.xz"),
("linux", "x86_64") => Some("ffmpeg-master-latest-linux64-gpl.tar.xz"),
_ => None,
}
}
fn wanted(path: &str) -> Option<String> {
let path = path.replace('\\', "/");
let file = path.rsplit('/').next().unwrap_or_default();
(path.contains("/bin/") && (file == format!("ffmpeg{EXE}") || file == format!("ffprobe{EXE}"))).then(|| file.to_string())
}
fn extract_ffmpeg(asset: &str, data: Vec<u8>, dir: &Path) -> Result<PathBuf> {
let mut found = None;
let mut keep = |file: String, buf: Vec<u8>| -> Result<()> {
let dest = dir.join(&file);
write_exec(&dest, &buf)?;
if file.starts_with("ffmpeg") {
found = Some(dest);
}
Ok(())
};
if asset.ends_with(".zip") {
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(data))?;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
if let Some(file) = wanted(&entry.name()?) {
let mut buf = Vec::with_capacity(entry.size() as usize);
entry.read_to_end(&mut buf)?;
keep(file, buf)?;
}
}
} else {
let mut tar_bytes = Vec::new();
lzma_rs::xz_decompress(&mut std::io::BufReader::new(std::io::Cursor::new(data)), &mut tar_bytes)
.map_err(|e| anyhow!("Couldn't unpack ffmpeg ({e})"))?;
let mut archive = tar::Archive::new(std::io::Cursor::new(tar_bytes));
for entry in archive.entries()? {
let mut entry = entry?;
let name = entry.path()?.to_string_lossy().into_owned();
if let Some(file) = wanted(&name) {
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
keep(file, buf)?;
}
}
}
found.ok_or_else(|| anyhow!("ffmpeg wasn't in the downloaded archive"))
}
async fn fetch(http: &reqwest::Client, url: &str, mut progress: impl FnMut(u64, Option<u64>)) -> Result<Vec<u8>> {
use futures_util::StreamExt;
let resp = http.get(url).send().await?.error_for_status().with_context(|| format!("Download failed: {url}"))?;
let total = resp.content_length();
let mut body = resp.bytes_stream();
let mut data = Vec::with_capacity(total.unwrap_or(0) as usize);
while let Some(chunk) = body.next().await {
data.extend_from_slice(&chunk?);
progress(data.len() as u64, total);
}
Ok(data)
}
fn expected_hash(sums: &str, asset: &str) -> Option<String> {
sums.lines().find_map(|l| {
let mut parts = l.split_whitespace();
let hash = parts.next()?;
let name = parts.next()?.trim_start_matches('*');
(name == asset).then(|| hash.to_ascii_lowercase())
})
}
fn verify(data: &[u8], sums: &str, asset: &str) -> Result<()> {
let expected = expected_hash(sums, asset).ok_or_else(|| anyhow!("No published checksum for {asset}"))?;
let actual = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect::<String>();
if actual != expected {
bail!("Checksum mismatch for {asset}. The download was discarded.");
}
Ok(())
}
fn write_exec(path: &Path, data: &[u8]) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("download");
std::fs::write(&tmp, data)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
}
std::fs::rename(&tmp, path)?;
Ok(())
}
pub async fn install_ytdlp(http: &reqwest::Client, progress: impl FnMut(u64, Option<u64>)) -> Result<PathBuf> {
let asset = ytdlp_asset();
let sums = http.get(format!("{YTDLP_RELEASE}/SHA2-256SUMS")).send().await?.error_for_status()?.text().await?;
let data = fetch(http, &format!("{YTDLP_RELEASE}/{asset}"), progress).await?;
verify(&data, &sums, asset)?;
let dest = bin_dir().join(format!("yt-dlp{EXE}"));
write_exec(&dest, &data)?;
Ok(dest)
}
pub async fn install_ffmpeg(http: &reqwest::Client, progress: impl FnMut(u64, Option<u64>)) -> Result<PathBuf> {
let Some(asset) = ffmpeg_asset() else {
bail!(if cfg!(target_os = "macos") {
"On macOS, install ffmpeg with Homebrew (`brew install ffmpeg`). Atmosphere finds it automatically."
} else {
"Install ffmpeg with your package manager, then restart Atmosphere."
});
};
let sums = http.get(format!("{FFMPEG_RELEASE}/checksums.sha256")).send().await?.error_for_status()?.text().await?;
let data = fetch(http, &format!("{FFMPEG_RELEASE}/{asset}"), progress).await?;
verify(&data, &sums, asset)?;
let dir = bin_dir();
tokio::task::spawn_blocking(move || extract_ffmpeg(asset, data, &dir)).await?
}
pub async fn update_ytdlp(path: &Path) -> Result<String> {
let out = command(path).arg("-U").stdout(Stdio::piped()).stderr(Stdio::piped()).output().await?;
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
let line = text
.lines()
.rev()
.find(|l| l.contains("Updated") || l.contains("up to date") || l.contains("ERROR"))
.unwrap_or("Update finished")
.trim()
.trim_start_matches("ERROR: ")
.to_string();
if !out.status.success() {
bail!(line);
}
Ok(line)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_checksums() {
let sums = "abc123 yt-dlp.exe\nDEF456 *yt-dlp_linux\n";
assert_eq!(expected_hash(sums, "yt-dlp.exe").as_deref(), Some("abc123"));
assert_eq!(expected_hash(sums, "yt-dlp_linux").as_deref(), Some("def456"));
assert!(expected_hash(sums, "nope").is_none());
let data = b"hello";
let good = format!("{} file.bin", Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect::<String>());
assert!(verify(data, &good, "file.bin").is_ok());
assert!(verify(b"tampered", &good, "file.bin").is_err());
}
#[test]
fn picks_ffmpeg_binaries_from_archives() {
let exe = |n: &str| format!("{n}{EXE}");
assert_eq!(wanted(&format!("ffmpeg-master-latest/bin/{}", exe("ffmpeg"))), Some(exe("ffmpeg")));
assert_eq!(wanted(&format!("ffmpeg-master-latest\\bin\\{}", exe("ffprobe"))), Some(exe("ffprobe")));
assert_eq!(wanted("ffmpeg-master-latest/doc/ffmpeg.html"), None);
assert_eq!(wanted(&format!("ffmpeg-master-latest/bin/{}", exe("ffplay"))), None);
}
}
+96
View File
@@ -0,0 +1,96 @@
// atmosphere · history.rs · Persists the list of finished downloads so the Library view survives restarts.
use crate::downloader::JobRequest;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
const LIMIT: usize = 5000;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Record {
pub id: String,
pub title: String,
pub artist: String,
pub platform: String,
pub url: String,
pub path: String,
pub format: Option<String>,
pub collection: Option<String>,
pub thumbnail: Option<String>,
pub at: u64,
}
impl Record {
pub fn new(req: &JobRequest, path: &Path, format: Option<String>) -> Self {
let at = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
let pick = |edited: &str, original: &str| if edited.trim().is_empty() { original.to_string() } else { edited.to_string() };
Self {
id: format!("{at}-{}", req.entry.index),
title: pick(&req.meta.title, &req.entry.title),
artist: pick(&req.meta.artist, &req.entry.artist),
platform: req.entry.platform.clone(),
url: req.entry.url.clone(),
path: path.to_string_lossy().into_owned(),
format,
collection: req.folder.clone(),
thumbnail: req.entry.thumbnail.clone(),
at,
}
}
}
pub struct History {
file: PathBuf,
items: Mutex<Vec<Record>>,
}
impl History {
pub fn load(file: PathBuf) -> Self {
let items = std::fs::read_to_string(&file).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
Self { file, items: Mutex::new(items) }
}
fn persist(&self, items: &[Record]) {
if let Some(dir) = self.file.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(data) = serde_json::to_vec(items) {
let tmp = self.file.with_extension("json.tmp");
if std::fs::write(&tmp, data).is_ok() {
let _ = std::fs::rename(&tmp, &self.file);
}
}
}
pub fn add(&self, record: Record) {
let mut items = self.items.lock().unwrap();
items.retain(|r| r.path != record.path);
items.insert(0, record);
items.truncate(LIMIT);
self.persist(&items);
}
pub fn list(&self) -> Vec<Record> {
self.items.lock().unwrap().iter().map(|r| {
let mut r = r.clone();
if !Path::new(&r.path).exists() {
r.path = String::new();
}
r
}).collect()
}
pub fn remove(&self, ids: &[String]) {
let mut items = self.items.lock().unwrap();
items.retain(|r| !ids.contains(&r.id));
self.persist(&items);
}
pub fn clear(&self) {
let mut items = self.items.lock().unwrap();
items.clear();
self.persist(&items);
}
}
+452
View File
@@ -0,0 +1,452 @@
// atmosphere · libcmd.rs · Library, playlist, lyrics and window commands, plus the atmo:// media protocol that streams local files.
use crate::library::{Snapshot, Track};
use crate::lyrics::{self, Found, Lyrics, Query};
use crate::tagging::{self, TagFields};
use crate::{err, AppState, CmdResult};
use notify::{RecursiveMode, Watcher};
use std::collections::HashSet;
use std::io::{Read, Seek, SeekFrom};
use std::sync::Mutex;
use std::time::Duration;
use std::path::{Path, PathBuf};
use tauri::http::{Request, Response};
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_dialog::DialogExt;
pub const LIBRARY_EVENT: &str = crate::downloader::LIBRARY_EVENT;
const MAX_CHUNK: u64 = 4 * 1024 * 1024;
fn dirs(state: &AppState) -> (Vec<PathBuf>, PathBuf) {
let s = state.snapshot();
(s.library_folders.iter().map(PathBuf::from).collect(), PathBuf::from(&s.playlists_dir))
}
fn changed(app: &AppHandle) {
let _ = app.emit(LIBRARY_EVENT, serde_json::json!({ "type": "changed" }));
}
#[tauri::command]
pub fn library_get(state: State<'_, AppState>) -> Snapshot {
let (_, pl) = dirs(&state);
state.library.snapshot(&pl)
}
pub fn spawn_scan(app: AppHandle) {
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
let (roots, pl) = dirs(&state);
let _ = std::fs::create_dir_all(&pl);
let emitter = app.clone();
let result = state.library.scan(&roots, &pl, |done, total| {
let _ = emitter.emit(LIBRARY_EVENT, serde_json::json!({ "type": "progress", "done": done, "total": total }));
});
let _ = app.emit(LIBRARY_EVENT, match result {
Ok(n) => serde_json::json!({ "type": "scanned", "count": n }),
Err(e) => serde_json::json!({ "type": "error", "message": format!("{e:#}") }),
});
});
}
static WATCHER: Mutex<Option<notify::RecommendedWatcher>> = Mutex::new(None);
fn apply_changes(app: &AppHandle, paths: HashSet<PathBuf>) {
let state = app.state::<AppState>();
let (_, pl) = dirs(&state);
let temp = crate::engine::temp_root();
let mut touched = false;
for p in paths {
if p.starts_with(&temp) || p.file_name().and_then(|n| n.to_str()).is_some_and(crate::storage::is_partial) {
continue;
}
if p.file_name().and_then(|n| n.to_str()) == Some("playlist.m3u8") {
touched = true;
continue;
}
if !p.exists() {
touched |= state.library.remove_under(&p) > 0;
} else if p.is_dir() {
for e in walkdir::WalkDir::new(&p).into_iter().flatten().filter(|e| e.file_type().is_file()) {
if crate::library::is_audio(e.path()) && !state.library.knows(e.path()) {
touched |= state.library.add_file(e.path(), &pl).is_ok();
}
}
} else if crate::library::is_audio(&p) && !state.library.knows(&p) {
touched |= state.library.add_file(&p, &pl).is_ok();
}
}
if touched {
changed(app);
}
}
pub fn start_watch(app: AppHandle) {
let (tx, rx) = std::sync::mpsc::channel::<notify::Result<notify::Event>>();
let Ok(mut watcher) = notify::recommended_watcher(tx) else { return };
let (roots, pl) = dirs(&app.state::<AppState>());
let _ = std::fs::create_dir_all(&pl);
let mut watched: Vec<PathBuf> = Vec::new();
for r in roots.into_iter().chain(std::iter::once(pl)) {
if r.is_dir() && !watched.iter().any(|w| r.starts_with(w)) && watcher.watch(&r, RecursiveMode::Recursive).is_ok() {
watched.push(r);
}
}
*WATCHER.lock().unwrap() = Some(watcher);
std::thread::spawn(move || {
while let Ok(first) = rx.recv() {
let mut batch: HashSet<PathBuf> = HashSet::new();
if let Ok(ev) = first {
batch.extend(ev.paths);
}
while let Ok(next) = rx.recv_timeout(Duration::from_millis(700)) {
if let Ok(ev) = next {
batch.extend(ev.paths);
}
}
if !batch.is_empty() {
apply_changes(&app, batch);
}
}
});
}
#[tauri::command]
pub fn library_scan(app: AppHandle) {
spawn_scan(app);
}
#[tauri::command]
pub async fn library_add_folder(app: AppHandle, state: State<'_, AppState>) -> CmdResult<Option<String>> {
let a = app.clone();
let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title("Add a music folder").blocking_pick_folder())
.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.to_string_lossy().into_owned();
state.update(|s| {
if !s.library_folders.contains(&p) {
s.library_folders.push(p.clone());
}
})?;
spawn_scan(app.clone());
start_watch(app);
Ok(Some(p))
}
#[tauri::command]
pub fn library_remove_folder(app: AppHandle, state: State<'_, AppState>, path: String) -> CmdResult<()> {
state.update(|s| s.library_folders.retain(|f| *f != path))?;
spawn_scan(app.clone());
start_watch(app);
Ok(())
}
#[tauri::command]
pub fn playlist_create(app: AppHandle, state: State<'_, AppState>, name: String) -> CmdResult<String> {
let (_, pl) = dirs(&state);
let n = state.library.playlist_create(&pl, &name).map_err(err)?;
changed(&app);
Ok(n)
}
#[tauri::command]
pub fn playlist_rename(app: AppHandle, state: State<'_, AppState>, from: String, to: String) -> CmdResult<String> {
let (_, pl) = dirs(&state);
let n = state.library.playlist_rename(&pl, &from, &to).map_err(err)?;
changed(&app);
Ok(n)
}
#[tauri::command]
pub fn playlist_delete(app: AppHandle, state: State<'_, AppState>, name: String) -> CmdResult<()> {
let (_, pl) = dirs(&state);
state.library.playlist_delete(&pl, &name).map_err(err)?;
changed(&app);
Ok(())
}
#[tauri::command]
pub async fn playlist_add(app: AppHandle, state: State<'_, AppState>, name: String, ids: Vec<String>) -> CmdResult<usize> {
let (_, pl) = dirs(&state);
let sources: Vec<PathBuf> = ids.iter().filter_map(|id| state.library.track(id)).map(|t| PathBuf::from(t.path)).collect();
let link = !state.snapshot().playlist_copy;
let lib = state.library.clone();
let n = tauri::async_runtime::spawn_blocking(move || lib.playlist_add(&pl, &name, &sources, link)).await.map_err(|e| e.to_string())?.map_err(err)?;
changed(&app);
Ok(n)
}
#[tauri::command]
pub async fn playlist_add_files(app: AppHandle, state: State<'_, AppState>, name: String) -> CmdResult<usize> {
let a = app.clone();
let picked = tauri::async_runtime::spawn_blocking(move || {
a.dialog().file().set_title("Add songs to the playlist").add_filter("Audio", &crate::library::AUDIO_EXT).blocking_pick_files()
})
.await
.map_err(|e| e.to_string())?;
let files: Vec<PathBuf> = picked.unwrap_or_default().into_iter().filter_map(|p| p.into_path().ok()).collect();
if files.is_empty() {
return Ok(0);
}
let (_, pl) = dirs(&state);
let lib = state.library.clone();
let n = tauri::async_runtime::spawn_blocking(move || lib.playlist_add(&pl, &name, &files, false)).await.map_err(|e| e.to_string())?.map_err(err)?;
changed(&app);
Ok(n)
}
#[tauri::command]
pub fn playlist_remove(app: AppHandle, state: State<'_, AppState>, name: String, ids: Vec<String>) -> CmdResult<()> {
let (_, pl) = dirs(&state);
state.library.playlist_remove(&pl, &name, &ids).map_err(err)?;
changed(&app);
Ok(())
}
#[tauri::command]
pub fn playlist_reorder(state: State<'_, AppState>, name: String, ids: Vec<String>) -> CmdResult<()> {
let (_, pl) = dirs(&state);
state.library.playlist_reorder(&pl, &name, &ids).map_err(err)
}
#[tauri::command]
pub async fn tracks_delete(app: AppHandle, state: State<'_, AppState>, ids: Vec<String>, playlists: bool) -> CmdResult<usize> {
let (_, pl) = dirs(&state);
let lib = state.library.clone();
let n = tauri::async_runtime::spawn_blocking(move || lib.delete(&ids, &pl, playlists)).await.map_err(|e| e.to_string())?;
changed(&app);
n.map_err(err)
}
#[tauri::command]
pub fn tracks_hide(app: AppHandle, state: State<'_, AppState>, ids: Vec<String>) -> usize {
let n = state.library.hide(&ids);
changed(&app);
n
}
#[tauri::command]
pub fn tracks_unhide_all(app: AppHandle, state: State<'_, AppState>) -> usize {
let n = state.library.unhide_all();
spawn_scan(app);
n
}
#[tauri::command]
pub fn track_played(state: State<'_, AppState>, id: String) {
state.library.played(&id);
}
#[tauri::command]
pub fn track_listened(state: State<'_, AppState>, id: String, ms: u64) {
state.library.listened(&id, ms);
}
#[tauri::command]
pub fn app_heartbeat(state: State<'_, AppState>, day: String, secs: u64) {
state.library.app_seconds(&day, secs);
}
#[tauri::command]
pub fn stats_get(state: State<'_, AppState>) -> crate::library::StatsData {
state.library.stats()
}
fn png_from(data: &str) -> CmdResult<Vec<u8>> {
use base64::Engine as _;
let raw = data.split_once(',').map(|(_, b)| b).unwrap_or(data);
base64::engine::general_purpose::STANDARD.decode(raw).map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn image_save(app: AppHandle, data: String, name: String) -> CmdResult<Option<String>> {
let bytes = png_from(&data)?;
let a = app.clone();
let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title("Save your stats").set_file_name(&name).add_filter("PNG image", &["png"]).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) };
std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
Ok(Some(path.to_string_lossy().into_owned()))
}
#[tauri::command]
pub fn image_copy(app: AppHandle, data: String) -> CmdResult<()> {
use tauri_plugin_clipboard_manager::ClipboardExt;
let bytes = png_from(&data)?;
let img = tauri::image::Image::from_bytes(&bytes).map_err(|e| e.to_string())?;
app.clipboard().write_image(&img).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn track_like(state: State<'_, AppState>, id: String, liked: bool) {
state.library.like(&id, liked);
}
#[tauri::command]
pub async fn track_edit(app: AppHandle, state: State<'_, AppState>, id: String, meta: TagFields) -> CmdResult<Track> {
let t = state.library.track(&id).ok_or("That track is no longer in the library")?;
let s = state.snapshot();
let ffmpeg = crate::engine::locate(&s.ytdlp_path, &s.ffmpeg_path).ok().and_then(|t| t.ffmpeg);
tagging::apply(Path::new(&t.path), &meta, "", ffmpeg.as_deref()).await.map_err(err)?;
let (_, pl) = dirs(&state);
let updated = state.library.refresh(&id, &pl).map_err(err)?;
changed(&app);
Ok(updated)
}
#[tauri::command]
pub async fn artist_update(app: AppHandle, state: State<'_, AppState>, name: String, pick_image: bool, bio: Option<String>) -> CmdResult<crate::library::ArtistMeta> {
let image = if pick_image {
let a = app.clone();
let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title("Choose an artist image").add_filter("Images", &["jpg", "jpeg", "png"]).blocking_pick_file())
.await
.map_err(|e| e.to_string())?;
match picked.and_then(|p| p.into_path().ok()) {
Some(p) => Some(p),
None => return Err("cancelled".into()),
}
} else {
None
};
let meta = state.library.set_artist(&name, image.as_deref(), bio).map_err(err)?;
changed(&app);
Ok(meta)
}
#[tauri::command]
pub async fn lyrics_get(state: State<'_, AppState>, query: Query, refresh: bool) -> CmdResult<Found> {
let s = state.snapshot();
lyrics::find(&state.http, &s, &query, refresh).await.map_err(err)
}
#[tauri::command]
pub fn lyrics_save(app: AppHandle, state: State<'_, AppState>, id: String, lyrics: Lyrics) -> CmdResult<()> {
let t = state.library.track(&id).ok_or("That track is no longer in the library")?;
std::fs::write(Path::new(&t.path).with_extension("lrc"), lyrics::to_lrc(&lyrics)).map_err(|e| e.to_string())?;
let (_, pl) = dirs(&state);
let _ = state.library.refresh(&id, &pl);
changed(&app);
Ok(())
}
#[tauri::command]
pub async fn lyrics_save_text(app: AppHandle, state: State<'_, AppState>, id: String, text: String) -> CmdResult<()> {
let t = state.library.track(&id).ok_or("That track is no longer in the library")?;
let path = PathBuf::from(&t.path);
let lrc = path.with_extension("lrc");
let text = text.trim().to_string();
if lyrics::is_timed(&text) {
std::fs::write(&lrc, &text).map_err(|e| e.to_string())?;
} else if lrc.exists() {
let _ = trash::delete(&lrc);
}
let meta = TagFields { lyrics: if text.is_empty() { String::new() } else { text.clone() }, ..Default::default() };
if !text.is_empty() {
tagging::apply(&path, &meta, "", None).await.map_err(err)?;
}
let (_, pl) = dirs(&state);
let _ = state.library.refresh(&id, &pl);
changed(&app);
Ok(())
}
#[tauri::command]
pub fn set_fullscreen(app: AppHandle, on: bool) -> CmdResult<bool> {
let w = app.get_webview_window("main").ok_or("No window")?;
w.set_fullscreen(on).map_err(|e| e.to_string())?;
w.is_fullscreen().map_err(|e| e.to_string())
}
fn mime(path: &Path) -> &'static str {
match path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase().as_str() {
"mp3" => "audio/mpeg",
"m4a" | "mp4" | "aac" => "audio/mp4",
"flac" => "audio/flac",
"ogg" => "audio/ogg",
"opus" => "audio/ogg; codecs=opus",
"wav" => "audio/wav",
"aiff" | "aif" => "audio/aiff",
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
_ => "application/octet-stream",
}
}
fn respond(status: u16, ctype: &str, body: Vec<u8>, extra: &[(&str, String)]) -> Response<Vec<u8>> {
let mut b = Response::builder().status(status).header("Content-Type", ctype).header("Access-Control-Allow-Origin", "*").header("Accept-Ranges", "bytes");
for (k, v) in extra {
b = b.header(*k, v.as_str());
}
b.body(body).unwrap_or_else(|_| Response::new(Vec::new()))
}
fn range_of(header: Option<&str>, len: u64) -> Option<(u64, u64)> {
let spec = header?.trim().strip_prefix("bytes=")?;
let (a, b) = spec.split_once('-')?;
let (start, end) = if a.is_empty() {
let n: u64 = b.parse().ok()?;
(len.saturating_sub(n), len - 1)
} else {
let s: u64 = a.parse().ok()?;
let e = if b.is_empty() { (s + MAX_CHUNK - 1).min(len - 1) } else { b.parse::<u64>().ok()?.min(len - 1) };
(s, e)
};
(start <= end && start < len).then_some((start, end))
}
fn stream(path: &Path, range: Option<&str>) -> Response<Vec<u8>> {
let Ok(mut f) = std::fs::File::open(path) else { return respond(404, "text/plain", b"not found".to_vec(), &[]) };
let len = f.metadata().map(|m| m.len()).unwrap_or(0);
if len == 0 {
return respond(200, mime(path), Vec::new(), &[]);
}
match range_of(range, len) {
Some((start, end)) => {
let mut buf = vec![0u8; (end - start + 1) as usize];
if f.seek(SeekFrom::Start(start)).is_err() || f.read_exact(&mut buf).is_err() {
return respond(416, "text/plain", Vec::new(), &[]);
}
respond(206, mime(path), buf, &[("Content-Range", format!("bytes {start}-{end}/{len}"))])
}
None => {
let mut buf = Vec::with_capacity(len as usize);
let _ = f.read_to_end(&mut buf);
respond(200, mime(path), buf, &[])
}
}
}
pub fn serve(app: &AppHandle, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
let state = app.state::<AppState>();
let path = request.uri().path().trim_start_matches('/').to_string();
let range = request.headers().get("range").and_then(|v| v.to_str().ok());
let (kind, id) = path.split_once('/').unwrap_or(("", ""));
match kind {
"t" => match state.library.track(id) {
Some(t) => stream(Path::new(&t.path), range),
None => respond(404, "text/plain", b"unknown track".to_vec(), &[]),
},
"a" => match state.library.art_path(id) {
Some(p) => {
let data = std::fs::read(&p).unwrap_or_default();
respond(200, "image/jpeg", data, &[("Cache-Control", "max-age=86400".into())])
}
None => respond(404, "text/plain", Vec::new(), &[]),
},
_ => respond(400, "text/plain", Vec::new(), &[]),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_byte_ranges() {
assert_eq!(range_of(Some("bytes=0-"), 10_000_000), Some((0, MAX_CHUNK - 1)));
assert_eq!(range_of(Some("bytes=100-199"), 1000), Some((100, 199)));
assert_eq!(range_of(Some("bytes=-100"), 1000), Some((900, 999)));
assert_eq!(range_of(Some("bytes=5000-"), 1000), None);
assert_eq!(range_of(None, 1000), None);
}
}
+701
View File
@@ -0,0 +1,701 @@
// atmosphere · library.rs · Local music library: folder scanning, tags, artwork cache, folder-based playlists, play stats and artist profiles.
use crate::downloader::sanitize;
use crate::engine::data_dir;
use anyhow::{anyhow, bail, Context, Result};
use lofty::file::{AudioFile, TaggedFileExt};
use lofty::tag::{Accessor, ItemKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use std::time::{SystemTime, UNIX_EPOCH};
pub const AUDIO_EXT: [&str; 9] = ["mp3", "m4a", "flac", "ogg", "opus", "wav", "aac", "aiff", "aif"];
const ORDER_FILE: &str = "playlist.m3u8";
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Track {
pub id: String,
pub path: String,
pub title: String,
pub artist: String,
pub album: String,
pub album_artist: String,
pub track_no: Option<u32>,
pub track_total: Option<u32>,
pub disc_no: Option<u32>,
pub year: Option<u32>,
pub genre: String,
pub duration_ms: u64,
pub bitrate: Option<u32>,
pub format: String,
pub size: u64,
pub mtime: u64,
pub art: Option<String>,
pub playlist: Option<String>,
pub has_lyrics: bool,
pub added: u64,
}
#[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
struct Stats {
plays: HashMap<String, u32>,
last_played: HashMap<String, u64>,
liked: HashSet<String>,
listens: Vec<Listen>,
app_time: std::collections::BTreeMap<String, u64>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Listen {
pub id: String,
pub at: u64,
pub ms: u64,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsData {
pub listens: Vec<Listen>,
pub app_time: std::collections::BTreeMap<String, u64>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ArtistMeta {
pub name: String,
pub image: Option<String>,
pub bio: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Playlist {
pub name: String,
pub path: String,
pub order: Vec<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
pub tracks: Vec<Track>,
pub playlists: Vec<Playlist>,
pub plays: HashMap<String, u32>,
pub last_played: HashMap<String, u64>,
pub liked: Vec<String>,
pub artists: HashMap<String, ArtistMeta>,
pub scanning: bool,
pub hidden: usize,
}
pub struct Library {
tracks: RwLock<HashMap<String, Track>>,
stats: RwLock<Stats>,
artists: RwLock<HashMap<String, ArtistMeta>>,
hidden: RwLock<HashSet<String>>,
scanning: AtomicBool,
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}
pub fn hash(s: &str) -> String {
Sha256::digest(s.as_bytes()).iter().take(10).map(|b| format!("{b:02x}")).collect()
}
pub fn artist_key(name: &str) -> String {
hash(&name.trim().to_lowercase())
}
fn art_dir() -> PathBuf {
data_dir().join("art")
}
fn load<T: for<'de> Deserialize<'de> + Default>(name: &str) -> T {
std::fs::read(data_dir().join(name)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
fn store<T: Serialize>(name: &str, value: &T) {
let path = data_dir().join(name);
let _ = std::fs::create_dir_all(data_dir());
if let Ok(data) = serde_json::to_vec(value) {
let tmp = path.with_extension("tmp");
if std::fs::write(&tmp, data).is_ok() {
let _ = std::fs::rename(&tmp, &path);
}
}
}
pub fn is_audio(p: &Path) -> bool {
p.extension().and_then(|e| e.to_str()).is_some_and(|e| AUDIO_EXT.contains(&e.to_ascii_lowercase().as_str()))
}
fn file_stamp(p: &Path) -> Option<(u64, u64)> {
let m = std::fs::metadata(p).ok()?;
let mtime = m.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_secs();
Some((m.len(), mtime))
}
fn save_art(key: &str, data: &[u8]) -> Option<String> {
let dir = art_dir();
let out = dir.join(format!("{key}.jpg"));
if out.exists() {
return Some(key.to_string());
}
std::fs::create_dir_all(&dir).ok()?;
let img = image::load_from_memory(data).ok()?;
let rgb = img.thumbnail(600, 600).to_rgb8();
let mut buf = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, 86).encode_image(&rgb).ok()?;
std::fs::write(&out, buf).ok()?;
Some(key.to_string())
}
fn year_of(s: &str) -> Option<u32> {
let digits: String = s.chars().skip_while(|c| !c.is_ascii_digit()).take(4).collect();
digits.parse().ok().filter(|y| (1000..3000).contains(y))
}
pub fn read_track(path: &Path, playlist: Option<String>) -> Result<Track> {
let (size, mtime) = file_stamp(path).ok_or_else(|| anyhow!("unreadable"))?;
let file = lofty::read_from_path(path)?;
let props = file.properties();
let tag = file.primary_tag().or_else(|| file.first_tag());
let get = |f: &dyn Fn(&lofty::tag::Tag) -> Option<String>| tag.and_then(f).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled").to_string();
let title = get(&|t| t.title().map(|c| c.into_owned())).unwrap_or(stem);
let artist = get(&|t| t.artist().map(|c| c.into_owned())).unwrap_or_default();
let album = get(&|t| t.album().map(|c| c.into_owned())).unwrap_or_default();
let album_artist = get(&|t| t.get_string(ItemKey::AlbumArtist).map(String::from)).unwrap_or_default();
let year = get(&|t| t.get_string(ItemKey::Year).or_else(|| t.get_string(ItemKey::RecordingDate)).or_else(|| t.get_string(ItemKey::ReleaseDate)).map(String::from)).and_then(|y| year_of(&y));
let lyrics_tag = tag.and_then(|t| t.get_string(ItemKey::Lyrics)).is_some_and(|l| !l.trim().is_empty());
let group = format!("{}|{}", if album_artist.is_empty() { &artist } else { &album_artist }, album).to_lowercase();
let art_key = if album.is_empty() { hash(&path.to_string_lossy()) } else { hash(&group) };
let art = tag.and_then(|t| t.pictures().first()).and_then(|p| save_art(&art_key, p.data()));
let path_s = path.to_string_lossy().into_owned();
Ok(Track {
id: hash(&path_s),
title,
artist,
album,
album_artist,
track_no: tag.and_then(|t| t.track()),
track_total: tag.and_then(|t| t.track_total()),
disc_no: tag.and_then(|t| t.disk()),
year,
genre: get(&|t| t.genre().map(|c| c.into_owned())).unwrap_or_default(),
duration_ms: props.duration().as_millis() as u64,
bitrate: props.audio_bitrate(),
format: path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase(),
size,
mtime,
art,
playlist,
has_lyrics: lyrics_tag || path.with_extension("lrc").exists(),
added: now(),
path: path_s,
})
}
fn playlist_of(path: &Path, playlists_dir: &Path) -> Option<String> {
let rel = path.strip_prefix(playlists_dir).ok()?;
let mut parts = rel.components();
let first = parts.next()?.as_os_str().to_string_lossy().into_owned();
parts.next().map(|_| first)
}
fn read_order(dir: &Path) -> Vec<String> {
std::fs::read_to_string(dir.join(ORDER_FILE))
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(String::from).collect())
.unwrap_or_default()
}
fn write_order(dir: &Path, names: &[String]) -> Result<()> {
let mut body = String::from("#EXTM3U\n");
for n in names {
body.push_str(n);
body.push('\n');
}
std::fs::write(dir.join(ORDER_FILE), body)?;
Ok(())
}
impl Library {
pub fn load() -> Self {
let cached: Vec<Track> = load("library.json");
Self {
tracks: RwLock::new(cached.into_iter().map(|t| (t.id.clone(), t)).collect()),
stats: RwLock::new(load("stats.json")),
artists: RwLock::new(load("artists.json")),
hidden: RwLock::new(load("hidden.json")),
scanning: AtomicBool::new(false),
}
}
fn persist(&self) {
let list: Vec<Track> = self.tracks.read().unwrap().values().cloned().collect();
store("library.json", &list);
}
pub fn track(&self, id: &str) -> Option<Track> {
self.tracks.read().unwrap().get(id).cloned()
}
pub fn art_path(&self, key: &str) -> Option<PathBuf> {
let safe: String = key.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
let p = art_dir().join(format!("{safe}.jpg"));
p.exists().then_some(p)
}
pub fn scan(&self, roots: &[PathBuf], playlists_dir: &Path, mut progress: impl FnMut(usize, usize)) -> Result<usize> {
if self.scanning.swap(true, Ordering::SeqCst) {
bail!("A scan is already running.");
}
let result = self.scan_files(roots, playlists_dir, &mut progress);
self.scanning.store(false, Ordering::SeqCst);
result
}
fn scan_files(&self, roots: &[PathBuf], playlists_dir: &Path, progress: &mut impl FnMut(usize, usize)) -> Result<usize> {
{
let old: HashMap<String, Track> = self.tracks.read().unwrap().values().map(|t| (t.path.clone(), t.clone())).collect();
let mut files: Vec<PathBuf> = Vec::new();
let mut seen = HashSet::new();
let mut all_roots: Vec<PathBuf> = roots.to_vec();
all_roots.push(playlists_dir.to_path_buf());
for root in all_roots.iter().filter(|r| r.is_dir()) {
for entry in walkdir::WalkDir::new(root).follow_links(false).into_iter().filter_entry(|e| !e.file_name().to_string_lossy().starts_with('.')).flatten() {
let p = entry.path();
if entry.file_type().is_file() && is_audio(p) && seen.insert(p.to_path_buf()) {
files.push(p.to_path_buf());
}
}
}
let hidden = self.hidden.read().unwrap().clone();
files.retain(|p| !hidden.contains(&*p.to_string_lossy()));
let total = files.len();
let mut next: HashMap<String, Track> = HashMap::with_capacity(total);
for (i, p) in files.iter().enumerate() {
let playlist = playlist_of(p, playlists_dir);
let key = p.to_string_lossy().into_owned();
let reuse = old.get(&key).filter(|t| file_stamp(p) == Some((t.size, t.mtime))).cloned();
let track = match reuse {
Some(mut t) => {
t.playlist = playlist;
Some(t)
}
None => read_track(p, playlist).ok(),
};
if let Some(t) = track {
next.insert(t.id.clone(), t);
}
if i % 25 == 0 || i + 1 == total {
progress(i + 1, total);
}
}
let count = next.len();
*self.tracks.write().unwrap() = next;
self.persist();
Ok(count)
}
}
pub fn add_file(&self, path: &Path, playlists_dir: &Path) -> Result<Track> {
if self.hidden.read().unwrap().contains(&*path.to_string_lossy()) {
bail!("hidden");
}
let t = read_track(path, playlist_of(path, playlists_dir))?;
self.tracks.write().unwrap().insert(t.id.clone(), t.clone());
self.persist();
Ok(t)
}
pub fn snapshot(&self, playlists_dir: &Path) -> Snapshot {
let tracks: Vec<Track> = self.tracks.read().unwrap().values().cloned().collect();
let stats = self.stats.read().unwrap();
Snapshot {
playlists: self.playlists(playlists_dir, &tracks),
tracks,
plays: stats.plays.clone(),
last_played: stats.last_played.clone(),
liked: stats.liked.iter().cloned().collect(),
artists: self.artists.read().unwrap().clone(),
scanning: self.scanning.load(Ordering::SeqCst),
hidden: self.hidden.read().unwrap().len(),
}
}
fn playlists(&self, dir: &Path, tracks: &[Track]) -> Vec<Playlist> {
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
let mut out = Vec::new();
for entry in rd.flatten().filter(|e| e.path().is_dir()) {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let folder = entry.path();
let mut members: Vec<&Track> = tracks.iter().filter(|t| t.playlist.as_deref() == Some(name.as_str())).collect();
let order = read_order(&folder);
let file_name = |t: &Track| Path::new(&t.path).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
members.sort_by_key(|t| (order.iter().position(|o| *o == file_name(t)).unwrap_or(usize::MAX), file_name(t).to_lowercase()));
out.push(Playlist { name, path: folder.to_string_lossy().into_owned(), order: members.iter().map(|t| t.id.clone()).collect() });
}
out.sort_by_key(|p| p.name.to_lowercase());
out
}
pub fn playlist_create(&self, dir: &Path, name: &str) -> Result<String> {
let clean = sanitize(name.trim());
let folder = dir.join(&clean);
if folder.exists() {
bail!("A playlist called “{clean}” already exists.");
}
std::fs::create_dir_all(&folder).context("Couldn't create the playlist folder")?;
write_order(&folder, &[])?;
Ok(clean)
}
pub fn playlist_rename(&self, dir: &Path, from: &str, to: &str) -> Result<String> {
let clean = sanitize(to.trim());
let (a, b) = (dir.join(from), dir.join(&clean));
if b.exists() {
bail!("A playlist called “{clean}” already exists.");
}
std::fs::rename(&a, &b).context("Couldn't rename the playlist folder")?;
let moved: Vec<Track> = self.tracks.read().unwrap().values().filter(|t| t.playlist.as_deref() == Some(from)).cloned().collect();
let mut tracks = self.tracks.write().unwrap();
for t in moved {
tracks.remove(&t.id);
let new_path = b.join(Path::new(&t.path).file_name().unwrap_or_default());
let mut nt = t.clone();
nt.path = new_path.to_string_lossy().into_owned();
nt.id = hash(&nt.path);
nt.playlist = Some(clean.clone());
tracks.insert(nt.id.clone(), nt);
}
drop(tracks);
self.persist();
Ok(clean)
}
pub fn playlist_delete(&self, dir: &Path, name: &str) -> Result<()> {
trash::delete(dir.join(name)).map_err(|e| anyhow!("Couldn't move the playlist to the trash ({e})"))?;
self.tracks.write().unwrap().retain(|_, t| t.playlist.as_deref() != Some(name));
self.persist();
Ok(())
}
pub fn playlist_add(&self, dir: &Path, name: &str, sources: &[PathBuf], link: bool) -> Result<usize> {
let folder = dir.join(name);
std::fs::create_dir_all(&folder)?;
let mut order = read_order(&folder);
let mut added = 0;
for src in sources {
let Some(file) = src.file_name() else { continue };
let dest = folder.join(file);
let fname = file.to_string_lossy().into_owned();
if !dest.exists() {
let linked = link && std::fs::hard_link(src, &dest).is_ok();
if !linked {
std::fs::copy(src, &dest).with_context(|| format!("Couldn't add {fname}"))?;
}
if let Some(lrc) = Some(src.with_extension("lrc")).filter(|l| l.exists()) {
let _ = std::fs::copy(&lrc, dest.with_extension("lrc"));
}
added += 1;
}
if !order.contains(&fname) {
order.push(fname);
}
if let Ok(t) = read_track(&dest, Some(name.to_string())) {
self.tracks.write().unwrap().insert(t.id.clone(), t);
}
}
write_order(&folder, &order)?;
self.persist();
Ok(added)
}
pub fn playlist_remove(&self, dir: &Path, name: &str, ids: &[String]) -> Result<()> {
let folder = dir.join(name);
let mut order = read_order(&folder);
for id in ids {
let Some(t) = self.track(id).filter(|t| t.playlist.as_deref() == Some(name)) else { continue };
let p = PathBuf::from(&t.path);
trash::delete(&p).map_err(|e| anyhow!("Couldn't move the file to the trash ({e})"))?;
let lrc = p.with_extension("lrc");
if lrc.exists() {
let _ = trash::delete(&lrc);
}
let fname = p.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
order.retain(|o| *o != fname);
self.tracks.write().unwrap().remove(id);
}
write_order(&folder, &order)?;
self.persist();
Ok(())
}
pub fn playlist_reorder(&self, dir: &Path, name: &str, ids: &[String]) -> Result<()> {
let names: Vec<String> = ids
.iter()
.filter_map(|id| self.track(id))
.filter_map(|t| Path::new(&t.path).file_name().map(|f| f.to_string_lossy().into_owned()))
.collect();
write_order(&dir.join(name), &names)
}
pub fn remove_under(&self, path: &Path) -> usize {
let mut tracks = self.tracks.write().unwrap();
let before = tracks.len();
tracks.retain(|_, t| {
let p = Path::new(&t.path);
p != path && !p.starts_with(path)
});
let n = before - tracks.len();
drop(tracks);
if n > 0 {
self.persist();
}
n
}
pub fn knows(&self, path: &Path) -> bool {
let stamp = file_stamp(path);
self.tracks.read().unwrap().values().any(|t| Path::new(&t.path) == path && stamp == Some((t.size, t.mtime)))
}
pub fn hide(&self, ids: &[String]) -> usize {
let mut hidden = self.hidden.write().unwrap();
let mut tracks = self.tracks.write().unwrap();
let mut n = 0;
for id in ids {
if let Some(t) = tracks.remove(id) {
hidden.insert(t.path);
n += 1;
}
}
store("hidden.json", &*hidden);
drop(tracks);
self.persist();
n
}
pub fn unhide_all(&self) -> usize {
let mut hidden = self.hidden.write().unwrap();
let n = hidden.len();
hidden.clear();
store("hidden.json", &*hidden);
n
}
fn same_song(a: &Track, b: &Track) -> bool {
let n = |s: &str| s.trim().to_lowercase();
n(&a.title) == n(&b.title) && n(&a.artist) == n(&b.artist) && a.duration_ms.abs_diff(b.duration_ms) < 2000
}
pub fn delete(&self, ids: &[String], playlists_dir: &Path, also_playlists: bool) -> Result<usize> {
let targets: Vec<Track> = ids.iter().filter_map(|id| self.track(id)).collect();
let mut doomed: Vec<Track> = targets.clone();
if also_playlists {
let all: Vec<Track> = self.tracks.read().unwrap().values().cloned().collect();
for t in targets.iter().filter(|t| t.playlist.is_none()) {
doomed.extend(all.iter().filter(|p| p.playlist.is_some() && p.id != t.id && Self::same_song(t, p)).cloned());
}
}
doomed.sort_by(|a, b| a.id.cmp(&b.id));
doomed.dedup_by(|a, b| a.id == b.id);
let mut deleted = 0;
let mut failures = Vec::new();
for t in &doomed {
let p = PathBuf::from(&t.path);
if p.exists() {
if let Err(e) = trash::delete(&p) {
failures.push(format!("{} ({e})", t.title));
continue;
}
}
let lrc = p.with_extension("lrc");
if lrc.exists() {
let _ = trash::delete(&lrc);
}
if let Some(name) = &t.playlist {
let folder = playlists_dir.join(name);
let fname = p.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
let mut order = read_order(&folder);
order.retain(|o| *o != fname);
let _ = write_order(&folder, &order);
}
self.tracks.write().unwrap().remove(&t.id);
if t.playlist.is_none() {
deleted += 1;
}
}
{
let mut s = self.stats.write().unwrap();
for t in &doomed {
s.plays.remove(&t.id);
s.last_played.remove(&t.id);
s.liked.remove(&t.id);
}
let gone: HashSet<&str> = doomed.iter().map(|t| t.id.as_str()).collect();
s.listens.retain(|l| !gone.contains(l.id.as_str()));
store("stats.json", &*s);
}
self.persist();
if !failures.is_empty() {
bail!("Couldn't move to the trash: {}", failures.join(", "));
}
Ok(deleted.max(targets.iter().filter(|t| t.playlist.is_some()).count()))
}
pub fn listened(&self, id: &str, ms: u64) {
if ms < 1000 || self.track(id).is_none() {
return;
}
let mut s = self.stats.write().unwrap();
s.listens.push(Listen { id: id.to_string(), at: now(), ms: ms.min(6 * 3600 * 1000) });
store("stats.json", &*s);
}
pub fn app_seconds(&self, day: &str, secs: u64) {
if day.len() != 10 || secs == 0 {
return;
}
let mut s = self.stats.write().unwrap();
*s.app_time.entry(day.to_string()).or_default() += secs.min(600);
store("stats.json", &*s);
}
pub fn stats(&self) -> StatsData {
let tracks = self.tracks.read().unwrap();
let s = self.stats.read().unwrap();
StatsData { listens: s.listens.iter().filter(|l| tracks.contains_key(&l.id)).cloned().collect(), app_time: s.app_time.clone() }
}
pub fn played(&self, id: &str) {
let mut s = self.stats.write().unwrap();
*s.plays.entry(id.to_string()).or_default() += 1;
s.last_played.insert(id.to_string(), now());
store("stats.json", &*s);
}
pub fn like(&self, id: &str, liked: bool) {
let mut s = self.stats.write().unwrap();
if liked {
s.liked.insert(id.to_string());
} else {
s.liked.remove(id);
}
store("stats.json", &*s);
}
pub fn set_artist(&self, name: &str, image: Option<&Path>, bio: Option<String>) -> Result<ArtistMeta> {
let key = artist_key(name);
let mut artists = self.artists.write().unwrap();
let meta = artists.entry(key.clone()).or_default();
meta.name = name.trim().to_string();
if let Some(src) = image {
let data = std::fs::read(src).context("Couldn't read that image")?;
let id = format!("artist{key}");
let _ = std::fs::remove_file(art_dir().join(format!("{id}.jpg")));
meta.image = Some(save_art(&id, &data).ok_or_else(|| anyhow!("That image couldn't be read"))?);
}
if let Some(b) = bio {
meta.bio = b;
}
let out = meta.clone();
store("artists.json", &*artists);
Ok(out)
}
pub fn refresh(&self, id: &str, playlists_dir: &Path) -> Result<Track> {
let t = self.track(id).ok_or_else(|| anyhow!("That track is no longer in the library"))?;
let _ = std::fs::remove_file(art_dir().join(format!("{}.jpg", t.art.clone().unwrap_or_default())));
self.tracks.write().unwrap().remove(id);
self.add_file(Path::new(&t.path), playlists_dir)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_playlist_membership() {
let root = Path::new("/music/Playlists");
assert_eq!(playlist_of(Path::new("/music/Playlists/Gym/a.mp3"), root), Some("Gym".into()));
assert_eq!(playlist_of(Path::new("/music/Playlists/a.mp3"), root), None);
assert_eq!(playlist_of(Path::new("/music/Other/a.mp3"), root), None);
}
#[test]
fn parses_years_and_extensions() {
assert_eq!(year_of("2019-04-12"), Some(2019));
assert_eq!(year_of("Released 1998"), Some(1998));
assert_eq!(year_of("n/a"), None);
assert!(is_audio(Path::new("x/Song.FLAC")));
assert!(!is_audio(Path::new("x/cover.jpg")));
}
fn wav(path: &Path, seconds: u32) {
let rate = 8000u32;
let n = rate * seconds;
let mut d = Vec::new();
d.extend(b"RIFF");
d.extend((36 + n * 2).to_le_bytes());
d.extend(b"WAVEfmt ");
d.extend(16u32.to_le_bytes());
d.extend(1u16.to_le_bytes());
d.extend(1u16.to_le_bytes());
d.extend(rate.to_le_bytes());
d.extend((rate * 2).to_le_bytes());
d.extend(2u16.to_le_bytes());
d.extend(16u16.to_le_bytes());
d.extend(b"data");
d.extend((n * 2).to_le_bytes());
d.extend(std::iter::repeat_n(0u8, (n * 2) as usize));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, d).unwrap();
}
#[test]
fn hide_restore_and_folder_removal() {
let root = std::env::temp_dir().join(format!("atmo-lib-{}", now()));
std::env::set_var("ATMOSPHERE_DATA_DIR", root.join("data"));
let music = root.join("music");
let lists = music.join("Playlists");
wav(&music.join("Album A").join("one.wav"), 2);
wav(&music.join("Album A").join("two.wav"), 3);
wav(&lists.join("Gym").join("one.wav"), 2);
let lib = Library::load();
assert_eq!(lib.scan(std::slice::from_ref(&music), &lists, |_, _| {}).unwrap(), 3);
let snap = lib.snapshot(&lists);
assert_eq!(snap.playlists.len(), 1);
assert_eq!(snap.playlists[0].order.len(), 1);
let one = snap.tracks.iter().find(|t| t.path.ends_with("one.wav") && t.playlist.is_none()).unwrap().id.clone();
assert_eq!(lib.hide(std::slice::from_ref(&one)), 1);
assert_eq!(lib.scan(std::slice::from_ref(&music), &lists, |_, _| {}).unwrap(), 2);
assert_eq!(lib.snapshot(&lists).hidden, 1);
assert_eq!(lib.unhide_all(), 1);
assert_eq!(lib.scan(std::slice::from_ref(&music), &lists, |_, _| {}).unwrap(), 3);
assert_eq!(lib.remove_under(&music.join("Album A")), 2);
assert_eq!(lib.snapshot(&lists).tracks.len(), 1);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn playlist_order_roundtrip() {
let dir = std::env::temp_dir().join(format!("atmo-test-{}", now()));
std::fs::create_dir_all(&dir).unwrap();
write_order(&dir, &["b.mp3".into(), "a.mp3".into()]).unwrap();
assert_eq!(read_order(&dir), vec!["b.mp3".to_string(), "a.mp3".to_string()]);
let _ = std::fs::remove_dir_all(&dir);
}
}
+590
View File
@@ -0,0 +1,590 @@
// atmosphere · lyrics.rs · Lyrics lookup across providers (local, LRCLIB, Musixmatch, NetEase, Kugou, custom) with LRC parsing and caching.
use crate::engine::data_dir;
use crate::library::hash;
use crate::settings::Settings;
use anyhow::{anyhow, Result};
use base64::Engine as _;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::Path;
use std::sync::LazyLock;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const CACHE_DAYS: u64 = 14;
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Query {
pub title: String,
pub artist: String,
pub album: String,
pub duration_ms: Option<u64>,
pub path: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Word {
pub t: u64,
pub d: u64,
pub text: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Line {
pub t: Option<u64>,
pub text: String,
pub words: Vec<Word>,
pub translation: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Lyrics {
pub provider: String,
pub synced: bool,
pub word_synced: bool,
pub lines: Vec<Line>,
pub copyright: Option<String>,
pub instrumental: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Attempt {
pub provider: String,
pub outcome: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Found {
pub lyrics: Option<Lyrics>,
pub tried: Vec<Attempt>,
pub cached: bool,
}
static JUNK: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)\s*[\(\[][^)\]]*\b(official|video|audio|lyrics?|visuali[sz]er|music video|mv|m/v|hd|hq|4k|explicit|clean|full song)\b[^)\]]*[\)\]]").unwrap()
});
static TAIL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\s*[||/]\s*.*$|\s+(official|lyrics?)\s*(video|audio)?\s*$").unwrap());
pub fn clean(q: &Query) -> Query {
let mut title = JUNK.replace_all(q.title.trim(), "").to_string();
title = TAIL.replace_all(&title, "").trim().to_string();
let mut artist = q.artist.trim().trim_end_matches(" - Topic").to_string();
if let Some((a, t)) = title.split_once(" - ").map(|(a, t)| (a.trim().to_string(), t.trim().to_string())) {
let lower_a = a.to_lowercase();
let related = artist.is_empty() || lower_a.contains(&artist.to_lowercase()) || artist.to_lowercase().contains(&lower_a);
if related && !a.is_empty() && !t.is_empty() {
artist = a;
title = t;
}
}
Query { title: if title.is_empty() { q.title.clone() } else { title }, artist, ..q.clone() }
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ProviderCfg {
pub id: String,
pub enabled: bool,
}
impl Default for ProviderCfg {
fn default() -> Self {
Self { id: String::new(), enabled: true }
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct CustomProvider {
pub id: String,
pub name: String,
pub url: String,
pub headers: String,
pub format: String,
pub json_path: String,
pub key: String,
}
pub fn default_providers() -> Vec<ProviderCfg> {
[("local", true), ("lrclib", true), ("netease", true), ("musixmatch", false), ("kugou", false)]
.into_iter()
.map(|(id, enabled)| ProviderCfg { id: id.into(), enabled })
.collect()
}
static TIME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?\]").unwrap());
static WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?>([^<]*)").unwrap());
static OFFSET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?mi)^\[offset:\s*([+-]?\d+)\]").unwrap());
static YRC_LINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[(\d+),(\d+)\](.*)$").unwrap());
static YRC_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\((\d+),(\d+),\d+\)([^(]*)").unwrap());
fn ms(m: &str, s: &str, frac: Option<&str>) -> u64 {
let f = frac.map(|f| match f.len() {
1 => f.parse::<u64>().unwrap_or(0) * 100,
2 => f.parse::<u64>().unwrap_or(0) * 10,
_ => f[..3].parse::<u64>().unwrap_or(0),
});
m.parse::<u64>().unwrap_or(0) * 60_000 + s.parse::<u64>().unwrap_or(0) * 1000 + f.unwrap_or(0)
}
pub fn parse_lrc(text: &str) -> Vec<Line> {
let offset: i64 = OFFSET.captures(text).and_then(|c| c[1].parse().ok()).unwrap_or(0);
let shift = |t: u64| (t as i64 - offset).max(0) as u64;
let mut lines = Vec::new();
let mut plain = Vec::new();
for raw in text.lines() {
let stamps: Vec<u64> = TIME.captures_iter(raw).map(|c| shift(ms(&c[1], &c[2], c.get(3).map(|m| m.as_str())))).collect();
let body = TIME.replace_all(raw, "").trim().to_string();
if stamps.is_empty() {
if !raw.trim().is_empty() && !raw.trim_start().starts_with('[') {
plain.push(Line { t: None, text: raw.trim().to_string(), ..Default::default() });
}
continue;
}
let mut words: Vec<Word> = WORD
.captures_iter(&body)
.map(|c| Word { t: shift(ms(&c[1], &c[2], c.get(3).map(|m| m.as_str()))), d: 0, text: c[4].to_string() })
.filter(|w| !w.text.is_empty())
.collect();
for i in 0..words.len() {
let next = words.get(i + 1).map(|n| n.t);
if let Some(n) = next {
words[i].d = n.saturating_sub(words[i].t);
}
}
let text = if words.is_empty() { body } else { words.iter().map(|w| w.text.as_str()).collect::<String>().trim().to_string() };
for t in stamps {
lines.push(Line { t: Some(t), text: text.clone(), words: words.clone(), translation: None });
}
}
if lines.is_empty() {
return plain;
}
lines.sort_by_key(|l| l.t);
lines
}
pub fn parse_yrc(text: &str) -> Vec<Line> {
text.lines()
.filter_map(|l| {
let c = YRC_LINE.captures(l.trim())?;
let words: Vec<Word> = YRC_WORD.captures_iter(&c[3]).map(|w| Word { t: w[1].parse().unwrap_or(0), d: w[2].parse().unwrap_or(0), text: w[3].to_string() }).collect();
let text = words.iter().map(|w| w.text.as_str()).collect::<String>().trim().to_string();
(!text.is_empty()).then(|| Line { t: c[1].parse().ok(), text, words, translation: None })
})
.collect()
}
fn build(provider: &str, lines: Vec<Line>, copyright: Option<String>) -> Option<Lyrics> {
let lines: Vec<Line> = lines.into_iter().filter(|l| !l.text.trim().is_empty() || l.t.is_some()).collect();
if lines.iter().all(|l| l.text.trim().is_empty()) {
return None;
}
let synced = lines.iter().any(|l| l.t.is_some());
let word_synced = lines.iter().any(|l| l.words.len() > 1);
Some(Lyrics { provider: provider.into(), synced, word_synced, lines, copyright, instrumental: false })
}
fn norm(s: &str) -> String {
static PAREN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\s*[\(\[][^)\]]*(feat|ft\.|remaster|version|edit|live|mix)[^)\]]*[\)\]]").unwrap());
PAREN.replace_all(s, "").to_lowercase().chars().filter(|c| c.is_alphanumeric() || c.is_whitespace()).collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")
}
fn score(q: &Query, title: &str, artist: &str, duration_ms: Option<u64>) -> i64 {
let (qt, qa, t, a) = (norm(&q.title), norm(&q.artist), norm(title), norm(artist));
let mut s = 0;
if t == qt {
s += 50;
} else if t.contains(&qt) || qt.contains(&t) {
s += 25;
} else {
return -100;
}
if !qa.is_empty() && (a.contains(&qa) || qa.contains(&a) || qa.split(' ').any(|w| w.len() > 2 && a.contains(w))) {
s += 30;
}
if let (Some(x), Some(y)) = (q.duration_ms, duration_ms) {
let diff = (x as i64 - y as i64).abs();
if diff > 8000 {
return -100;
}
s += 20 - (diff / 500).min(20);
}
s
}
fn local(q: &Query) -> Option<Lyrics> {
let path = Path::new(q.path.as_deref()?);
if let Ok(text) = std::fs::read_to_string(path.with_extension("lrc")) {
if let Some(l) = build("Local .lrc", parse_lrc(&text), None) {
return Some(l);
}
}
let file = lofty::read_from_path(path).ok()?;
use lofty::file::TaggedFileExt;
let tag = file.primary_tag().or_else(|| file.first_tag())?;
let text = tag.get_string(lofty::tag::ItemKey::Lyrics)?;
build("Embedded", parse_lrc(text), None)
}
async fn get_json(http: &reqwest::Client, url: &str, headers: &[(String, String)]) -> Result<Value> {
let mut req = http.get(url).timeout(Duration::from_secs(10));
for (k, v) in headers {
req = req.header(k.as_str(), v.as_str());
}
let resp = req.send().await?;
if resp.status().as_u16() == 404 {
return Ok(Value::Null);
}
Ok(resp.error_for_status()?.json().await?)
}
fn enc(s: &str) -> String {
url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}
async fn lrclib(http: &reqwest::Client, q: &Query) -> Result<Option<Lyrics>> {
let from = |v: &Value| -> Option<Lyrics> {
if v["instrumental"].as_bool() == Some(true) {
return Some(Lyrics { provider: "LRCLIB".into(), instrumental: true, ..Default::default() });
}
v["syncedLyrics"].as_str().and_then(|s| build("LRCLIB", parse_lrc(s), None)).or_else(|| v["plainLyrics"].as_str().and_then(|s| build("LRCLIB", parse_lrc(s), None)))
};
let mut url = format!("https://lrclib.net/api/get?track_name={}&artist_name={}", enc(&q.title), enc(&q.artist));
if !q.album.is_empty() {
url.push_str(&format!("&album_name={}", enc(&q.album)));
}
if let Some(d) = q.duration_ms {
url.push_str(&format!("&duration={}", d / 1000));
}
let v = get_json(http, &url, &[]).await?;
if let Some(l) = from(&v) {
return Ok(Some(l));
}
let mut list = get_json(http, &format!("https://lrclib.net/api/search?track_name={}&artist_name={}", enc(&q.title), enc(&q.artist)), &[]).await?;
if list.as_array().is_none_or(|a| a.is_empty()) {
list = get_json(http, &format!("https://lrclib.net/api/search?q={}", enc(&format!("{} {}", q.artist, q.title))), &[]).await?;
}
let best = list.as_array().and_then(|a| {
a.iter()
.map(|v| (score(q, v["trackName"].as_str().unwrap_or(""), v["artistName"].as_str().unwrap_or(""), v["duration"].as_f64().map(|d| (d * 1000.0) as u64)), v))
.filter(|(s, _)| *s >= 40)
.max_by_key(|(s, v)| (*s, v["syncedLyrics"].is_string() as i64))
.map(|(_, v)| v.clone())
});
Ok(best.as_ref().and_then(from))
}
async fn musixmatch(http: &reqwest::Client, q: &Query, key: &str) -> Result<Option<Lyrics>> {
if key.trim().is_empty() {
return Ok(None);
}
let base = "https://api.musixmatch.com/ws/1.1";
let common = format!("q_track={}&q_artist={}&apikey={}", enc(&q.title), enc(&q.artist), enc(key.trim()));
let mut sub = format!("{base}/matcher.subtitle.get?{common}");
if let Some(d) = q.duration_ms {
sub.push_str(&format!("&f_subtitle_length={}&f_subtitle_length_max_deviation=5", d / 1000));
}
let v = get_json(http, &sub, &[]).await?;
if v["message"]["header"]["status_code"].as_u64() == Some(401) {
return Err(anyhow!("Musixmatch rejected the API key"));
}
let body = &v["message"]["body"]["subtitle"];
if let Some(text) = body["subtitle_body"].as_str() {
if let Some(l) = build("Musixmatch", parse_lrc(text), body["lyrics_copyright"].as_str().map(String::from)) {
return Ok(Some(l));
}
}
let v = get_json(http, &format!("{base}/matcher.lyrics.get?{common}"), &[]).await?;
let body = &v["message"]["body"]["lyrics"];
if body["instrumental"].as_u64() == Some(1) {
return Ok(Some(Lyrics { provider: "Musixmatch".into(), instrumental: true, ..Default::default() }));
}
let text = body["lyrics_body"].as_str().unwrap_or("");
let cleaned: String = text.lines().take_while(|l| !l.contains("*******")).collect::<Vec<_>>().join("\n");
Ok(build("Musixmatch", parse_lrc(&cleaned), body["lyrics_copyright"].as_str().map(String::from)))
}
async fn netease(http: &reqwest::Client, q: &Query) -> Result<Option<Lyrics>> {
let search = get_json(http, &format!("https://music.163.com/api/search/get?s={}&type=1&limit=8", enc(&format!("{} {}", q.artist, q.title))), &[]).await?;
let best = search["result"]["songs"].as_array().and_then(|songs| {
songs
.iter()
.map(|s| {
let artist = s["artists"].as_array().map(|a| a.iter().filter_map(|x| x["name"].as_str()).collect::<Vec<_>>().join(" ")).unwrap_or_default();
(score(q, s["name"].as_str().unwrap_or(""), &artist, s["duration"].as_u64()), s["id"].as_u64())
})
.filter(|(sc, _)| *sc >= 45)
.max_by_key(|(sc, _)| *sc)
.and_then(|(_, id)| id)
});
let Some(id) = best else { return Ok(None) };
let v = get_json(http, &format!("https://music.163.com/api/song/lyric?id={id}&lv=1&tv=-1&yv=1"), &[]).await?;
let mut lines = v["yrc"]["lyric"].as_str().map(parse_yrc).filter(|l| !l.is_empty()).unwrap_or_else(|| v["lrc"]["lyric"].as_str().map(parse_lrc).unwrap_or_default());
if let Some(tr) = v["tlyric"]["lyric"].as_str().map(parse_lrc) {
for line in lines.iter_mut() {
if let Some(t) = line.t {
line.translation = tr.iter().find(|x| x.t.is_some_and(|xt| xt.abs_diff(t) < 600)).map(|x| x.text.clone()).filter(|s| !s.is_empty());
}
}
}
Ok(build("NetEase Cloud Music", lines, None))
}
async fn kugou(http: &reqwest::Client, q: &Query) -> Result<Option<Lyrics>> {
let mut url = format!("https://lyrics.kugou.com/search?ver=1&man=yes&client=pc&keyword={}", enc(&format!("{} - {}", q.artist, q.title)));
if let Some(d) = q.duration_ms {
url.push_str(&format!("&duration={d}"));
}
let v = get_json(http, &url, &[]).await?;
let best = v["candidates"].as_array().and_then(|c| {
c.iter()
.map(|x| (score(q, x["song"].as_str().unwrap_or(""), x["singer"].as_str().unwrap_or(""), x["duration"].as_u64()), x))
.filter(|(s, _)| *s >= 45)
.max_by_key(|(s, _)| *s)
.map(|(_, x)| x.clone())
});
let Some(c) = best else { return Ok(None) };
let dl = format!(
"https://lyrics.kugou.com/download?ver=1&client=pc&id={}&accesskey={}&fmt=lrc&charset=utf8",
enc(&c["id"].as_str().map(String::from).unwrap_or_else(|| c["id"].to_string())),
enc(c["accesskey"].as_str().unwrap_or(""))
);
let v = get_json(http, &dl, &[]).await?;
let Some(content) = v["content"].as_str() else { return Ok(None) };
let bytes = base64::engine::general_purpose::STANDARD.decode(content.trim())?;
Ok(build("Kugou", parse_lrc(&String::from_utf8_lossy(&bytes)), None))
}
fn json_path<'a>(v: &'a Value, path: &str) -> Option<&'a Value> {
path.split('.').filter(|p| !p.is_empty()).try_fold(v, |cur, part| match part.parse::<usize>() {
Ok(i) => cur.get(i),
Err(_) => cur.get(part),
})
}
async fn custom(http: &reqwest::Client, q: &Query, p: &CustomProvider) -> Result<Option<Lyrics>> {
if p.url.trim().is_empty() {
return Ok(None);
}
let fill = |s: &str, encode: bool| {
let e = |x: &str| if encode { enc(x) } else { x.to_string() };
s.replace("{title}", &e(&q.title))
.replace("{artist}", &e(&q.artist))
.replace("{album}", &e(&q.album))
.replace("{duration}", &q.duration_ms.map(|d| (d / 1000).to_string()).unwrap_or_default())
.replace("{duration_ms}", &q.duration_ms.map(|d| d.to_string()).unwrap_or_default())
.replace("{key}", &e(&p.key))
};
let url = fill(&p.url, true);
let headers: Vec<(String, String)> = p.headers.lines().filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_string(), fill(v.trim(), false))).collect();
let name = if p.name.trim().is_empty() { "Custom" } else { p.name.trim() };
if p.format == "json" {
let v = get_json(http, &url, &headers).await?;
let text = json_path(&v, &p.json_path).and_then(|x| x.as_str()).unwrap_or("");
return Ok(build(name, parse_lrc(text), None));
}
let mut req = http.get(&url).timeout(Duration::from_secs(10));
for (k, v) in &headers {
req = req.header(k.as_str(), v.as_str());
}
let resp = req.send().await?;
if !resp.status().is_success() {
return Ok(None);
}
Ok(build(name, parse_lrc(&resp.text().await?), None))
}
fn cache_key(q: &Query) -> String {
hash(&format!("{}|{}|{}", norm(&q.title), norm(&q.artist), q.duration_ms.map(|d| d / 2000).unwrap_or(0)))
}
fn cache_path(q: &Query) -> std::path::PathBuf {
data_dir().join("lyrics").join(format!("{}.json", cache_key(q)))
}
#[derive(Serialize, Deserialize)]
struct Cached {
at: u64,
lyrics: Option<Lyrics>,
}
fn now_s() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
pub async fn find(http: &reqwest::Client, settings: &Settings, raw: &Query, refresh: bool) -> Result<Found> {
let mut tried = Vec::new();
if settings.lyrics_providers.iter().any(|p| p.id == "local" && p.enabled) {
if let Some(l) = local(raw) {
return Ok(Found { lyrics: Some(l), tried, cached: false });
}
tried.push(Attempt { provider: "Your files".into(), outcome: "no .lrc or embedded lyrics".into() });
}
let q = clean(raw);
let cpath = cache_path(&q);
if !refresh {
if let Some(c) = std::fs::read(&cpath).ok().and_then(|b| serde_json::from_slice::<Cached>(&b).ok()) {
if c.lyrics.is_some() || now_s().saturating_sub(c.at) < CACHE_DAYS * 86400 {
return Ok(Found { lyrics: c.lyrics, tried, cached: true });
}
}
}
let mut fallback: Option<Lyrics> = None;
let enabled: Vec<&ProviderCfg> = settings.lyrics_providers.iter().filter(|p| p.enabled && p.id != "local").collect();
for p in &enabled {
let name = match p.id.as_str() {
"lrclib" => "LRCLIB".to_string(),
"musixmatch" => "Musixmatch".to_string(),
"netease" => "NetEase".to_string(),
"kugou" => "Kugou".to_string(),
other => settings.custom_lyrics.iter().find(|c| format!("custom:{}", c.id) == other).map(|c| if c.name.trim().is_empty() { "Custom source".to_string() } else { c.name.clone() }).unwrap_or_else(|| "Custom source".into()),
};
let result = match p.id.as_str() {
"lrclib" => lrclib(http, &q).await,
"musixmatch" if settings.musixmatch_key.trim().is_empty() => {
tried.push(Attempt { provider: name, outcome: "skipped, no API key".into() });
continue;
}
"musixmatch" => musixmatch(http, &q, &settings.musixmatch_key).await,
"netease" => netease(http, &q).await,
"kugou" => kugou(http, &q).await,
other => match settings.custom_lyrics.iter().find(|c| format!("custom:{}", c.id) == other) {
Some(c) => custom(http, &q, c).await,
None => Ok(None),
},
};
match result {
Ok(Some(l)) if l.synced || l.instrumental => {
tried.push(Attempt { provider: name, outcome: if l.instrumental { "instrumental".into() } else { "found synced lyrics".into() } });
fallback = Some(l);
break;
}
Ok(Some(l)) => {
tried.push(Attempt { provider: name, outcome: "found unsynced lyrics".into() });
fallback.get_or_insert(l);
}
Ok(None) => tried.push(Attempt { provider: name, outcome: "not found".into() }),
Err(e) => tried.push(Attempt { provider: name, outcome: format!("unreachable ({})", e.to_string().chars().take(80).collect::<String>()) }),
}
}
let all_failed = !enabled.is_empty() && tried.iter().filter(|t| t.outcome.starts_with("unreachable")).count() == enabled.len();
if !all_failed {
let _ = std::fs::create_dir_all(cpath.parent().unwrap_or(Path::new(".")));
let _ = std::fs::write(&cpath, serde_json::to_vec(&Cached { at: now_s(), lyrics: fallback.clone() }).unwrap_or_default());
}
Ok(Found { lyrics: fallback, tried, cached: false })
}
pub fn is_timed(text: &str) -> bool {
parse_lrc(text).iter().filter(|l| l.t.is_some()).count() >= 2
}
pub fn plain_text(text: &str) -> String {
if !is_timed(text) {
return text.trim().to_string();
}
parse_lrc(text).into_iter().map(|l| l.text).collect::<Vec<_>>().join("\n")
}
pub fn to_lrc(l: &Lyrics) -> String {
l.lines
.iter()
.map(|line| match line.t {
Some(t) => format!("[{:02}:{:02}.{:02}]{}", t / 60000, (t / 1000) % 60, (t % 1000) / 10, line.text),
None => line.text.clone(),
})
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_lrc_with_offsets_and_repeats() {
let l = parse_lrc("[ar:Nova]\n[offset:+500]\n[00:12.50][01:02.00]Hello there\n[00:05.1]First\n");
assert_eq!(l.len(), 3);
assert_eq!(l[0].t, Some(4600));
assert_eq!(l[0].text, "First");
assert_eq!(l[1].t, Some(12000));
assert_eq!(l[2].t, Some(61500));
}
#[test]
fn parses_enhanced_and_yrc_word_timing() {
let l = parse_lrc("[00:01.00]<00:01.00>Hel<00:01.40>lo <00:02.00>world");
assert_eq!(l[0].text, "Hello world");
assert_eq!(l[0].words.len(), 3);
assert_eq!(l[0].words[0].d, 400);
let y = parse_yrc("{\"t\":0,\"c\":[]}\n[1000,2000](1000,500,0)Hi (1500,500,0)you");
assert_eq!(y.len(), 1);
assert_eq!(y[0].text, "Hi you");
assert_eq!(y[0].words[1].t, 1500);
}
#[test]
fn plain_text_stays_unsynced() {
let l = parse_lrc("Line one\nLine two");
assert_eq!(l.len(), 2);
assert!(l.iter().all(|x| x.t.is_none()));
assert!(build("x", l, None).is_some_and(|b| !b.synced));
}
#[test]
fn scores_candidates_sensibly() {
let q = Query { title: "Night Drive (feat. Kai)".into(), artist: "Nova Lumen".into(), duration_ms: Some(200_000), ..Default::default() };
assert!(score(&q, "Night Drive", "Nova Lumen", Some(201_000)) > 80);
assert!(score(&q, "Night Drive", "Nova Lumen", Some(260_000)) < 0);
assert!(score(&q, "Daylight", "Nova Lumen", Some(200_000)) < 0);
let v: Value = serde_json::json!({"a": {"b": [ {"c": "x"} ]}});
assert_eq!(json_path(&v, "a.b.0.c").and_then(|x| x.as_str()), Some("x"));
}
#[test]
fn cleans_video_style_titles() {
let q = |t: &str, a: &str| clean(&Query { title: t.into(), artist: a.into(), ..Default::default() });
let c = q("Daft Punk - Get Lucky (Official Video)", "Daft Punk");
assert_eq!((c.artist.as_str(), c.title.as_str()), ("Daft Punk", "Get Lucky"));
let c = q("Night Drive [Lyrics]", "Nova Lumen - Topic");
assert_eq!((c.artist.as_str(), c.title.as_str()), ("Nova Lumen", "Night Drive"));
let c = q("Ember (Night Edit)", "Kai Rivers");
assert_eq!(c.title, "Ember (Night Edit)");
let c = q("Halsey - Without Me | Official Music Video", "");
assert_eq!((c.artist.as_str(), c.title.as_str()), ("Halsey", "Without Me"));
}
#[tokio::test]
#[ignore = "hits the network; run with --ignored"]
async fn live_lookup_finds_free_lyrics() {
let http = reqwest::Client::builder().user_agent("atmosphere/0.1").build().unwrap();
let settings = Settings::default();
for (title, artist, dur) in [("Daft Punk - Get Lucky (Official Video)", "Daft Punk", 248_000), ("Blinding Lights", "The Weeknd", 200_000)] {
let q = Query { title: title.into(), artist: artist.into(), duration_ms: Some(dur), ..Default::default() };
let f = find(&http, &settings, &q, true).await.unwrap();
let l = f.lyrics.as_ref();
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 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();
println!("NetEase only: provider={:?} synced={:?} words={:?} lines={:?}", l.map(|x| &x.provider), l.map(|x| x.synced), l.map(|x| x.word_synced), l.map(|x| x.lines.len()));
assert!(l.is_some_and(|x| x.synced));
}
#[test]
fn roundtrips_to_lrc() {
let l = build("x", parse_lrc("[01:02.34]Hey"), None).unwrap();
assert_eq!(to_lrc(&l), "[01:02.34]Hey");
}
}
+416
View File
@@ -0,0 +1,416 @@
// 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 downloader;
mod engine;
mod history;
mod libcmd;
mod library;
mod lyrics;
mod media;
mod settings;
mod storage;
mod tagging;
use base64::Engine as _;
use downloader::{Downloader, JobRequest, SaveOptions};
use history::{History, Record};
use media::{Collection, Entry, Prober};
use serde::Serialize;
use settings::{Settings, SettingsPatch, TERMS_VERSION};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
pub(crate) struct AppState {
settings: Arc<Mutex<Settings>>,
pub(crate) http: reqwest::Client,
prober: Arc<Prober>,
dl: Arc<Downloader>,
history: Arc<History>,
pub(crate) library: Arc<library::Library>,
startup_cleanup: Mutex<Option<(usize, u64)>>,
}
pub(crate) type CmdResult<T> = Result<T, String>;
pub(crate) fn err(e: anyhow::Error) -> String {
format!("{e:#}")
}
impl AppState {
pub(crate) fn snapshot(&self) -> Settings {
self.settings.lock().unwrap().clone()
}
pub(crate) fn update(&self, f: impl FnOnce(&mut Settings)) -> CmdResult<Settings> {
let mut s = self.settings.lock().unwrap();
f(&mut s);
settings::save(&s).map_err(err)?;
Ok(s.clone())
}
fn require_rights(&self) -> CmdResult<Settings> {
let s = self.snapshot();
if !s.rights_ok() {
return Err("Confirm the rights acknowledgment before using Atmosphere.".into());
}
Ok(s)
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SettingsView {
#[serde(flatten)]
settings: Settings,
rights_accepted: bool,
terms_version: u32,
}
fn view(s: Settings) -> SettingsView {
SettingsView { rights_accepted: s.rights_ok(), terms_version: TERMS_VERSION, settings: s }
}
#[tauri::command]
fn get_settings(state: State<'_, AppState>) -> SettingsView {
view(state.snapshot())
}
#[tauri::command]
fn accept_rights(state: State<'_, AppState>, version: u32) -> CmdResult<SettingsView> {
if version != TERMS_VERSION {
return Err("The acknowledgment has changed. Please review it again.".into());
}
Ok(view(state.update(Settings::accept_rights)?))
}
#[tauri::command]
fn revoke_rights(state: State<'_, AppState>) -> CmdResult<SettingsView> {
state.dl.cancel_all();
Ok(view(state.update(Settings::revoke_rights)?))
}
#[tauri::command]
fn save_settings(state: State<'_, AppState>, patch: SettingsPatch) -> CmdResult<SettingsView> {
let before = state.snapshot().concurrency;
let after = state.update(|s| s.apply(patch))?;
if after.concurrency != before {
state.dl.set_concurrency(after.concurrency);
}
Ok(view(after))
}
#[tauri::command]
async fn tools_status(state: State<'_, AppState>) -> CmdResult<engine::ToolStatus> {
let s = state.snapshot();
Ok(engine::status(&s.ytdlp_path, &s.ffmpeg_path).await)
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct InstallProgress {
tool: String,
received: u64,
total: Option<u64>,
}
#[tauri::command]
async fn install_tool(app: AppHandle, state: State<'_, AppState>, tool: String) -> CmdResult<engine::ToolStatus> {
let emit = |received: u64, total: Option<u64>| {
let _ = app.emit("atmosphere://install", InstallProgress { tool: tool.clone(), received, total });
};
match tool.as_str() {
"ytdlp" => engine::install_ytdlp(&state.http, emit).await.map_err(err)?,
"ffmpeg" => engine::install_ffmpeg(&state.http, emit).await.map_err(err)?,
_ => return Err("Unknown tool".into()),
};
let s = state.snapshot();
Ok(engine::status(&s.ytdlp_path, &s.ffmpeg_path).await)
}
#[tauri::command]
async fn update_ytdlp(state: State<'_, AppState>) -> CmdResult<String> {
let s = state.snapshot();
let tools = engine::locate(&s.ytdlp_path, &s.ffmpeg_path).map_err(err)?;
engine::update_ytdlp(&tools.ytdlp).await.map_err(err)
}
#[tauri::command]
async fn probe(app: AppHandle, state: State<'_, AppState>, url: String) -> CmdResult<Collection> {
let s = state.require_rights()?;
state.prober.probe(&app, &s, url.trim()).await.map_err(err)
}
#[tauri::command]
async fn search(state: State<'_, AppState>, platform: String, query: String) -> CmdResult<Collection> {
let s = state.require_rights()?;
state.prober.search(&s, &platform, query.trim()).await.map_err(err)
}
#[tauri::command]
async fn detail(state: State<'_, AppState>, url: String, index: u32) -> CmdResult<Entry> {
let s = state.require_rights()?;
state.prober.detail(&s, &url, index).await.map_err(err)
}
#[tauri::command]
fn forget(state: State<'_, AppState>, id: String) {
state.prober.cancel(&id);
}
#[tauri::command]
fn enqueue(state: State<'_, AppState>, jobs: Vec<JobRequest>, save: SaveOptions, attested: bool) -> CmdResult<Vec<u64>> {
state.require_rights()?;
if !attested {
return Err("Confirm you have the rights to download these items first.".into());
}
Ok(state.dl.enqueue(jobs, save))
}
#[tauri::command]
fn cancel(state: State<'_, AppState>, id: u64) {
state.dl.cancel(id);
}
#[tauri::command]
fn cancel_all(state: State<'_, AppState>) {
state.dl.cancel_all();
}
#[tauri::command]
fn history_list(state: State<'_, AppState>) -> Vec<Record> {
state.history.list()
}
#[tauri::command]
fn history_remove(state: State<'_, AppState>, ids: Vec<String>) {
state.history.remove(&ids);
}
#[tauri::command]
fn history_clear(state: State<'_, AppState>) {
state.history.clear();
}
#[tauri::command]
async fn pick_folder(app: AppHandle, state: State<'_, AppState>) -> CmdResult<Option<String>> {
let start = state.snapshot().output_dir;
let picked = tauri::async_runtime::spawn_blocking(move || {
app.dialog().file().set_directory(start).set_title("Choose where downloads are saved").blocking_pick_folder()
})
.await
.map_err(|e| e.to_string())?;
Ok(picked.and_then(|p| p.into_path().ok()).map(|p| p.to_string_lossy().into_owned()))
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PickedImage {
path: String,
data_url: String,
}
#[tauri::command]
async fn pick_image(app: AppHandle) -> CmdResult<Option<PickedImage>> {
let picked = tauri::async_runtime::spawn_blocking(move || {
app.dialog().file().set_title("Choose cover art").add_filter("Images", &["jpg", "jpeg", "png"]).blocking_pick_file()
})
.await
.map_err(|e| e.to_string())?;
let Some(path) = picked.and_then(|p| p.into_path().ok()) else { return Ok(None) };
let data = tokio::fs::read(&path).await.map_err(|e| e.to_string())?;
if data.len() > 20 * 1024 * 1024 {
return Err("That image is over 20 MB. Pick a smaller cover.".into());
}
let mime = if data.starts_with(&[0x89, b'P', b'N', b'G']) {
"image/png"
} else if data.starts_with(&[0xFF, 0xD8]) {
"image/jpeg"
} else {
return Err("Cover art must be a JPEG or PNG image.".into());
};
let data_url = format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(&data));
Ok(Some(PickedImage { path: path.to_string_lossy().into_owned(), data_url }))
}
#[tauri::command]
fn reveal(app: AppHandle, path: String) -> CmdResult<()> {
let p = std::path::PathBuf::from(&path);
let result = if p.is_file() {
app.opener().reveal_item_in_dir(&p)
} else {
std::fs::create_dir_all(&p).map_err(|e| e.to_string())?;
app.opener().open_path(path, None::<&str>)
};
result.map_err(|e| e.to_string())
}
#[tauri::command]
fn open_link(app: AppHandle, url: String) -> CmdResult<()> {
if !url.starts_with("https://") && !url.starts_with("http://") {
return Err("Only web links can be opened.".into());
}
app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string())
}
#[tauri::command]
fn storage_report(state: State<'_, AppState>) -> Vec<storage::Item> {
let s = state.snapshot();
let lib = state.library.snapshot(std::path::Path::new(&s.playlists_dir));
storage::report(&s, &lib, state.dl.busy())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Cleaned {
files: usize,
bytes: u64,
}
#[tauri::command]
fn storage_clean(state: State<'_, AppState>, ids: Vec<String>) -> Cleaned {
let s = state.snapshot();
let lib = state.library.snapshot(std::path::Path::new(&s.playlists_dir));
let (files, bytes) = storage::clean(&s, &lib, &ids, state.dl.busy());
Cleaned { files, bytes }
}
#[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 pick_text_file(app: AppHandle) -> CmdResult<Option<String>> {
let picked = tauri::async_runtime::spawn_blocking(move || {
app.dialog().file().set_title("Import lyrics").add_filter("Lyrics", &["lrc", "txt"]).blocking_pick_file()
})
.await
.map_err(|e| e.to_string())?;
let Some(path) = picked.and_then(|p| p.into_path().ok()) else { return Ok(None) };
let data = tokio::fs::read(&path).await.map_err(|e| e.to_string())?;
if data.len() > 1024 * 1024 {
return Err("That file is too large to be lyrics.".into());
}
Ok(Some(String::from_utf8_lossy(&data).trim_start_matches('\u{feff}').to_string()))
}
#[tauri::command]
fn clipboard_text(app: AppHandle) -> String {
app.clipboard().read_text().unwrap_or_default()
}
#[tauri::command]
fn clipboard_write(app: AppHandle, text: String) -> CmdResult<()> {
app.clipboard().write_text(text).map_err(|e| e.to_string())
}
#[tauri::command]
fn read_clipboard(app: AppHandle, state: State<'_, AppState>) -> Option<String> {
if !state.snapshot().watch_clipboard {
return None;
}
let text = app.clipboard().read_text().ok()?;
let t = text.trim();
(t.len() < 2048 && (t.starts_with("https://") || t.starts_with("http://")) && !t.contains(char::is_whitespace)).then(|| t.to_string())
}
fn main() {
let settings = Arc::new(Mutex::new(settings::load()));
let http = reqwest::Client::builder()
.user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION")))
.connect_timeout(Duration::from_secs(15))
.read_timeout(Duration::from_secs(90))
.build()
.expect("http client");
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_clipboard_manager::init())
.register_asynchronous_uri_scheme_protocol("atmo", |ctx, request, responder| {
let app = ctx.app_handle().clone();
tauri::async_runtime::spawn_blocking(move || responder.respond(libcmd::serve(&app, &request)));
})
.setup(move |app| {
let history = Arc::new(History::load(engine::data_dir().join("history.json")));
let cleaned = storage::startup(&settings.lock().unwrap());
let library = Arc::new(library::Library::load());
let dl = Arc::new(Downloader::new(app.handle().clone(), settings.clone(), history.clone(), library.clone(), http.clone()));
app.manage(AppState { settings: settings.clone(), http: http.clone(), prober: Arc::new(Prober::default()), dl, history, library, startup_cleanup: Mutex::new(Some(cleaned)) });
libcmd::spawn_scan(app.handle().clone());
libcmd::start_watch(app.handle().clone());
Ok(())
})
.invoke_handler(tauri::generate_handler![
get_settings,
accept_rights,
revoke_rights,
save_settings,
tools_status,
install_tool,
update_ytdlp,
probe,
search,
detail,
forget,
enqueue,
cancel,
cancel_all,
history_list,
history_remove,
history_clear,
pick_folder,
pick_image,
reveal,
open_link,
read_clipboard,
clipboard_text,
pick_text_file,
clipboard_write,
storage_report,
storage_clean,
startup_cleanup,
libcmd::library_get,
libcmd::library_scan,
libcmd::library_add_folder,
libcmd::library_remove_folder,
libcmd::playlist_create,
libcmd::playlist_rename,
libcmd::playlist_delete,
libcmd::playlist_add,
libcmd::playlist_add_files,
libcmd::playlist_remove,
libcmd::playlist_reorder,
libcmd::track_played,
libcmd::track_listened,
libcmd::app_heartbeat,
libcmd::stats_get,
libcmd::image_save,
libcmd::image_copy,
libcmd::tracks_delete,
libcmd::tracks_hide,
libcmd::tracks_unhide_all,
libcmd::track_like,
libcmd::track_edit,
libcmd::artist_update,
libcmd::lyrics_get,
libcmd::lyrics_save,
libcmd::lyrics_save_text,
libcmd::set_fullscreen
])
.build(tauri::generate_context!())
.expect("error while building atmosphere")
.run(|app, event| {
if let tauri::RunEvent::Exit = event {
if let Some(state) = app.try_state::<AppState>() {
state.dl.cancel_all();
}
storage::wipe_temp();
}
});
}
+675
View File
@@ -0,0 +1,675 @@
// atmosphere · media.rs · Turns links and searches into collections via yt-dlp: metadata, available formats and release-type detection.
use crate::engine::{self, Tools};
use crate::settings::Settings;
use anyhow::{anyhow, bail, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::process::Stdio;
use std::sync::{Arc, LazyLock, Mutex};
use tauri::{AppHandle, Emitter};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::Notify;
pub const PROBE_EVENT: &str = "atmosphere://probe";
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaInfo {
pub has_video: bool,
pub heights: Vec<u32>,
pub best_abr: Option<u32>,
pub best_codec: Option<String>,
pub lossless: bool,
pub original: bool,
pub original_lossless: bool,
pub original_ext: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Entry {
pub index: u32,
pub id: String,
pub url: String,
pub title: String,
pub artist: String,
pub uploader: String,
pub album: Option<String>,
pub album_artist: Option<String>,
pub track_number: Option<u32>,
pub disc_number: Option<u32>,
pub genre: Option<String>,
pub composer: Option<String>,
pub release_date: Option<String>,
pub year: Option<u16>,
pub duration_ms: Option<u64>,
pub thumbnail: Option<String>,
pub license: Option<String>,
pub description: Option<String>,
pub lyrics: Option<String>,
pub platform: String,
pub availability: String,
pub media: Option<MediaInfo>,
pub detailed: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Collection {
pub id: String,
pub single: bool,
pub release_type: String,
pub release_type_source: String,
pub title: String,
pub artist: String,
pub url: String,
pub thumbnail: Option<String>,
pub platform: String,
pub year: Option<u16>,
pub entries: Vec<Entry>,
pub enriching: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum ProbeEvent {
#[serde(rename_all = "camelCase")]
Entry { collection: String, entry: Box<Entry> },
#[serde(rename_all = "camelCase")]
Done { collection: String, release_type: String, release_type_source: String, artist: String, year: Option<u16>, failed: u32 },
}
#[derive(Default)]
pub struct Prober {
running: Mutex<HashMap<String, Arc<Notify>>>,
}
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn s(v: &Value) -> Option<String> {
v.as_str().map(str::trim).filter(|x| !x.is_empty()).map(String::from)
}
fn joined(v: &Value) -> Option<String> {
let items: Vec<String> = v.as_array()?.iter().filter_map(s).collect();
(!items.is_empty()).then(|| items.join(", "))
}
fn ymd(raw: &str) -> Option<String> {
let d: String = raw.chars().filter(|c| c.is_ascii_digit()).collect();
match d.len() {
8 => Some(format!("{}-{}-{}", &d[..4], &d[4..6], &d[6..])),
4 => Some(d),
_ => None,
}
}
pub fn platform_name(extractor: &str) -> String {
let e = extractor.to_ascii_lowercase();
let known = [
("soundcloud", "SoundCloud"),
("youtube", "YouTube"),
("bandcamp", "Bandcamp"),
("vimeo", "Vimeo"),
("twitch", "Twitch"),
("mixcloud", "Mixcloud"),
("audiomack", "Audiomack"),
("tiktok", "TikTok"),
("twitter", "X"),
("instagram", "Instagram"),
("dailymotion", "Dailymotion"),
("archiveorg", "Internet Archive"),
("generic", "Web"),
];
known
.iter()
.find(|(k, _)| e.starts_with(k))
.map(|(_, n)| n.to_string())
.unwrap_or_else(|| extractor.trim_end_matches("IE").to_string())
}
fn summarize_formats(v: &Value) -> (MediaInfo, String) {
let mut info = MediaInfo::default();
let formats = v["formats"].as_array().cloned().unwrap_or_default();
let usable: Vec<&Value> = formats
.iter()
.filter(|f| !f["has_drm"].as_bool().unwrap_or(false))
.filter(|f| !s(&f["format_id"]).unwrap_or_default().contains("preview"))
.collect();
if formats.is_empty() {
let has_v = s(&v["vcodec"]).is_some_and(|c| c != "none");
info.has_video = has_v;
info.best_abr = v["abr"].as_f64().map(|a| a.round() as u32);
return (info, "ok".into());
}
if usable.is_empty() {
let drm = formats.iter().any(|f| f["has_drm"].as_bool().unwrap_or(false));
return (info, if drm { "drm" } else { "preview" }.into());
}
let lossless_codec = |c: &str| ["flac", "alac", "pcm", "wav", "aiff"].iter().any(|l| c.starts_with(l));
let mut heights: Vec<u32> = Vec::new();
let mut best: Option<(u32, String)> = None;
for f in &usable {
let vcodec = s(&f["vcodec"]).unwrap_or_else(|| "none".into());
let acodec = s(&f["acodec"]).unwrap_or_else(|| "none".into());
let id = s(&f["format_id"]).unwrap_or_default();
if id == "download" {
info.original = true;
info.original_ext = s(&f["ext"]);
if f["ext"].as_str().is_some_and(|e| ["wav", "flac", "aiff", "aif"].contains(&e)) {
info.original_lossless = true;
}
continue;
}
if vcodec != "none" {
info.has_video = true;
if let Some(h) = f["height"].as_u64() {
if !heights.contains(&(h as u32)) {
heights.push(h as u32);
}
}
}
if acodec != "none" {
if lossless_codec(&acodec) {
info.lossless = true;
}
let abr = f["abr"].as_f64().or_else(|| (vcodec == "none").then(|| f["tbr"].as_f64()).flatten());
if let Some(a) = abr.map(|a| a.round() as u32) {
if best.as_ref().is_none_or(|(b, _)| a > *b) {
best = Some((a, acodec.split('.').next().unwrap_or(&acodec).to_string()));
}
}
}
}
heights.sort_unstable_by(|a, b| b.cmp(a));
info.heights = heights;
if let Some((abr, codec)) = best {
info.best_abr = Some(abr);
info.best_codec = Some(codec);
}
(info, "ok".into())
}
fn best_thumbnail(v: &Value) -> Option<String> {
if let Some(list) = v["thumbnails"].as_array() {
let pick = list
.iter()
.filter(|t| s(&t["url"]).is_some())
.max_by_key(|t| (t["preference"].as_i64().unwrap_or(0), t["width"].as_u64().unwrap_or(0)));
if let Some(t) = pick {
return s(&t["url"]);
}
}
s(&v["thumbnail"])
}
pub fn entry_from_info(v: &Value, index: u32) -> Entry {
let extractor = s(&v["extractor_key"]).or_else(|| s(&v["ie_key"])).unwrap_or_default();
let uploader = s(&v["uploader"]).or_else(|| s(&v["channel"])).unwrap_or_default();
let has_formats = v["formats"].is_array() || v["vcodec"].is_string() || v["acodec"].is_string();
let (media, mut availability) = if has_formats {
let (m, a) = summarize_formats(v);
(Some(m), a)
} else {
(None, "ok".into())
};
if let Some(a) = s(&v["availability"]) {
if matches!(a.as_str(), "needs_auth" | "premium_only" | "subscriber_only") && availability == "ok" {
availability = "restricted".into();
}
}
let (desc_lyrics, desc_rest) = s(&v["description"]).map(|d| split_lyrics(&d)).unwrap_or((None, None));
let release_date = s(&v["release_date"]).and_then(|d| ymd(&d)).or_else(|| s(&v["upload_date"]).and_then(|d| ymd(&d)));
let year = v["release_year"]
.as_u64()
.map(|y| y as u16)
.or_else(|| release_date.as_deref().and_then(|d| d.get(..4)?.parse().ok()));
Entry {
index,
id: s(&v["id"]).unwrap_or_default(),
url: s(&v["webpage_url"]).or_else(|| s(&v["original_url"])).or_else(|| s(&v["url"])).unwrap_or_default(),
title: s(&v["track"]).or_else(|| s(&v["title"])).unwrap_or_else(|| "Untitled".into()),
artist: s(&v["artist"])
.or_else(|| joined(&v["artists"]))
.or_else(|| s(&v["creator"]))
.unwrap_or_else(|| uploader.clone()),
uploader,
album: s(&v["album"]),
album_artist: s(&v["album_artist"]).or_else(|| joined(&v["album_artists"])),
track_number: v["track_number"].as_u64().map(|n| n as u32),
disc_number: v["disc_number"].as_u64().map(|n| n as u32),
genre: s(&v["genre"]).or_else(|| joined(&v["genres"])),
composer: s(&v["composer"]).or_else(|| joined(&v["composers"])),
release_date,
year,
duration_ms: v["duration"].as_f64().map(|d| (d * 1000.0) as u64),
thumbnail: best_thumbnail(v),
license: s(&v["license"]),
description: desc_rest,
lyrics: desc_lyrics,
platform: platform_name(&extractor),
availability,
detailed: has_formats,
media,
}
}
static LYRIC_HEAD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)^\s*[\[\(]?\s*(lyrics|lyric|letra|letras|paroles|songtext|testo|歌词|歌詞|가사)\s*[\]\)]?\s*[::\-–—]?\s*(.*)$").unwrap());
static SECTION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)^\s*[\[\(]\s*(verse|chorus|hook|bridge|intro|outro|pre-chorus|refrain|interlude|breakdown|drop)[^\]\)]*[\]\)]\s*$").unwrap());
static END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)^\s*(prod\.?|produced|producer|mixed|mix(ing)?\s*(&|and)?\s*master|mastered|mastering|engineered|artwork|cover art|art by|written by|composed|credits?|follow|stream|download|free download|buy|out now|available|booking|contact|management|label|instagram|insta|ig\b|twitter|tiktok|spotify|apple music|youtube|bandcamp|soundcloud|support|thanks|©|℗|copyright|\(c\)|https?://|www\.|@\w)").unwrap());
static LRC_LINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\[\d{1,3}:\d{1,2}(?:[.:]\d{1,3})?\]").unwrap());
fn tidy(lines: &[&str]) -> Option<String> {
let text = lines.join("\n").trim_matches(|c: char| c == '\n' || c.is_whitespace()).to_string();
let words = text.split_whitespace().count();
(words >= 12).then_some(text)
}
pub fn split_lyrics(desc: &str) -> (Option<String>, Option<String>) {
let lines: Vec<&str> = desc.lines().collect();
let rest_of = |skip: std::ops::Range<usize>| {
let r: Vec<&str> = lines.iter().enumerate().filter(|(i, _)| !skip.contains(i)).map(|(_, l)| *l).collect();
let t = r.join("\n").trim().to_string();
(!t.is_empty()).then_some(t)
};
let timed: Vec<usize> = lines.iter().enumerate().filter(|(_, l)| LRC_LINE.is_match(l)).map(|(i, _)| i).collect();
if timed.len() >= 4 {
let (a, b) = (timed[0], timed[timed.len() - 1] + 1);
if let Some(l) = tidy(&lines[a..b]) {
return (Some(l), rest_of(a..b));
}
}
if let Some(start) = lines.iter().position(|l| LYRIC_HEAD.is_match(l)) {
let inline = LYRIC_HEAD.captures(lines[start]).and_then(|c| c.get(2)).map(|m| m.as_str().trim()).filter(|s| !s.is_empty());
let mut end = start + 1;
let mut blank_run = 0;
while end < lines.len() {
let l = lines[end].trim();
if END.is_match(l) {
break;
}
blank_run = if l.is_empty() { blank_run + 1 } else { 0 };
if blank_run >= 3 {
break;
}
end += 1;
}
let mut body: Vec<&str> = Vec::new();
if let Some(i) = inline {
body.push(i);
}
body.extend_from_slice(&lines[start + 1..end]);
if let Some(l) = tidy(&body) {
return (Some(l), rest_of(start..end));
}
}
let sections = lines.iter().filter(|l| SECTION.is_match(l)).count();
if sections >= 2 {
let first = lines.iter().position(|l| SECTION.is_match(l)).unwrap_or(0);
let mut end = first;
while end < lines.len() && !END.is_match(lines[end].trim()) {
end += 1;
}
if let Some(l) = tidy(&lines[first..end]) {
return (Some(l), rest_of(first..end));
}
}
let t = desc.trim();
(None, (!t.is_empty()).then(|| t.chars().take(4000).collect()))
}
fn common<T: PartialEq + Clone>(entries: &[Entry], f: impl Fn(&Entry) -> Option<T>) -> Option<T> {
let first = f(entries.first()?)?;
entries.iter().all(|e| f(e).as_ref() == Some(&first)).then_some(first)
}
fn by_length(entries: &[Entry]) -> &'static str {
let minutes = entries.iter().filter_map(|e| e.duration_ms).sum::<u64>() as f64 / 60000.0;
match entries.len() {
n if n <= 3 && minutes < 30.0 => "single",
n if n <= 6 && minutes < 30.0 => "ep",
_ => "album",
}
}
static TITLE_RULES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
[
(r"(?i)\b(compilation|various artists|v\.?a\.?)\b", "compilation"),
(r"(?i)\bmix ?tape\b", "mixtape"),
(r"(?i)\be\.?p\.?\b", "ep"),
(r"(?i)\bl\.?p\.?\b", "lp"),
(r"(?i)\bsingle\b", "single"),
(r"(?i)\b(deluxe|album|remaster(ed)?|anniversary edition)\b", "album"),
]
.into_iter()
.map(|(p, k)| (Regex::new(p).unwrap(), k))
.collect()
});
pub fn classify(extractor: &str, playlist_id: &str, url: &str, title: &str, entries: &[Entry]) -> (String, String) {
let ex = extractor.to_ascii_lowercase();
if ex.contains("soundclouduser") || ex.contains("soundcloud:user") {
return ("profile".into(), "platform".into());
}
if ex.starts_with("youtubetab") && (playlist_id.starts_with("UC") || url.contains("/@") || url.contains("/channel/")) {
return ("channel".into(), "platform".into());
}
for (re, kind) in TITLE_RULES.iter() {
if re.is_match(title) {
return ((*kind).into(), "title".into());
}
}
if ex.starts_with("bandcampalbum") || ex == "bandcamp:album" || playlist_id.starts_with("OLAK5uy_") {
return (by_length(entries).into(), "platform".into());
}
let norm = |x: &str| x.trim().to_lowercase();
let shared_album = common(entries, |e| e.album.as_deref().map(norm));
let one_artist = common(entries, |e| Some(e.artist.to_lowercase())).is_some();
let numbered = entries.len() > 1 && entries.iter().enumerate().all(|(i, e)| e.track_number == Some(i as u32 + 1));
if shared_album.as_deref().is_some_and(|a| a == norm(title)) || (shared_album.is_some() && one_artist) || (numbered && one_artist) {
return (by_length(entries).into(), "metadata".into());
}
("playlist".into(), "none".into())
}
fn release_artist(kind: &str, fallback: &str, entries: &[Entry]) -> String {
if let Some(a) = common(entries, |e| e.album_artist.clone()) {
return a;
}
if let Some(a) = common(entries, |e| Some(e.artist.clone())) {
return a;
}
if kind == "compilation" {
return "Various Artists".into();
}
fallback.to_string()
}
pub fn humanize(stderr: &str) -> String {
let err = stderr
.lines()
.rev()
.find(|l| l.contains("ERROR"))
.map(|l| l.trim().trim_start_matches("ERROR:").trim().to_string())
.unwrap_or_else(|| stderr.lines().last().unwrap_or("Unknown error").trim().to_string());
let lower = err.to_lowercase();
if lower.contains("unsupported url") {
"Atmosphere can't read that link. The site isn't supported.".into()
} else if lower.contains("drm") {
"This stream is DRM-encrypted, so Atmosphere can't read it. If it's your own track, turn on downloads for it in the platform's track settings (or enable “Use my browser sign-in”), then choose Original file to get your uploaded master.".into()
} else if lower.contains("sign in") || lower.contains("private") || lower.contains("login") || lower.contains("members-only") {
format!("{err} — if this is your own content, enable “Use my browser sign-in” in Settings.")
} else if lower.contains("404") || lower.contains("not found") || lower.contains("does not exist") {
"Not found — the link may be private, removed or mistyped.".into()
} else if lower.contains("429") || lower.contains("too many requests") {
"The site is rate-limiting requests. Wait a bit and try again.".into()
} else {
static PREFIX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[[^\]]+\]\s*(\S+:\s+)?").unwrap());
let cleaned = PREFIX.replace(&err, "").trim().chars().take(300).collect::<String>();
if cleaned.is_empty() { err } else { cleaned }
}
}
pub fn base_args(settings: &Settings, tools: &Tools) -> Vec<String> {
let mut args: Vec<String> = ["--ignore-config", "--no-warnings", "--encoding", "utf-8", "--no-color"].map(String::from).into();
if let Some(ff) = &tools.ffmpeg {
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());
}
if !settings.proxy.trim().is_empty() {
args.push("--proxy".into());
args.push(settings.proxy.trim().into());
}
args
}
async fn run_json(tools: &Tools, args: Vec<String>) -> Result<Value> {
let out = engine::command(&tools.ytdlp).args(&args).stdout(Stdio::piped()).stderr(Stdio::piped()).output().await?;
if !out.status.success() || out.stdout.is_empty() {
bail!(humanize(&String::from_utf8_lossy(&out.stderr)));
}
serde_json::from_slice(&out.stdout).map_err(|e| anyhow!("Unexpected response from yt-dlp ({e})"))
}
fn collection_from(v: &Value, id: String, link: &str) -> Collection {
let extractor = s(&v["extractor_key"]).unwrap_or_default();
let is_list = matches!(v["_type"].as_str(), Some("playlist") | Some("multi_video"));
if !is_list {
let entry = entry_from_info(v, 1);
return Collection {
id,
single: true,
release_type: "track".into(),
release_type_source: "none".into(),
title: entry.title.clone(),
artist: entry.artist.clone(),
url: entry.url.clone(),
thumbnail: entry.thumbnail.clone(),
platform: entry.platform.clone(),
year: entry.year,
entries: vec![entry],
enriching: false,
};
}
let entries: Vec<Entry> = v["entries"]
.as_array()
.map(|list| {
list.iter()
.enumerate()
.filter(|(_, e)| !e.is_null())
.map(|(i, e)| {
let mut entry = entry_from_info(e, i as u32 + 1);
if entry.platform.is_empty() {
entry.platform = platform_name(&extractor);
}
entry
})
.collect()
})
.unwrap_or_default();
let title = s(&v["title"]).unwrap_or_else(|| "Untitled".into());
let pid = s(&v["id"]).unwrap_or_default();
let url = s(&v["webpage_url"]).unwrap_or_else(|| link.to_string());
let (release_type, source) = classify(&extractor, &pid, &url, &title, &entries);
let owner = s(&v["uploader"]).or_else(|| s(&v["channel"])).unwrap_or_default();
let artist = release_artist(&release_type, &owner, &entries);
let thumbnail = best_thumbnail(v).or_else(|| entries.iter().find_map(|e| e.thumbnail.clone()));
let needs_detail = entries.iter().any(|e| !e.detailed);
Collection {
id,
single: false,
release_type,
release_type_source: source,
title,
artist,
url,
thumbnail,
platform: platform_name(&extractor),
year: v["release_year"].as_u64().map(|y| y as u16).or_else(|| entries.iter().find_map(|e| e.year)),
entries,
enriching: needs_detail,
}
}
impl Prober {
pub async fn probe(self: &Arc<Self>, app: &AppHandle, settings: &Settings, link: &str) -> Result<Collection> {
let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?;
let mut args = base_args(settings, &tools);
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);
if collection.enriching {
self.enrich(app.clone(), settings.clone(), tools, collection.clone(), v);
}
Ok(collection)
}
pub async fn search(&self, settings: &Settings, platform: &str, query: &str) -> Result<Collection> {
let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?;
let prefix = match platform {
"soundcloud" => "scsearch20",
_ => "ytsearch20",
};
let mut args = base_args(settings, &tools);
args.extend(["-J".into(), "--flat-playlist".into(), "--".into(), format!("{prefix}:{query}")]);
let v = run_json(&tools, args).await?;
let id = format!("s{}", NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst));
let mut c = collection_from(&v, id, query);
c.release_type = "search".into();
c.release_type_source = "none".into();
c.title = query.to_string();
c.enriching = false;
Ok(c)
}
pub async fn detail(&self, settings: &Settings, url: &str, index: u32) -> Result<Entry> {
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))
}
pub fn cancel(&self, id: &str) {
if let Some(n) = self.running.lock().unwrap().remove(id) {
n.notify_one();
}
}
fn enrich(self: &Arc<Self>, app: AppHandle, settings: Settings, tools: Tools, collection: Collection, raw: Value) {
let stop = Arc::new(Notify::new());
self.running.lock().unwrap().insert(collection.id.clone(), stop.clone());
let this = self.clone();
tauri::async_runtime::spawn(async move {
let mut args = base_args(&settings, &tools);
args.extend(["-j", "--ignore-errors", "--yes-playlist", "--", &collection.url].map(String::from));
let mut entries = collection.entries.clone();
let mut failed = 0u32;
let spawned = engine::command(&tools.ytdlp).args(&args).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true).spawn();
if let Ok(mut child) = spawned {
if let Some(stdout) = child.stdout.take() {
let mut lines = BufReader::new(stdout).lines();
loop {
tokio::select! {
_ = stop.notified() => { let _ = child.kill().await; return; }
line = lines.next_line() => {
let Ok(Some(line)) = line else { break };
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
let idx = v["playlist_index"].as_u64().map(|i| i as u32);
let vid = s(&v["id"]).unwrap_or_default();
let slot = entries.iter().position(|e| Some(e.index) == idx).or_else(|| entries.iter().position(|e| e.id == vid));
if let Some(pos) = slot {
let entry = entry_from_info(&v, entries[pos].index);
entries[pos] = entry.clone();
let _ = app.emit(PROBE_EVENT, ProbeEvent::Entry { collection: collection.id.clone(), entry: Box::new(entry) });
}
}
}
}
}
let _ = child.wait().await;
}
failed += entries.iter().filter(|e| !e.detailed).count() as u32;
let extractor = s(&raw["extractor_key"]).unwrap_or_default();
let pid = s(&raw["id"]).unwrap_or_default();
let (release_type, source) = classify(&extractor, &pid, &collection.url, &collection.title, &entries);
let owner = s(&raw["uploader"]).or_else(|| s(&raw["channel"])).unwrap_or_default();
let artist = release_artist(&release_type, &owner, &entries);
let year = entries.iter().find_map(|e| e.year);
let _ = app.emit(
PROBE_EVENT,
ProbeEvent::Done { collection: collection.id.clone(), release_type, release_type_source: source, artist, year, failed },
);
this.running.lock().unwrap().remove(&collection.id);
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn e(artist: &str, album: Option<&str>, mins: u64, n: Option<u32>) -> Entry {
Entry {
artist: artist.into(),
album: album.map(String::from),
duration_ms: Some(mins * 60000),
track_number: n,
..Default::default()
}
}
#[test]
fn classifies_by_title_platform_and_metadata() {
let five: Vec<_> = (0..5).map(|i| e("Nova", Some("Glass"), 4, Some(i + 1))).collect();
assert_eq!(classify("SoundcloudSet", "1", "", "Glass", &five), ("ep".into(), "metadata".into()));
let ten: Vec<_> = (0..10).map(|i| e("Nova", Some("Glass"), 4, Some(i + 1))).collect();
assert_eq!(classify("SoundcloudSet", "1", "", "Glass", &ten).0, "album");
assert_eq!(classify("SoundcloudSet", "1", "", "Midnight Drive EP", &ten), ("ep".into(), "title".into()));
assert_eq!(classify("SoundcloudSet", "1", "", "Sunset LP", &ten).0, "lp");
assert_eq!(classify("SoundcloudSet", "1", "", "Summer Mixtape 2024", &ten).0, "mixtape");
assert_eq!(classify("BandcampAlbum", "1", "", "Glass", &ten), ("album".into(), "platform".into()));
assert_eq!(classify("SoundcloudUser", "1", "", "Nova", &ten).0, "profile");
let mixed = vec![e("A", None, 3, None), e("B", None, 3, None)];
assert_eq!(classify("SoundcloudSet", "1", "", "Faves", &mixed).0, "playlist");
assert_eq!(classify("SoundcloudSet", "1", "", "Help", &mixed).0, "playlist");
assert_eq!(release_artist("compilation", "owner", &mixed), "Various Artists");
}
#[test]
fn summarizes_formats_honestly() {
let v = json!({
"id": "1", "title": "Song", "extractor_key": "Soundcloud", "webpage_url": "https://soundcloud.com/a/b",
"upload_date": "20210314", "duration": 200.5,
"formats": [
{"format_id": "hls_mp3_1_0", "acodec": "mp3", "vcodec": "none", "abr": 128, "ext": "mp3"},
{"format_id": "hls_aac_160k", "acodec": "aac", "vcodec": "none", "abr": 160, "ext": "m4a"},
{"format_id": "download", "ext": "wav", "acodec": "none", "vcodec": "none"},
{"format_id": "x", "acodec": "aac", "vcodec": "none", "abr": 256, "has_drm": true}
]
});
let entry = entry_from_info(&v, 1);
let m = entry.media.unwrap();
assert_eq!(m.best_abr, Some(160));
assert!(m.original && m.original_lossless && !m.lossless && !m.has_video);
assert_eq!(entry.release_date.as_deref(), Some("2021-03-14"));
assert_eq!(entry.platform, "SoundCloud");
assert_eq!(entry.duration_ms, Some(200500));
let drm = entry_from_info(&json!({"formats": [{"format_id": "a", "has_drm": true}]}), 1);
assert_eq!(drm.availability, "drm");
}
#[test]
fn splits_lyrics_from_descriptions() {
let d = "New single out now!\n\nLyrics:\nHeadlights on the overpass\nEvery window holds a star\n\nWe don't need to say it twice\nNight drive keep the city close\n\nProd. by Kai Rivers\nInstagram: @novalumen\nhttps://example.com";
let (l, rest) = split_lyrics(d);
let l = l.unwrap();
assert!(l.starts_with("Headlights") && l.ends_with("city close"));
let rest = rest.unwrap();
assert!(rest.contains("out now") && rest.contains("Prod. by") && !rest.contains("Headlights"));
let timed = "Stream everywhere\n[00:01.00]One two three four\n[00:04.00]Five six seven eight\n[00:08.00]Nine ten eleven twelve\n[00:12.00]Thirteen fourteen fifteen";
let (l, rest) = split_lyrics(timed);
assert!(l.unwrap().starts_with("[00:01.00]"));
assert_eq!(rest.as_deref(), Some("Stream everywhere"));
let sections = "[Verse 1]\nI walk the line between the night and day\nCount the lights along the way\n[Chorus]\nHold on hold on we're nearly home\nHold on we're not alone\nFollow me on twitter";
let (l, _) = split_lyrics(sections);
assert!(l.unwrap().contains("[Chorus]"));
let promo = "Free download! Mixed and mastered by me. Thanks for 10k plays";
let (l, rest) = split_lyrics(promo);
assert!(l.is_none());
assert_eq!(rest.as_deref(), Some(promo));
}
#[test]
fn humanizes_errors() {
assert!(humanize("ERROR: Unsupported URL: https://x").contains("isn't supported"));
assert!(humanize("ERROR: [youtube] abc: Private video. Sign in").contains("browser sign-in"));
}
}
+264
View File
@@ -0,0 +1,264 @@
// atmosphere · settings.rs · Persistent user settings: rights acknowledgment, save-as defaults, engine paths and network options.
use crate::lyrics::{default_providers, CustomProvider, ProviderCfg};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
pub const TERMS_VERSION: u32 = 1;
pub const MP3_BITRATES: [u32; 7] = [64, 96, 128, 160, 192, 256, 320];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SaveAs {
Original,
#[default]
Best,
Mp3,
M4a,
Flac,
Wav,
Video,
}
impl SaveAs {
pub fn audio_format(self) -> Option<&'static str> {
match self {
SaveAs::Mp3 => Some("mp3"),
SaveAs::M4a => Some("m4a"),
SaveAs::Flac => Some("flac"),
SaveAs::Wav => Some("wav"),
_ => None,
}
}
}
pub fn snap_bitrate(requested: u32, cap: Option<u32>) -> u32 {
let limit = cap.map_or(requested, |c| requested.min(c));
MP3_BITRATES.iter().copied().filter(|b| *b <= limit).max().unwrap_or(MP3_BITRATES[0])
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Settings {
pub rights_version: u32,
pub rights_accepted_at: Option<u64>,
pub output_dir: String,
pub save_as: SaveAs,
pub mp3_bitrate: u32,
pub video_height: u32,
pub video_container: String,
pub concurrency: u8,
pub filename_template: String,
pub embed_metadata: bool,
pub collection_folders: bool,
pub number_tracks: bool,
pub skip_downloaded: bool,
pub sponsorblock: bool,
pub embed_subtitles: bool,
pub subtitle_langs: String,
pub embed_chapters: bool,
pub cookies_browser: String,
pub proxy: String,
pub rate_limit: String,
pub ytdlp_path: String,
pub ffmpeg_path: String,
pub watch_clipboard: bool,
pub theme: String,
pub library_folders: Vec<String>,
pub playlists_dir: String,
pub playlist_copy: bool,
pub lyrics_providers: Vec<ProviderCfg>,
pub musixmatch_key: String,
pub custom_lyrics: Vec<CustomProvider>,
pub lyrics_on_download: bool,
pub fx_presets: Vec<serde_json::Value>,
}
impl Default for Settings {
fn default() -> Self {
let base = dirs::audio_dir().or_else(dirs::download_dir).unwrap_or_else(|| PathBuf::from("."));
let out = base.join("Atmosphere");
Self {
rights_version: 0,
rights_accepted_at: None,
output_dir: out.to_string_lossy().into_owned(),
save_as: SaveAs::Best,
mp3_bitrate: 320,
video_height: 1080,
video_container: "mp4".into(),
concurrency: 3,
filename_template: "{artist} - {title}".into(),
embed_metadata: true,
collection_folders: true,
number_tracks: true,
skip_downloaded: true,
sponsorblock: false,
embed_subtitles: false,
subtitle_langs: "en".into(),
embed_chapters: true,
cookies_browser: String::new(),
proxy: String::new(),
rate_limit: String::new(),
ytdlp_path: String::new(),
ffmpeg_path: String::new(),
watch_clipboard: true,
theme: "system".into(),
library_folders: vec![out.to_string_lossy().into_owned()],
playlists_dir: out.join("Playlists").to_string_lossy().into_owned(),
playlist_copy: false,
lyrics_providers: default_providers(),
musixmatch_key: String::new(),
custom_lyrics: Vec::new(),
lyrics_on_download: false,
fx_presets: Vec::new(),
}
}
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct SettingsPatch {
pub output_dir: Option<String>,
pub save_as: Option<SaveAs>,
pub mp3_bitrate: Option<u32>,
pub video_height: Option<u32>,
pub video_container: Option<String>,
pub concurrency: Option<u8>,
pub filename_template: Option<String>,
pub embed_metadata: Option<bool>,
pub collection_folders: Option<bool>,
pub number_tracks: Option<bool>,
pub skip_downloaded: Option<bool>,
pub sponsorblock: Option<bool>,
pub embed_subtitles: Option<bool>,
pub subtitle_langs: Option<String>,
pub embed_chapters: Option<bool>,
pub cookies_browser: Option<String>,
pub proxy: Option<String>,
pub rate_limit: Option<String>,
pub ytdlp_path: Option<String>,
pub ffmpeg_path: Option<String>,
pub watch_clipboard: Option<bool>,
pub theme: Option<String>,
pub library_folders: Option<Vec<String>>,
pub playlists_dir: Option<String>,
pub playlist_copy: Option<bool>,
pub lyrics_providers: Option<Vec<ProviderCfg>>,
pub musixmatch_key: Option<String>,
pub custom_lyrics: Option<Vec<CustomProvider>>,
pub lyrics_on_download: Option<bool>,
pub fx_presets: Option<Vec<serde_json::Value>>,
}
impl Settings {
pub fn rights_ok(&self) -> bool {
self.rights_version == TERMS_VERSION
}
pub fn accept_rights(&mut self) {
self.rights_version = TERMS_VERSION;
self.rights_accepted_at = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs());
}
pub fn revoke_rights(&mut self) {
self.rights_version = 0;
self.rights_accepted_at = None;
}
pub fn apply(&mut self, p: SettingsPatch) {
macro_rules! set {
($($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);
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();
}
if let Some(v) = p.playlists_dir.filter(|v| !v.trim().is_empty()) {
self.playlists_dir = v;
}
if let Some(mut v) = p.lyrics_providers {
for d in default_providers() {
if !v.iter().any(|x| x.id == d.id) {
v.push(d);
}
}
self.lyrics_providers = v;
}
if let Some(v) = p.output_dir.filter(|v| !v.trim().is_empty()) {
self.output_dir = v;
}
if let Some(v) = p.mp3_bitrate {
self.mp3_bitrate = snap_bitrate(v, None);
}
if let Some(v) = p.video_height {
self.video_height = v;
}
if let Some(v) = p.video_container.filter(|v| matches!(v.as_str(), "mp4" | "mkv" | "webm")) {
self.video_container = v;
}
if let Some(v) = p.concurrency {
self.concurrency = v.clamp(1, 8);
}
if let Some(v) = p.filename_template {
self.filename_template = if v.trim().is_empty() { Settings::default().filename_template } else { v };
}
if let Some(v) = p.theme.filter(|v| matches!(v.as_str(), "system" | "light" | "dark")) {
self.theme = v;
}
}
}
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"),
}
}
pub fn load() -> Settings {
let mut s: Settings = std::fs::read_to_string(path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
for d in default_providers() {
if !s.lyrics_providers.iter().any(|x| x.id == d.id) {
s.lyrics_providers.push(d);
}
}
if s.library_folders.is_empty() {
s.library_folders.push(s.output_dir.clone());
}
s
}
pub fn save(s: &Settings) -> Result<()> {
let p = path();
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = p.with_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(s)?)?;
std::fs::rename(&tmp, &p).context("Couldn't save settings")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn snaps_bitrates_to_source() {
assert_eq!(snap_bitrate(320, Some(160)), 160);
assert_eq!(snap_bitrate(320, Some(150)), 128);
assert_eq!(snap_bitrate(192, None), 192);
assert_eq!(snap_bitrate(320, Some(40)), 64);
}
#[test]
fn applies_patches_safely() {
let mut s = Settings::default();
s.apply(SettingsPatch { concurrency: Some(40), theme: Some("neon".into()), mp3_bitrate: Some(200), ..Default::default() });
assert_eq!(s.concurrency, 8);
assert_eq!(s.theme, "system");
assert_eq!(s.mp3_bitrate, 192);
}
}
+144
View File
@@ -0,0 +1,144 @@
// atmosphere · storage.rs · Temp-file hygiene: startup and exit cleanup, stalled partial downloads, orphaned caches and the Storage report.
use crate::engine::{bin_dir, data_dir, temp_root};
use crate::library::Snapshot;
use crate::settings::Settings;
use serde::Serialize;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Item {
pub id: String,
pub label: String,
pub detail: String,
pub bytes: u64,
pub count: usize,
pub cleanable: bool,
}
pub fn is_partial(name: &str) -> bool {
let n = name.to_ascii_lowercase();
n.ends_with(".part") || n.ends_with(".ytdl") || n.contains(".part-frag") || n.contains(".atmosphere-src.") || n.contains(".tagging.") || n.ends_with(".temp") || n.ends_with(".download")
}
fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>, keep: &dyn Fn(&Path) -> bool) {
let Ok(rd) = std::fs::read_dir(dir) else { return };
for e in rd.flatten() {
let p = e.path();
match e.file_type() {
Ok(t) if t.is_dir() && depth > 0 => walk(&p, depth - 1, out, keep),
Ok(t) if t.is_file() && keep(&p) => out.push(p),
_ => {}
}
}
}
fn size(paths: &[PathBuf]) -> u64 {
paths.iter().filter_map(|p| std::fs::metadata(p).ok()).map(|m| m.len()).sum()
}
fn all_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
walk(dir, 6, &mut out, &|_| true);
out
}
fn stalled(settings: &Settings) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut roots: Vec<PathBuf> = vec![PathBuf::from(&settings.output_dir), PathBuf::from(&settings.playlists_dir), bin_dir()];
roots.dedup();
for r in roots {
walk(&r, 4, &mut out, &|p| p.file_name().and_then(|n| n.to_str()).is_some_and(is_partial));
}
out.sort();
out.dedup();
out
}
fn orphan_art(lib: &Snapshot) -> Vec<PathBuf> {
let used: HashSet<String> = lib.tracks.iter().filter_map(|t| t.art.clone()).chain(lib.artists.values().filter_map(|a| a.image.clone())).collect();
let mut out = Vec::new();
walk(&data_dir().join("art"), 0, &mut out, &|p| p.file_stem().and_then(|s| s.to_str()).is_some_and(|s| !used.contains(s)));
out
}
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> {
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: "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 },
Item { id: "engine".into(), label: "Download engine".into(), detail: "yt-dlp and ffmpeg managed by Atmosphere.".into(), bytes: size(&engine), count: engine.len(), cleanable: false },
]
}
fn remove_all(paths: &[PathBuf]) -> (usize, u64) {
let mut n = 0;
let mut bytes = 0;
for p in paths {
let len = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
if std::fs::remove_file(p).is_ok() {
n += 1;
bytes += len;
}
}
(n, bytes)
}
pub fn wipe_temp() -> (usize, u64) {
let files = all_files(&temp_root());
let r = remove_all(&files);
let _ = std::fs::remove_dir_all(temp_root());
r
}
pub fn clean(settings: &Settings, lib: &Snapshot, ids: &[String], busy: bool) -> (usize, u64) {
let mut total = (0, 0);
let mut add = |r: (usize, u64)| {
total.0 += r.0;
total.1 += r.1;
};
for id in ids {
match id.as_str() {
"temp" if !busy => add(wipe_temp()),
"stalled" if !busy => add(remove_all(&stalled(settings))),
"orphan-art" => add(remove_all(&orphan_art(lib))),
"lyrics" => add(remove_all(&all_files(&data_dir().join("lyrics")))),
_ => {}
}
}
total
}
pub fn startup(settings: &Settings) -> (usize, u64) {
let a = wipe_temp();
let b = remove_all(&stalled(settings));
(a.0 + b.0, a.1 + b.1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recognises_partial_files_only() {
for n in ["Song.mp3.part", "x.f251.webm.part-Frag12", "a.ytdl", "03 - Track.atmosphere-src.m4a", "v.tagging.mkv", "yt-dlp.download"] {
assert!(is_partial(n), "{n}");
}
for n in ["Song.mp3", "partner.flac", "cover.jpg", "playlist.m3u8", "Night Drive.lrc"] {
assert!(!is_partial(n), "{n}");
}
}
}
+184
View File
@@ -0,0 +1,184 @@
// atmosphere · tagging.rs · Applies the user's edited metadata and cover art on top of what yt-dlp embedded.
use anyhow::{anyhow, bail, Result};
use lofty::config::WriteOptions;
use lofty::file::{AudioFile, TaggedFileExt};
use lofty::picture::{MimeType, Picture, PictureType};
use lofty::tag::items::Timestamp;
use lofty::tag::{Accessor, ItemKey, Tag};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::process::Stdio;
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Artwork {
#[default]
Keep,
None,
File {
path: String,
},
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TagFields {
pub title: String,
pub artist: String,
pub album: String,
pub album_artist: String,
pub genre: String,
pub date: String,
pub track_number: Option<u32>,
pub track_total: Option<u32>,
pub disc_number: Option<u32>,
pub composer: String,
pub label: String,
pub isrc: String,
pub bpm: Option<u32>,
pub key: String,
pub comment: String,
pub lyrics: String,
pub artwork: Artwork,
}
const LOFTY: [&str; 10] = ["mp3", "m4a", "mp4", "m4v", "flac", "ogg", "opus", "wav", "aiff", "aif"];
fn parse_date(raw: &str) -> Option<Timestamp> {
let raw = raw.trim();
if raw.is_empty() {
return None;
}
raw.parse::<Timestamp>().ok().or_else(|| {
let year = raw.get(..4)?.parse().ok()?;
Some(Timestamp { year, ..Default::default() })
})
}
fn put(tag: &mut Tag, key: ItemKey, value: &str) {
let v = value.trim();
if !v.is_empty() {
tag.insert_text(key, v.to_string());
}
}
fn write_lofty(path: &Path, f: &TagFields, source_url: &str) -> Result<()> {
let mut file = lofty::read_from_path(path)?;
let kind = file.primary_tag_type();
if file.primary_tag().is_none() {
file.insert_tag(Tag::new(kind));
}
let tag = file.primary_tag_mut().ok_or_else(|| anyhow!("no writable tag"))?;
put(tag, ItemKey::TrackTitle, &f.title);
put(tag, ItemKey::TrackArtist, &f.artist);
put(tag, ItemKey::AlbumTitle, &f.album);
put(tag, ItemKey::AlbumArtist, &f.album_artist);
put(tag, ItemKey::Genre, &f.genre);
put(tag, ItemKey::Composer, &f.composer);
put(tag, ItemKey::Label, &f.label);
put(tag, ItemKey::Isrc, &f.isrc);
put(tag, ItemKey::InitialKey, &f.key);
put(tag, ItemKey::Comment, &f.comment);
put(tag, ItemKey::AudioSourceUrl, source_url);
if !f.lyrics.trim().is_empty() {
tag.insert_text(ItemKey::Lyrics, crate::lyrics::plain_text(&f.lyrics));
}
if let Some(bpm) = f.bpm.filter(|b| *b > 0) {
tag.insert_text(ItemKey::IntegerBpm, bpm.to_string());
}
if let Some(date) = parse_date(&f.date) {
tag.set_date(date);
}
if let Some(n) = f.track_number {
tag.set_track(n);
}
if let Some(total) = f.track_total {
tag.set_track_total(total);
}
if let Some(disc) = f.disc_number {
tag.set_disk(disc);
}
match &f.artwork {
Artwork::Keep => {}
Artwork::None => {
while !tag.pictures().is_empty() {
tag.remove_picture(0);
}
}
Artwork::File { path } => {
let data = std::fs::read(path).map_err(|e| anyhow!("couldn't read the cover image ({e})"))?;
let mime = if data.starts_with(&[0x89, b'P', b'N', b'G']) { MimeType::Png } else { MimeType::Jpeg };
while !tag.pictures().is_empty() {
tag.remove_picture(0);
}
tag.push_picture(Picture::unchecked(data).pic_type(PictureType::CoverFront).mime_type(mime).build());
}
}
file.save_to_path(path, WriteOptions::default())?;
Ok(())
}
async fn write_ffmpeg(ffmpeg: &Path, path: &Path, f: &TagFields) -> Result<()> {
let pairs = [
("title", f.title.clone()),
("artist", f.artist.clone()),
("album", f.album.clone()),
("album_artist", f.album_artist.clone()),
("genre", f.genre.clone()),
("date", f.date.clone()),
("composer", f.composer.clone()),
("comment", f.comment.clone()),
("track", f.track_number.map(|n| n.to_string()).unwrap_or_default()),
];
let meta: Vec<(&str, String)> = pairs.into_iter().filter(|(_, v)| !v.trim().is_empty()).collect();
if meta.is_empty() {
return Ok(());
}
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("mkv");
let tmp: PathBuf = path.with_extension(format!("tagging.{ext}"));
let mut cmd = crate::engine::command(ffmpeg);
cmd.args(["-y", "-v", "error", "-i"]).arg(path).args(["-map", "0", "-c", "copy"]);
for (k, v) in &meta {
cmd.arg("-metadata").arg(format!("{k}={}", v.trim()));
}
let out = cmd.arg(&tmp).stdout(Stdio::null()).stderr(Stdio::piped()).output().await?;
if !out.status.success() {
let _ = tokio::fs::remove_file(&tmp).await;
bail!("{}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("ffmpeg failed"));
}
tokio::fs::rename(&tmp, path).await?;
Ok(())
}
pub async fn apply(path: &Path, f: &TagFields, source_url: &str, ffmpeg: Option<&Path>) -> Result<()> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();
if LOFTY.contains(&ext.as_str()) {
let (path, f, url) = (path.to_path_buf(), f.clone(), source_url.to_string());
return tokio::task::spawn_blocking(move || write_lofty(&path, &f, &url)).await?;
}
match ffmpeg {
Some(ff) => write_ffmpeg(ff, path, f).await,
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_dates() {
assert_eq!(parse_date("2021").unwrap().year, 2021);
let full = parse_date("2019-04-12").unwrap();
assert_eq!((full.year, full.month, full.day), (2019, Some(4), Some(12)));
assert!(parse_date(" ").is_none());
}
#[test]
fn artwork_defaults_to_keep() {
let f: TagFields = serde_json::from_str(r#"{"title":"x"}"#).unwrap();
assert!(matches!(f.artwork, Artwork::Keep));
let f: TagFields = serde_json::from_str(r#"{"artwork":{"kind":"file","path":"c.jpg"}}"#).unwrap();
assert!(matches!(f.artwork, Artwork::File { .. }));
}
}