mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Discord Rich Presence, album folder moves and TheAudioDB logos
- Discord: listening status with cover, artist and progress; choose what your status names; optional own Discord app with a Save the images button - Songs given an album move from Tracks into that album's folder with their lyrics and video; single downloads join an existing album folder - Artist logos, photos and bios from TheAudioDB too, with logos in the Search online picker
This commit is contained in:
+112
-14
@@ -1,4 +1,4 @@
|
||||
// atmosphere · artistinfo.rs · Finds artist photos, bios and logos from keyless public sources: Deezer, Wikipedia and Wikidata
|
||||
// atmosphere · artistinfo.rs · Finds artist photos, bios and logos from keyless public sources: Deezer, Wikipedia, Wikidata and TheAudioDB
|
||||
use anyhow::Result;
|
||||
use base64::Engine as _;
|
||||
use regex::Regex;
|
||||
@@ -7,6 +7,7 @@ use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_IMAGE: usize = 8 * 1024 * 1024;
|
||||
const AUDIODB: &str = "https://www.theaudiodb.com/api/v1/json/123";
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Found {
|
||||
@@ -34,7 +35,7 @@ fn title_matches(key: &str, name: &str) -> bool {
|
||||
norm(base) == norm(name)
|
||||
}
|
||||
|
||||
async fn get_json(http: &reqwest::Client, url: &str) -> Option<Value> {
|
||||
pub(crate) async fn get_json(http: &reqwest::Client, url: &str) -> Option<Value> {
|
||||
let r = http.get(url).timeout(Duration::from_secs(15)).send().await.ok()?;
|
||||
if !r.status().is_success() {
|
||||
return None;
|
||||
@@ -51,7 +52,7 @@ async fn get_bytes(http: &reqwest::Client, url: &str) -> Option<Vec<u8>> {
|
||||
(b.len() <= MAX_IMAGE && !b.is_empty()).then(|| b.to_vec())
|
||||
}
|
||||
|
||||
fn enc(s: &str) -> String {
|
||||
pub(crate) fn enc(s: &str) -> String {
|
||||
url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
|
||||
}
|
||||
|
||||
@@ -103,6 +104,39 @@ async fn wikidata_file(http: &reqwest::Client, qid: &str, prop: &str) -> Option<
|
||||
get_bytes(http, &format!("https://commons.wikimedia.org/wiki/Special:FilePath/{}?width=800", path_enc(file))).await
|
||||
}
|
||||
|
||||
struct AudioDb {
|
||||
id: String,
|
||||
logo: Option<String>,
|
||||
thumb: Option<String>,
|
||||
bio: Option<String>,
|
||||
}
|
||||
|
||||
fn audiodb_entry(a: &Value) -> Option<AudioDb> {
|
||||
let url = |k: &str| a[k].as_str().filter(|u| u.starts_with("https://")).map(String::from);
|
||||
Some(AudioDb { id: a["idArtist"].as_str()?.to_string(), logo: url("strArtistLogo"), thumb: url("strArtistThumb"), bio: a["strBiographyEN"].as_str().map(str::trim).filter(|b| b.len() >= 40).map(String::from) })
|
||||
}
|
||||
|
||||
async fn audiodb_search(http: &reqwest::Client, query: &str) -> Vec<Value> {
|
||||
get_json(http, &format!("{AUDIODB}/search.php?s={}", enc(query))).await.and_then(|v| v["artists"].as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn audiodb(http: &reqwest::Client, name: &str) -> Option<AudioDb> {
|
||||
let want = norm(name);
|
||||
audiodb_search(http, name).await.iter().find(|a| a["strArtist"].as_str().is_some_and(|n| norm(n) == want)).and_then(audiodb_entry)
|
||||
}
|
||||
|
||||
pub fn audiodb_page(id: &str) -> String {
|
||||
format!("https://www.theaudiodb.com/artist/{id}")
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LogoChoice {
|
||||
pub name: String,
|
||||
pub thumb: String,
|
||||
pub full: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PhotoChoice {
|
||||
@@ -121,7 +155,7 @@ pub struct PageChoice {
|
||||
pub music: bool,
|
||||
}
|
||||
|
||||
pub async fn choices(http: &reqwest::Client, query: &str) -> (Vec<PhotoChoice>, Vec<PageChoice>) {
|
||||
pub async fn choices(http: &reqwest::Client, query: &str) -> (Vec<PhotoChoice>, Vec<PageChoice>, Vec<LogoChoice>) {
|
||||
let q = enc(query);
|
||||
let photos = async {
|
||||
let Some(v) = get_json(http, &format!("https://api.deezer.com/search/artist?q={q}&limit=12")).await else { return Vec::new() };
|
||||
@@ -151,31 +185,59 @@ pub async fn choices(http: &reqwest::Client, query: &str) -> (Vec<PhotoChoice>,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (mut photos, pages) = tokio::join!(photos, pages);
|
||||
let thumbs = futures_util::future::join_all(photos.iter().map(|p| get_bytes(http, &p.thumb))).await;
|
||||
let logos = async {
|
||||
audiodb_search(http, query)
|
||||
.await
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
let full = a["strArtistLogo"].as_str().filter(|u| allowed_logo(u))?.to_string();
|
||||
Some(LogoChoice { name: a["strArtist"].as_str()?.to_string(), thumb: format!("{full}/preview"), full })
|
||||
})
|
||||
.take(8)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (mut photos, pages, mut logos) = tokio::join!(photos, pages, logos);
|
||||
let b64 = |b: Vec<u8>, mime: &str| format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(b));
|
||||
let (thumbs, logo_thumbs) = tokio::join!(
|
||||
futures_util::future::join_all(photos.iter().map(|p| get_bytes(http, &p.thumb))),
|
||||
futures_util::future::join_all(logos.iter().map(|l| async { match get_bytes(http, &l.thumb).await { Some(b) => Some(b), None => get_bytes(http, &l.full).await } }))
|
||||
);
|
||||
for (p, bytes) in photos.iter_mut().zip(thumbs) {
|
||||
p.thumb = bytes.map(|b| format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(b))).unwrap_or_default();
|
||||
p.thumb = bytes.map(|b| b64(b, "image/jpeg")).unwrap_or_default();
|
||||
}
|
||||
for (l, bytes) in logos.iter_mut().zip(logo_thumbs) {
|
||||
l.thumb = bytes.map(|b| b64(b, "image/png")).unwrap_or_default();
|
||||
}
|
||||
photos.retain(|p| !p.thumb.is_empty());
|
||||
(photos, pages)
|
||||
logos.retain(|l| !l.thumb.is_empty());
|
||||
(photos, pages, logos)
|
||||
}
|
||||
|
||||
pub fn allowed_logo(url: &str) -> bool {
|
||||
url::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some_and(|h| h == "theaudiodb.com" || h.ends_with(".theaudiodb.com")))
|
||||
}
|
||||
|
||||
pub fn allowed_photo(url: &str) -> bool {
|
||||
url::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some_and(|h| h.ends_with(".dzcdn.net")))
|
||||
}
|
||||
|
||||
pub async fn chosen(http: &reqwest::Client, photo: Option<&str>, page: Option<&str>) -> Found {
|
||||
pub async fn chosen(http: &reqwest::Client, photo: Option<&str>, page: Option<&str>, logo: Option<&str>) -> Found {
|
||||
let mut found = Found::default();
|
||||
if let Some(url) = photo.filter(|u| allowed_photo(u)) {
|
||||
found.photo = get_bytes(http, url).await;
|
||||
}
|
||||
if let Some(url) = logo.filter(|u| allowed_logo(u)) {
|
||||
found.logo = get_bytes(http, url).await;
|
||||
}
|
||||
if let Some(key) = page.filter(|k| !k.is_empty() && k.len() < 300 && !k.contains('/')) {
|
||||
if let Some(s) = get_json(http, &format!("https://en.wikipedia.org/api/rest_v1/page/summary/{}", path_enc(key))).await {
|
||||
if s["type"].as_str() == Some("standard") {
|
||||
found.bio = s["extract"].as_str().map(|t| t.trim().to_string());
|
||||
found.bio_source = s["content_urls"]["desktop"]["page"].as_str().map(String::from);
|
||||
if let Some(q) = s["wikibase_item"].as_str() {
|
||||
found.logo = wikidata_file(http, q, "P154").await;
|
||||
if logo.is_none() {
|
||||
found.logo = wikidata_file(http, q, "P154").await;
|
||||
}
|
||||
if found.photo.is_none() && photo.is_none() {
|
||||
found.photo = wikidata_file(http, q, "P18").await;
|
||||
}
|
||||
@@ -202,15 +264,29 @@ pub async fn find(http: &reqwest::Client, name: &str, want_photo: bool, want_bio
|
||||
None
|
||||
}
|
||||
};
|
||||
let (photo, wiki) = tokio::join!(photo, wiki);
|
||||
let adb = async {
|
||||
if want_logo || want_photo || want_bio {
|
||||
audiodb(http, name).await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let (photo, wiki, adb) = tokio::join!(photo, wiki, adb);
|
||||
found.photo = photo;
|
||||
if let Some(a) = &adb {
|
||||
if want_logo {
|
||||
if let Some(u) = a.logo.as_deref() {
|
||||
found.logo = get_bytes(http, u).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((bio, url, qid)) = wiki {
|
||||
if want_bio {
|
||||
found.bio = Some(bio);
|
||||
found.bio_source = Some(url);
|
||||
}
|
||||
if let Some(q) = qid {
|
||||
if want_logo {
|
||||
if want_logo && found.logo.is_none() {
|
||||
found.logo = wikidata_file(http, &q, "P154").await;
|
||||
}
|
||||
if want_photo && found.photo.is_none() {
|
||||
@@ -218,6 +294,17 @@ pub async fn find(http: &reqwest::Client, name: &str, want_photo: bool, want_bio
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(a) = adb {
|
||||
if want_photo && found.photo.is_none() {
|
||||
if let Some(u) = a.thumb.as_deref() {
|
||||
found.photo = get_bytes(http, u).await;
|
||||
}
|
||||
}
|
||||
if want_bio && found.bio.is_none() {
|
||||
found.bio = a.bio;
|
||||
found.bio_source = Some(audiodb_page(&a.id));
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
@@ -241,6 +328,13 @@ mod tests {
|
||||
assert!(!allowed_photo("http://cdn-images.dzcdn.net/x.jpg"));
|
||||
assert!(!allowed_photo("https://evil.example/dzcdn.net.jpg"));
|
||||
assert!(!allowed_photo("file:///C:/Windows/win.ini"));
|
||||
assert!(allowed_logo("https://r2.TheAudioDB.com/images/media/artist/logo/x.png"));
|
||||
assert!(allowed_logo("https://www.theaudiodb.com/images/media/artist/logo/x.png"));
|
||||
assert!(!allowed_logo("https://theaudiodb.com.evil.example/x.png"));
|
||||
assert!(!allowed_logo("http://www.theaudiodb.com/x.png"));
|
||||
let a = audiodb_entry(&serde_json::json!({ "idArtist": "111", "strArtistLogo": "https://r2.theaudiodb.com/l.png", "strArtistThumb": null, "strBiographyEN": "short" })).unwrap();
|
||||
assert_eq!(a.logo.as_deref(), Some("https://r2.theaudiodb.com/l.png"));
|
||||
assert!(a.thumb.is_none() && a.bio.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -248,8 +342,12 @@ mod tests {
|
||||
async fn live_choices_include_photos() {
|
||||
let http = reqwest::Client::builder().user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION"))).build().unwrap();
|
||||
for q in ["Daft Punk", "Drake", "Taylor Swift", "Westwood"] {
|
||||
let (photos, pages) = choices(&http, q).await;
|
||||
eprintln!("{q}: {} photos, {} pages", photos.len(), pages.len());
|
||||
let (photos, pages, logos) = choices(&http, q).await;
|
||||
eprintln!("{q}: {} photos, {} pages, {} logos", photos.len(), pages.len(), logos.len());
|
||||
assert!(logos.iter().all(|l| l.thumb.starts_with("data:image/png;base64,") && allowed_logo(&l.full)));
|
||||
if q != "Westwood" {
|
||||
assert!(!logos.is_empty(), "no logos for {q}");
|
||||
}
|
||||
assert!(!photos.is_empty(), "no photos for {q}");
|
||||
assert!(photos.iter().all(|p| p.thumb.starts_with("data:image/jpeg;base64,") && p.full.starts_with("https://")));
|
||||
}
|
||||
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
// atmosphere · discord.rs · Optional Discord Rich Presence over Discord's local IPC socket, plus the art assets for your own Discord app
|
||||
use crate::settings::Settings;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{timeout, Instant};
|
||||
|
||||
pub const BUILTIN_CLIENT_ID: &str = "";
|
||||
pub const ASSET_LOGO: &str = "atmosphere";
|
||||
pub const ASSET_PAUSED: &str = "paused";
|
||||
const LOGO_PNG: &[u8] = include_bytes!("../icons/icon.png");
|
||||
const SEND_GAP: Duration = Duration::from_secs(4);
|
||||
const RETRY: Duration = Duration::from_secs(15);
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NowPlaying {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub duration_ms: u64,
|
||||
pub position_ms: u64,
|
||||
pub playing: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Options {
|
||||
pub enabled: bool,
|
||||
pub client_id: String,
|
||||
pub cover: bool,
|
||||
pub paused: bool,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
pub fn from(s: &Settings) -> Self {
|
||||
let own = s.discord_client_id.trim();
|
||||
Self {
|
||||
enabled: s.discord_enabled,
|
||||
client_id: if own.is_empty() { BUILTIN_CLIENT_ID.to_string() } else { own.to_string() },
|
||||
cover: s.discord_cover,
|
||||
paused: s.discord_paused,
|
||||
status: s.discord_status.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Status {
|
||||
pub state: String,
|
||||
pub user: Option<String>,
|
||||
pub error: Option<String>,
|
||||
pub builtin_id: bool,
|
||||
}
|
||||
|
||||
enum Msg {
|
||||
Now(Option<NowPlaying>),
|
||||
Opts(Options),
|
||||
}
|
||||
|
||||
pub struct DiscordHub {
|
||||
tx: mpsc::UnboundedSender<Msg>,
|
||||
status: Arc<Mutex<Status>>,
|
||||
}
|
||||
|
||||
impl DiscordHub {
|
||||
pub fn start(app: AppHandle, http: reqwest::Client, opts: Options) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let status = Arc::new(Mutex::new(Status { state: "off".into(), builtin_id: !BUILTIN_CLIENT_ID.is_empty(), ..Default::default() }));
|
||||
let worker = Worker { app, http, status: status.clone(), opts, now: None, conn: None, covers: HashMap::new(), nonce: 0 };
|
||||
tauri::async_runtime::spawn(worker.run(rx));
|
||||
Self { tx, status }
|
||||
}
|
||||
|
||||
pub fn now_playing(&self, now: Option<NowPlaying>) {
|
||||
let _ = self.tx.send(Msg::Now(now));
|
||||
}
|
||||
|
||||
pub fn configure(&self, opts: Options) {
|
||||
let _ = self.tx.send(Msg::Opts(opts));
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Status {
|
||||
self.status.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
|
||||
|
||||
struct Conn {
|
||||
io: Box<dyn Io>,
|
||||
client_id: String,
|
||||
}
|
||||
|
||||
enum Fail {
|
||||
NotRunning,
|
||||
Rejected(String),
|
||||
Broken,
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
app: AppHandle,
|
||||
http: reqwest::Client,
|
||||
status: Arc<Mutex<Status>>,
|
||||
opts: Options,
|
||||
now: Option<NowPlaying>,
|
||||
conn: Option<Conn>,
|
||||
covers: HashMap<String, Option<String>>,
|
||||
nonce: u64,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Msg>) {
|
||||
let mut dirty = true;
|
||||
let mut ready = Instant::now();
|
||||
let mut last = Instant::now().checked_sub(SEND_GAP).unwrap_or_else(Instant::now);
|
||||
loop {
|
||||
let msg = if dirty {
|
||||
match timeout_at(ready, rx.recv()).await {
|
||||
Ok(None) => break,
|
||||
Ok(Some(m)) => Some(m),
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
match rx.recv().await {
|
||||
None => break,
|
||||
m => m,
|
||||
}
|
||||
};
|
||||
match msg {
|
||||
Some(Msg::Now(n)) => {
|
||||
if n == self.now {
|
||||
continue;
|
||||
}
|
||||
self.now = n;
|
||||
dirty = true;
|
||||
ready = ready.max(last + SEND_GAP).max(Instant::now());
|
||||
}
|
||||
Some(Msg::Opts(o)) => {
|
||||
if o == self.opts {
|
||||
continue;
|
||||
}
|
||||
if o.client_id != self.opts.client_id || !o.enabled {
|
||||
self.conn = None;
|
||||
}
|
||||
self.opts = o;
|
||||
dirty = true;
|
||||
ready = Instant::now();
|
||||
}
|
||||
None => match self.flush().await {
|
||||
Ok(()) => {
|
||||
dirty = false;
|
||||
last = Instant::now();
|
||||
}
|
||||
Err(wait) => ready = Instant::now() + wait,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_status(&self, state: &str, user: Option<String>, error: Option<String>) {
|
||||
let s = Status { state: state.into(), user, error, builtin_id: !BUILTIN_CLIENT_ID.is_empty() };
|
||||
let changed = {
|
||||
let mut cur = self.status.lock().unwrap();
|
||||
let changed = (cur.state.as_str(), &cur.user, &cur.error) != (s.state.as_str(), &s.user, &s.error);
|
||||
*cur = s.clone();
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
let _ = self.app.emit("atmosphere://discord", s);
|
||||
}
|
||||
}
|
||||
|
||||
async fn flush(&mut self) -> Result<(), Duration> {
|
||||
if !self.opts.enabled {
|
||||
self.conn = None;
|
||||
self.set_status("off", None, None);
|
||||
return Ok(());
|
||||
}
|
||||
if self.opts.client_id.is_empty() {
|
||||
self.conn = None;
|
||||
self.set_status("noid", None, None);
|
||||
return Ok(());
|
||||
}
|
||||
if self.conn.as_ref().is_some_and(|c| c.client_id != self.opts.client_id) {
|
||||
self.conn = None;
|
||||
}
|
||||
if self.conn.is_none() {
|
||||
self.set_status("connecting", None, None);
|
||||
match connect(&self.opts.client_id).await {
|
||||
Ok((conn, user)) => {
|
||||
self.conn = Some(conn);
|
||||
self.set_status("connected", user, None);
|
||||
}
|
||||
Err(Fail::NotRunning) => {
|
||||
self.set_status("waiting", None, None);
|
||||
return Err(RETRY);
|
||||
}
|
||||
Err(Fail::Rejected(e)) => {
|
||||
self.set_status("error", None, Some(e));
|
||||
return Err(RETRY * 4);
|
||||
}
|
||||
Err(Fail::Broken) => {
|
||||
self.set_status("waiting", None, None);
|
||||
return Err(RETRY);
|
||||
}
|
||||
}
|
||||
}
|
||||
let wanted = match (&self.now, self.opts.cover) {
|
||||
(Some(n), true) if !n.title.trim().is_empty() => Some((n.artist.clone(), n.title.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let cover = match wanted {
|
||||
Some((artist, title)) => self.cover_for(&artist, &title).await,
|
||||
None => None,
|
||||
};
|
||||
let act = self.now.as_ref().and_then(|n| activity(&self.opts, n, cover.as_deref(), now_ms()));
|
||||
self.nonce += 1;
|
||||
let frame = json!({ "cmd": "SET_ACTIVITY", "args": { "pid": std::process::id(), "activity": act }, "nonce": self.nonce.to_string() });
|
||||
let conn = self.conn.as_mut().expect("connected");
|
||||
let sent = async {
|
||||
write_frame(&mut conn.io, 1, &frame).await.ok()?;
|
||||
read_frame(&mut conn.io).await.ok()
|
||||
};
|
||||
match timeout(Duration::from_secs(5), sent).await {
|
||||
Ok(Some((_, reply))) if reply["evt"] == "ERROR" => {
|
||||
let msg = reply["data"]["message"].as_str().unwrap_or("Discord didn't accept the status").to_string();
|
||||
let user = self.status.lock().unwrap().user.clone();
|
||||
self.set_status("connected", user, Some(msg));
|
||||
Ok(())
|
||||
}
|
||||
Ok(Some(_)) => {
|
||||
let user = self.status.lock().unwrap().user.clone();
|
||||
self.set_status("connected", user, None);
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
self.conn = None;
|
||||
self.set_status("waiting", None, None);
|
||||
Err(Duration::from_secs(2))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn cover_for(&mut self, artist: &str, title: &str) -> Option<String> {
|
||||
let key = format!("{}\u{1}{}", crate::artistinfo::norm(artist), crate::artistinfo::norm(title));
|
||||
if let Some(hit) = self.covers.get(&key) {
|
||||
return hit.clone();
|
||||
}
|
||||
let first = artist.split([',', '&']).next().unwrap_or(artist).trim();
|
||||
let q = if first.is_empty() { format!("track:\"{title}\"") } else { format!("artist:\"{first}\" track:\"{title}\"") };
|
||||
let url = format!("https://api.deezer.com/search?limit=5&q={}", crate::artistinfo::enc(&q));
|
||||
let found = match timeout(Duration::from_secs(6), crate::artistinfo::get_json(&self.http, &url)).await {
|
||||
Ok(Some(v)) => pick_cover(&v, first),
|
||||
Ok(None) => None,
|
||||
Err(_) => return None,
|
||||
};
|
||||
self.covers.insert(key, found.clone());
|
||||
found
|
||||
}
|
||||
}
|
||||
|
||||
async fn timeout_at<F: std::future::Future>(at: Instant, f: F) -> Result<F::Output, tokio::time::error::Elapsed> {
|
||||
tokio::time::timeout_at(at, f).await
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn pick_cover(v: &Value, artist: &str) -> Option<String> {
|
||||
let want = crate::artistinfo::norm(artist);
|
||||
v["data"].as_array()?.iter().find_map(|t| {
|
||||
let name = crate::artistinfo::norm(t["artist"]["name"].as_str().unwrap_or_default());
|
||||
let ok = want.is_empty() || name == want || name.contains(&want) || want.contains(&name);
|
||||
let url = t["album"]["cover_xl"].as_str().or_else(|| t["album"]["cover_big"].as_str())?;
|
||||
(ok && url.starts_with("https://")).then(|| url.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn fit(s: &str) -> Option<String> {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut out: String = s.chars().take(128).collect();
|
||||
if s.chars().count() > 128 {
|
||||
out = out.chars().take(127).collect::<String>() + "…";
|
||||
}
|
||||
while out.chars().count() < 2 {
|
||||
out.push('\u{2800}');
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn activity(opts: &Options, now: &NowPlaying, cover: Option<&str>, at_ms: u64) -> Option<Value> {
|
||||
if !now.playing && !opts.paused {
|
||||
return None;
|
||||
}
|
||||
let title = fit(&now.title).unwrap_or_else(|| "Unknown song".into());
|
||||
let mut a = json!({
|
||||
"type": 2,
|
||||
"details": title,
|
||||
"status_display_type": match opts.status.as_str() { "artist" => 1, "song" => 2, _ => 0 },
|
||||
});
|
||||
if let Some(artist) = fit(&now.artist) {
|
||||
a["state"] = json!(artist);
|
||||
}
|
||||
let mut assets = json!({ "large_image": cover.unwrap_or(ASSET_LOGO) });
|
||||
if let Some(album) = fit(&now.album) {
|
||||
assets["large_text"] = json!(album);
|
||||
}
|
||||
if !now.playing {
|
||||
assets["small_image"] = json!(ASSET_PAUSED);
|
||||
assets["small_text"] = json!("Paused");
|
||||
} else if cover.is_some() {
|
||||
assets["small_image"] = json!(ASSET_LOGO);
|
||||
assets["small_text"] = json!("Atmosphere");
|
||||
}
|
||||
a["assets"] = assets;
|
||||
if now.playing {
|
||||
let start = at_ms.saturating_sub(now.position_ms);
|
||||
let mut ts = json!({ "start": start });
|
||||
if now.duration_ms > now.position_ms {
|
||||
ts["end"] = json!(start + now.duration_ms);
|
||||
}
|
||||
a["timestamps"] = ts;
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
|
||||
async fn write_frame(io: &mut Box<dyn Io>, op: u32, v: &Value) -> std::io::Result<()> {
|
||||
let body = serde_json::to_vec(v)?;
|
||||
let mut buf = Vec::with_capacity(body.len() + 8);
|
||||
buf.extend(op.to_le_bytes());
|
||||
buf.extend((body.len() as u32).to_le_bytes());
|
||||
buf.extend(body);
|
||||
io.write_all(&buf).await?;
|
||||
io.flush().await
|
||||
}
|
||||
|
||||
async fn read_frame(io: &mut Box<dyn Io>) -> std::io::Result<(u32, Value)> {
|
||||
let mut head = [0u8; 8];
|
||||
io.read_exact(&mut head).await?;
|
||||
let op = u32::from_le_bytes(head[..4].try_into().unwrap());
|
||||
let len = u32::from_le_bytes(head[4..].try_into().unwrap()) as usize;
|
||||
if len > 1 << 20 {
|
||||
return Err(std::io::Error::other("frame too large"));
|
||||
}
|
||||
let mut body = vec![0u8; len];
|
||||
io.read_exact(&mut body).await?;
|
||||
Ok((op, serde_json::from_slice(&body).unwrap_or(Value::Null)))
|
||||
}
|
||||
|
||||
async fn open_socket() -> Option<Box<dyn Io>> {
|
||||
#[cfg(windows)]
|
||||
for i in 0..10 {
|
||||
if let Ok(p) = tokio::net::windows::named_pipe::ClientOptions::new().open(format!(r"\\.\pipe\discord-ipc-{i}")) {
|
||||
return Some(Box::new(p));
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut dirs: Vec<std::path::PathBuf> = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"].iter().filter_map(|k| std::env::var_os(k).map(Into::into)).collect();
|
||||
dirs.push("/tmp".into());
|
||||
for dir in dirs {
|
||||
for sub in ["", "app/com.discordapp.Discord", "snap.discord", ".flatpak/dev.vencord.Vesktop/xdg-run"] {
|
||||
for i in 0..10 {
|
||||
let path = dir.join(sub).join(format!("discord-ipc-{i}"));
|
||||
if let Ok(s) = tokio::net::UnixStream::connect(&path).await {
|
||||
return Some(Box::new(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn connect(client_id: &str) -> Result<(Conn, Option<String>), Fail> {
|
||||
let mut io = open_socket().await.ok_or(Fail::NotRunning)?;
|
||||
let hello = async {
|
||||
write_frame(&mut io, 0, &json!({ "v": 1, "client_id": client_id })).await.ok()?;
|
||||
read_frame(&mut io).await.ok()
|
||||
};
|
||||
let (op, reply) = timeout(Duration::from_secs(5), hello).await.ok().flatten().ok_or(Fail::Broken)?;
|
||||
if op == 2 || reply["evt"] == "ERROR" {
|
||||
let msg = reply["message"].as_str().or_else(|| reply["data"]["message"].as_str()).unwrap_or("Discord refused the connection");
|
||||
let friendly = if msg.to_lowercase().contains("client id") { "Discord doesn't recognise that application ID. Check it in the Discord Developer Portal." } else { msg };
|
||||
return Err(Fail::Rejected(friendly.to_string()));
|
||||
}
|
||||
let u = &reply["data"]["user"];
|
||||
let user = u["global_name"].as_str().filter(|s| !s.is_empty()).or_else(|| u["username"].as_str()).map(str::to_string);
|
||||
Ok((Conn { io, client_id: client_id.to_string() }, user))
|
||||
}
|
||||
|
||||
fn badge_png(size: u32) -> Vec<u8> {
|
||||
let (bg, fg) = ([0x4bu8, 0x52, 0xd6], [255u8, 255, 255]);
|
||||
let s = size as f32;
|
||||
let (cx, r) = (s / 2.0, s / 2.0);
|
||||
let (bar_w, bar_h, gap) = (s * 0.11, s * 0.40, s * 0.10);
|
||||
let in_bar = |x: f32, y: f32| {
|
||||
let top = cx - bar_h / 2.0;
|
||||
let left = cx - gap / 2.0 - bar_w;
|
||||
let right = cx + gap / 2.0;
|
||||
(top..top + bar_h).contains(&y) && ((left..left + bar_w).contains(&x) || (right..right + bar_w).contains(&x))
|
||||
};
|
||||
let mut img = image::RgbaImage::new(size, size);
|
||||
const N: u32 = 4;
|
||||
for (px, py, p) in img.enumerate_pixels_mut() {
|
||||
let (mut circle, mut glyph) = (0u32, 0u32);
|
||||
for sy in 0..N {
|
||||
for sx in 0..N {
|
||||
let x = px as f32 + (sx as f32 + 0.5) / N as f32;
|
||||
let y = py as f32 + (sy as f32 + 0.5) / N as f32;
|
||||
if (x - cx).powi(2) + (y - cx).powi(2) <= r * r {
|
||||
circle += 1;
|
||||
if in_bar(x, y) {
|
||||
glyph += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if circle == 0 {
|
||||
continue;
|
||||
}
|
||||
let t = glyph as f32 / circle as f32;
|
||||
let mix = |i: usize| (bg[i] as f32 * (1.0 - t) + fg[i] as f32 * t).round() as u8;
|
||||
*p = image::Rgba([mix(0), mix(1), mix(2), (circle * 255 / (N * N)) as u8]);
|
||||
}
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).expect("png");
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
const SETUP_NOTES: &str = "Atmosphere on Discord: using your own Discord application
|
||||
|
||||
1. Open https://discord.com/developers/applications and choose New Application.
|
||||
The name you give it is what Discord shows as \"Listening to <name>\".
|
||||
2. On the application's General Information page, copy the Application ID
|
||||
and paste it into Atmosphere > Settings > Discord > Your own Discord app.
|
||||
3. Open Rich Presence > Art Assets and upload both images from this folder.
|
||||
Keep their names exactly as they are (atmosphere and paused), because
|
||||
Atmosphere asks Discord for them by name.
|
||||
4. New art can take a few minutes to show up on Discord.
|
||||
";
|
||||
|
||||
pub fn write_assets(dir: &Path) -> anyhow::Result<Vec<String>> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let files = [(format!("{ASSET_LOGO}.png"), LOGO_PNG.to_vec()), (format!("{ASSET_PAUSED}.png"), badge_png(1024)), ("How to set up.txt".to_string(), SETUP_NOTES.as_bytes().to_vec())];
|
||||
let mut written = Vec::new();
|
||||
for (name, bytes) in files {
|
||||
let path = dir.join(&name);
|
||||
std::fs::write(&path, bytes)?;
|
||||
written.push(path.to_string_lossy().into_owned());
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn opts() -> Options {
|
||||
Options { enabled: true, client_id: "1".into(), cover: true, paused: true, status: "app".into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_a_listening_activity_with_a_progress_bar() {
|
||||
let now = NowPlaying { title: "Get Lucky".into(), artist: "Daft Punk".into(), album: "Random Access Memories".into(), duration_ms: 248_000, position_ms: 8_000, playing: true };
|
||||
let a = activity(&opts(), &now, Some("https://cdn/x.jpg"), 1_000_000).unwrap();
|
||||
assert_eq!(a["type"], 2);
|
||||
assert_eq!(a["details"], "Get Lucky");
|
||||
assert_eq!(a["state"], "Daft Punk");
|
||||
assert_eq!(a["timestamps"]["start"], 992_000);
|
||||
assert_eq!(a["timestamps"]["end"], 1_240_000);
|
||||
assert_eq!(a["assets"]["large_image"], "https://cdn/x.jpg");
|
||||
assert_eq!(a["assets"]["small_image"], ASSET_LOGO);
|
||||
assert_eq!(a["status_display_type"], 0);
|
||||
|
||||
let paused = NowPlaying { playing: false, ..now.clone() };
|
||||
let p = activity(&Options { status: "artist".into(), ..opts() }, &paused, None, 1_000_000).unwrap();
|
||||
assert!(p.get("timestamps").is_none());
|
||||
assert_eq!(p["assets"]["large_image"], ASSET_LOGO);
|
||||
assert_eq!(p["assets"]["small_image"], ASSET_PAUSED);
|
||||
assert_eq!(p["status_display_type"], 1);
|
||||
assert!(activity(&Options { paused: false, ..opts() }, &paused, None, 0).is_none());
|
||||
|
||||
let short = NowPlaying { title: "X".into(), artist: String::new(), album: "A".repeat(300), ..Default::default() };
|
||||
let s = activity(&opts(), &short, None, 0).unwrap();
|
||||
assert_eq!(s["details"].as_str().unwrap().chars().count(), 2);
|
||||
assert!(s.get("state").is_none());
|
||||
assert_eq!(s["assets"]["large_text"].as_str().unwrap().chars().count(), 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_a_cover_only_from_the_same_artist() {
|
||||
let v = json!({ "data": [
|
||||
{ "artist": { "name": "Someone Else" }, "album": { "cover_xl": "https://e/1.jpg" } },
|
||||
{ "artist": { "name": "Daft Punk" }, "album": { "cover_xl": "https://e/2.jpg" } }
|
||||
]});
|
||||
assert_eq!(pick_cover(&v, "Daft Punk").as_deref(), Some("https://e/2.jpg"));
|
||||
assert_eq!(pick_cover(&json!({ "data": [v["data"][0].clone()] }), "Daft Punk"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn live_discord_refuses_an_unknown_app() {
|
||||
match connect("100000000000000001").await {
|
||||
Err(Fail::Rejected(msg)) => eprintln!("refused: {msg}"),
|
||||
Err(Fail::NotRunning) => panic!("Discord isn't running"),
|
||||
Err(Fail::Broken) => panic!("no reply"),
|
||||
Ok(_) => panic!("accepted a made-up app"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_the_art_assets() {
|
||||
let dir = std::env::temp_dir().join(format!("atmo-discord-{}", std::process::id()));
|
||||
let files = write_assets(&dir).unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
let badge = image::open(dir.join("paused.png")).unwrap();
|
||||
assert_eq!((badge.width(), badge.height()), (1024, 1024));
|
||||
let logo = image::open(dir.join("atmosphere.png")).unwrap();
|
||||
assert!(logo.width() >= 512);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -733,10 +733,19 @@ pub fn target_dir(settings: &Settings, req: &JobRequest) -> PathBuf {
|
||||
if settings.playlists_dir.trim().is_empty() { base.join("Playlists") } else { lists }.join(sanitize(name))
|
||||
}
|
||||
(None, Some(name)) => base.join(sanitize(name)),
|
||||
_ => base.join("Tracks"),
|
||||
_ => {
|
||||
let album = req.meta.album.trim();
|
||||
let existing = (settings.collection_folders && !album.is_empty()).then(|| existing_dir(&base.join("Albums"), &sanitize(album))).flatten();
|
||||
existing.unwrap_or_else(|| base.join("Tracks"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn existing_dir(parent: &Path, name: &str) -> Option<PathBuf> {
|
||||
let want = name.to_lowercase();
|
||||
std::fs::read_dir(parent).ok()?.flatten().find(|e| e.path().is_dir() && e.file_name().to_string_lossy().to_lowercase() == want).map(|e| e.path())
|
||||
}
|
||||
|
||||
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 };
|
||||
@@ -879,6 +888,18 @@ mod tests {
|
||||
assert_eq!(target_dir(&flat, &req(Some("album"), Some("Luxury"))), PathBuf::from("M").join("Tracks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_songs_join_an_album_folder_that_already_exists() {
|
||||
let base = std::env::temp_dir().join(format!("atmo-single-{}", std::process::id()));
|
||||
std::fs::create_dir_all(base.join("Albums").join("Luxury")).unwrap();
|
||||
let settings = Settings { output_dir: base.to_string_lossy().into_owned(), collection_folders: true, ..Default::default() };
|
||||
let req = |album: &str| JobRequest { entry: entry(None, false, vec![]), meta: TagFields { album: album.into(), ..Default::default() }, folder: None, trim: None, playlist: None, kind: Some("track".into()) };
|
||||
assert_eq!(target_dir(&settings, &req("luxury")), base.join("Albums").join("Luxury"));
|
||||
assert_eq!(target_dir(&settings, &req("Something Else")), base.join("Tracks"));
|
||||
assert_eq!(target_dir(&settings, &req("")), base.join("Tracks"));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_stems_and_escapes_templates() {
|
||||
let settings = Settings { output_dir: "out".into(), ..Default::default() };
|
||||
|
||||
+164
-9
@@ -361,11 +361,127 @@ pub async fn track_edit(app: AppHandle, state: State<'_, AppState>, id: String,
|
||||
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)?;
|
||||
let mut updated = state.library.refresh(&id, &pl).map_err(err)?;
|
||||
if let Some(moved) = file_by_album(&state, &[(t, updated.clone())]).into_iter().next() {
|
||||
updated = moved;
|
||||
}
|
||||
changed(&app);
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
let n = |p: &Path| p.to_string_lossy().replace('\\', "/").trim_end_matches('/').to_lowercase();
|
||||
n(a) == n(b)
|
||||
}
|
||||
|
||||
pub fn album_home(base: &Path, file: &Path, album: &str, known: Option<PathBuf>) -> Option<PathBuf> {
|
||||
let (tracks, albums) = (base.join("Tracks"), base.join("Albums"));
|
||||
let parent = file.parent()?;
|
||||
let in_tracks = same_dir(parent, &tracks);
|
||||
let in_album = parent.parent().is_some_and(|p| same_dir(p, &albums));
|
||||
let album = album.trim();
|
||||
if !(in_tracks || in_album) || album.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = crate::downloader::sanitize(album);
|
||||
let target = known.or_else(|| crate::downloader::existing_dir(&albums, &name)).unwrap_or_else(|| albums.join(&name));
|
||||
(!same_dir(&target, parent)).then_some(target)
|
||||
}
|
||||
|
||||
fn move_file(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if std::fs::rename(from, to).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::copy(from, to)?;
|
||||
std::fs::remove_file(from)
|
||||
}
|
||||
|
||||
pub fn move_with_sidecars(file: &Path, dir: &Path) -> std::io::Result<PathBuf> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let parent = file.parent().ok_or_else(|| std::io::Error::other("no folder"))?.to_path_buf();
|
||||
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let ext = file.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||
let mut dest = dir.join(format!("{stem}{ext}"));
|
||||
let mut n = 2;
|
||||
while dest.exists() {
|
||||
dest = dir.join(format!("{stem} ({n}){ext}"));
|
||||
n += 1;
|
||||
}
|
||||
move_file(file, &dest)?;
|
||||
let new_stem = dest.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
for e in std::fs::read_dir(&parent)?.flatten() {
|
||||
let p = e.path();
|
||||
if !p.is_file() || p.file_stem().map(|s| s.to_string_lossy().into_owned()).as_deref() != Some(stem.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let ext = p.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||
let to = dir.join(format!("{new_stem}{ext}"));
|
||||
if !to.exists() {
|
||||
let _ = move_file(&p, &to);
|
||||
}
|
||||
}
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
fn tidy_album_dir(dir: &Path, albums: &Path, went_to: &HashSet<PathBuf>) {
|
||||
if !dir.parent().is_some_and(|p| same_dir(p, albums)) {
|
||||
return;
|
||||
}
|
||||
let Ok(rest) = std::fs::read_dir(dir) else { return };
|
||||
let rest: Vec<PathBuf> = rest.flatten().map(|e| e.path()).collect();
|
||||
if rest.iter().any(|p| p.is_dir() || crate::library::is_playable(p)) {
|
||||
return;
|
||||
}
|
||||
if let (1, Some(target)) = (went_to.len(), went_to.iter().next()) {
|
||||
for p in &rest {
|
||||
if let Some(name) = p.file_name() {
|
||||
if !target.join(name).exists() {
|
||||
let _ = move_file(p, &target.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir(dir);
|
||||
}
|
||||
|
||||
fn file_by_album(state: &AppState, edits: &[(Track, Track)]) -> Vec<Track> {
|
||||
let s = state.snapshot();
|
||||
if !s.collection_folders {
|
||||
return Vec::new();
|
||||
}
|
||||
let base = PathBuf::from(&s.output_dir);
|
||||
let albums = base.join("Albums");
|
||||
let editing: HashSet<&str> = edits.iter().map(|(_, a)| a.path.as_str()).collect();
|
||||
let norm = crate::artistinfo::norm;
|
||||
let mut out = Vec::new();
|
||||
let mut left: std::collections::HashMap<PathBuf, HashSet<PathBuf>> = std::collections::HashMap::new();
|
||||
for (before, after) in edits {
|
||||
if norm(&before.album) == norm(&after.album) || after.album.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let file = PathBuf::from(&after.path);
|
||||
let (want, by) = (norm(&after.album), norm(&after.album_artist));
|
||||
let in_albums = |t: &Track| Path::new(&t.path).parent().and_then(Path::parent).is_some_and(|p| same_dir(p, &albums));
|
||||
let same_artist = |t: &Track| by.is_empty() || norm(&t.album_artist).is_empty() || norm(&t.album_artist) == by;
|
||||
let known = state
|
||||
.library
|
||||
.find_track(|t| !editing.contains(t.path.as_str()) && norm(&t.album) == want && same_artist(t) && in_albums(t))
|
||||
.and_then(|t| Path::new(&t.path).parent().map(Path::to_path_buf));
|
||||
let Some(dir) = album_home(&base, &file, &after.album, known) else { continue };
|
||||
let Ok(dest) = move_with_sidecars(&file, &dir) else { continue };
|
||||
if let Some(old_dir) = file.parent() {
|
||||
left.entry(old_dir.to_path_buf()).or_default().insert(dir.clone());
|
||||
}
|
||||
if let Some(t) = state.library.remap_file(&file, &dest).and_then(|id| state.library.track(&id)) {
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
for (dir, went_to) in &left {
|
||||
tidy_album_dir(dir, &albums, went_to);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[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 {
|
||||
@@ -600,17 +716,21 @@ pub async fn tracks_edit(app: AppHandle, state: State<'_, AppState>, ids: Vec<St
|
||||
let (_, pl) = dirs(&state);
|
||||
let mut done = 0;
|
||||
let mut failed = Vec::new();
|
||||
let mut edits = Vec::new();
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let Some(t) = state.library.track(id) else { continue };
|
||||
match tagging::apply(Path::new(&t.path), &meta, "", ffmpeg.as_deref()).await {
|
||||
Ok(()) => {
|
||||
let _ = state.library.refresh(id, &pl);
|
||||
if let Ok(after) = state.library.refresh(id, &pl) {
|
||||
edits.push((t, after));
|
||||
}
|
||||
done += 1;
|
||||
}
|
||||
Err(e) => failed.push(format!("{} ({e})", t.title)),
|
||||
}
|
||||
let _ = app.emit(LIBRARY_EVENT, serde_json::json!({ "type": "editing", "done": i + 1, "total": ids.len() }));
|
||||
}
|
||||
file_by_album(&state, &edits);
|
||||
changed(&app);
|
||||
if done == 0 && !failed.is_empty() {
|
||||
return Err(format!("Couldn't update {}", failed.join(", ")));
|
||||
@@ -720,18 +840,18 @@ pub async fn import_file(app: AppHandle, state: State<'_, AppState>, request: ta
|
||||
pub async fn artist_choices(state: State<'_, AppState>, query: String) -> CmdResult<serde_json::Value> {
|
||||
let q = query.trim();
|
||||
if q.is_empty() {
|
||||
return Ok(serde_json::json!({ "photos": [], "pages": [] }));
|
||||
return Ok(serde_json::json!({ "photos": [], "pages": [], "logos": [] }));
|
||||
}
|
||||
let (photos, pages) = crate::artistinfo::choices(&state.http, q).await;
|
||||
Ok(serde_json::json!({ "photos": photos, "pages": pages }))
|
||||
let (photos, pages, logos) = crate::artistinfo::choices(&state.http, q).await;
|
||||
Ok(serde_json::json!({ "photos": photos, "pages": pages, "logos": logos }))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn artist_apply(state: State<'_, AppState>, name: String, photo: Option<String>, page: Option<String>) -> CmdResult<crate::library::ArtistMeta> {
|
||||
if photo.as_deref().is_some_and(|u| !crate::artistinfo::allowed_photo(u)) {
|
||||
return Err("That photo isn't from a source Atmosphere trusts.".into());
|
||||
pub async fn artist_apply(state: State<'_, AppState>, name: String, photo: Option<String>, page: Option<String>, logo: Option<String>) -> CmdResult<crate::library::ArtistMeta> {
|
||||
if photo.as_deref().is_some_and(|u| !crate::artistinfo::allowed_photo(u)) || logo.as_deref().is_some_and(|u| !crate::artistinfo::allowed_logo(u)) {
|
||||
return Err("That image isn't from a source Atmosphere trusts.".into());
|
||||
}
|
||||
let found = crate::artistinfo::chosen(&state.http, photo.as_deref(), page.as_deref()).await;
|
||||
let found = crate::artistinfo::chosen(&state.http, photo.as_deref(), page.as_deref(), logo.as_deref()).await;
|
||||
if found.photo.is_none() && found.bio.is_none() && found.logo.is_none() {
|
||||
return Err("Couldn't get anything from that choice. Try another one.".into());
|
||||
}
|
||||
@@ -851,6 +971,41 @@ pub async fn move_music(app: AppHandle, state: State<'_, AppState>, to: String)
|
||||
mod move_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn songs_given_an_album_move_into_its_folder_with_their_lyrics() {
|
||||
let base = std::env::temp_dir().join(format!("atmo-album-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (tracks, albums) = (base.join("Tracks"), base.join("Albums"));
|
||||
std::fs::create_dir_all(albums.join("Random Access Memories")).unwrap();
|
||||
std::fs::create_dir_all(&tracks).unwrap();
|
||||
let song = tracks.join("Daft Punk - Get Lucky.m4a");
|
||||
std::fs::write(&song, b"a").unwrap();
|
||||
std::fs::write(tracks.join("Daft Punk - Get Lucky.lrc"), b"l").unwrap();
|
||||
std::fs::write(tracks.join("Daft Punk - Get Lucky.mp4"), b"v").unwrap();
|
||||
|
||||
assert_eq!(album_home(&base, &song, "random access memories", None), Some(albums.join("Random Access Memories")));
|
||||
assert_eq!(album_home(&base, &song, "Brand New", None), Some(albums.join("Brand New")));
|
||||
assert_eq!(album_home(&base, &song, "", None), None);
|
||||
assert_eq!(album_home(&base, &base.join("Mine").join("x.mp3"), "Brand New", None), None);
|
||||
assert_eq!(album_home(&base, &albums.join("Random Access Memories").join("x.mp3"), "Random Access Memories", None), None);
|
||||
assert_eq!(album_home(&base, &song, "RAM", Some(albums.join("Random Access Memories"))), Some(albums.join("Random Access Memories")));
|
||||
|
||||
let dest = move_with_sidecars(&song, &albums.join("Random Access Memories")).unwrap();
|
||||
assert_eq!(dest, albums.join("Random Access Memories").join("Daft Punk - Get Lucky.m4a"));
|
||||
for ext in ["m4a", "lrc", "mp4"] {
|
||||
assert!(albums.join("Random Access Memories").join(format!("Daft Punk - Get Lucky.{ext}")).is_file());
|
||||
assert!(!tracks.join(format!("Daft Punk - Get Lucky.{ext}")).exists());
|
||||
}
|
||||
|
||||
let old = albums.join("Old Name");
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
std::fs::write(old.join("cover.jpg"), b"c").unwrap();
|
||||
tidy_album_dir(&old, &albums, &HashSet::from([albums.join("Random Access Memories")]));
|
||||
assert!(!old.exists());
|
||||
assert!(albums.join("Random Access Memories").join("cover.jpg").is_file());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moves_a_tree_and_keeps_both_on_name_clashes() {
|
||||
let root = std::env::temp_dir().join(format!("atmo-move-{}", std::process::id()));
|
||||
|
||||
+40
-7
@@ -965,14 +965,26 @@ impl Library {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn find_track(&self, f: impl Fn(&Track) -> bool) -> Option<Track> {
|
||||
self.tracks.read().unwrap().values().find(|t| f(t)).cloned()
|
||||
}
|
||||
|
||||
pub fn remap_file(&self, from: &Path, to: &Path) -> Option<String> {
|
||||
self.remap_with(|p| (p == from).then(|| to.to_path_buf()));
|
||||
self.find_track(|t| Path::new(&t.path) == to).map(|t| t.id)
|
||||
}
|
||||
|
||||
pub fn remap_paths(&self, from: &Path, to: &Path) -> usize {
|
||||
self.remap_with(|p| p.strip_prefix(from).ok().map(|r| to.join(r)))
|
||||
}
|
||||
|
||||
fn remap_with(&self, map: impl Fn(&Path) -> Option<PathBuf>) -> usize {
|
||||
let mut moved: HashMap<String, String> = HashMap::new();
|
||||
{
|
||||
let mut tracks = self.tracks.write().unwrap();
|
||||
let old: Vec<Track> = tracks.values().filter(|t| Path::new(&t.path).starts_with(from)).cloned().collect();
|
||||
for mut t in old {
|
||||
let Ok(rel) = Path::new(&t.path).strip_prefix(from).map(Path::to_path_buf) else { continue };
|
||||
let new_path = to.join(rel).to_string_lossy().into_owned();
|
||||
let old: Vec<(Track, PathBuf)> = tracks.values().filter_map(|t| map(Path::new(&t.path)).map(|p| (t.clone(), p))).collect();
|
||||
for (mut t, to) in old {
|
||||
let new_path = to.to_string_lossy().into_owned();
|
||||
let new_id = hash(&new_path);
|
||||
tracks.remove(&t.id);
|
||||
moved.insert(t.id.clone(), new_id.clone());
|
||||
@@ -999,7 +1011,7 @@ impl Library {
|
||||
let mut hidden = self.hidden.write().unwrap();
|
||||
let next: HashSet<String> = hidden
|
||||
.drain()
|
||||
.map(|p| Path::new(&p).strip_prefix(from).map(|r| to.join(r).to_string_lossy().into_owned()).unwrap_or(p))
|
||||
.map(|p| map(Path::new(&p)).map(|n| n.to_string_lossy().into_owned()).unwrap_or(p))
|
||||
.collect();
|
||||
*hidden = next;
|
||||
store("hidden.json", &*hidden);
|
||||
@@ -1007,8 +1019,8 @@ impl Library {
|
||||
{
|
||||
let mut linked = self.linked.write().unwrap();
|
||||
for l in linked.iter_mut() {
|
||||
if let Ok(r) = Path::new(&l.path).strip_prefix(from) {
|
||||
l.path = to.join(r).to_string_lossy().into_owned();
|
||||
if let Some(n) = map(Path::new(&l.path)) {
|
||||
l.path = n.to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
store("linked.json", &*linked);
|
||||
@@ -1159,6 +1171,27 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_one_song_keeps_its_likes_and_plays() {
|
||||
let root = std::env::temp_dir().join(format!("atmo-remap1-{}-{}", std::process::id(), now()));
|
||||
std::env::set_var("ATMOSPHERE_DATA_DIR", root.join("data"));
|
||||
let (from, to) = (root.join("Tracks").join("one.wav"), root.join("Albums").join("A").join("one.wav"));
|
||||
wav(&from, 2);
|
||||
wav(&root.join("Tracks").join("two.wav"), 2);
|
||||
let lib = Library::load();
|
||||
lib.scan(std::slice::from_ref(&root), &root.join("Playlists"), |_, _| {}).unwrap();
|
||||
let id = lib.find_track(|t| Path::new(&t.path) == from).unwrap().id;
|
||||
lib.like(&id, true);
|
||||
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
|
||||
std::fs::rename(&from, &to).unwrap();
|
||||
let new_id = lib.remap_file(&from, &to).unwrap();
|
||||
let snap = lib.snapshot(&root.join("Playlists"));
|
||||
assert_eq!(snap.tracks.len(), 2);
|
||||
assert!(snap.liked.contains(&new_id));
|
||||
assert!(snap.tracks.iter().any(|t| t.path.ends_with("two.wav")));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playlist_order_roundtrip() {
|
||||
let dir = std::env::temp_dir().join(format!("atmo-test-{}", now()));
|
||||
|
||||
+33
@@ -5,6 +5,7 @@ mod api;
|
||||
mod artistinfo;
|
||||
mod backup;
|
||||
mod direct;
|
||||
mod discord;
|
||||
mod downloader;
|
||||
mod engine;
|
||||
mod history;
|
||||
@@ -110,6 +111,10 @@ fn save_settings(app: AppHandle, state: State<'_, AppState>, patch: SettingsPatc
|
||||
if (after.api_enabled, after.api_port) != (before.api_enabled, before.api_port) {
|
||||
api::apply(&app);
|
||||
}
|
||||
let opts = discord::Options::from(&after);
|
||||
if opts != discord::Options::from(&before) {
|
||||
app.state::<discord::DiscordHub>().configure(opts);
|
||||
}
|
||||
Ok(view(after))
|
||||
}
|
||||
|
||||
@@ -125,6 +130,30 @@ fn api_new_token(app: AppHandle, hub: State<'_, api::ApiHub>) -> CmdResult<Strin
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn discord_status(hub: State<'_, discord::DiscordHub>) -> discord::Status {
|
||||
hub.status()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn discord_now(hub: State<'_, discord::DiscordHub>, now: Option<discord::NowPlaying>) {
|
||||
hub.now_playing(now);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn discord_save_assets(app: AppHandle) -> CmdResult<Option<String>> {
|
||||
let start = dirs::desktop_dir().or_else(dirs::download_dir).unwrap_or_default();
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || {
|
||||
app.dialog().file().set_directory(start).set_title("Choose where to save the Discord images").blocking_pick_folder()
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let Some(dir) = picked.and_then(|p| p.into_path().ok()) else { return Ok(None) };
|
||||
let dir = dir.join("Atmosphere for Discord");
|
||||
discord::write_assets(&dir).map_err(err)?;
|
||||
Ok(Some(dir.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn api_publish(hub: State<'_, api::ApiHub>, state: serde_json::Value) {
|
||||
hub.publish(state);
|
||||
@@ -470,6 +499,7 @@ fn main() {
|
||||
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)), pending_open: Mutex::new(libcmd::audio_args(std::env::args().skip(1))) });
|
||||
app.manage(api::ApiHub::load());
|
||||
app.manage(discord::DiscordHub::start(app.handle().clone(), http.clone(), discord::Options::from(&settings.lock().unwrap())));
|
||||
api::apply(app.handle());
|
||||
libcmd::spawn_scan(app.handle().clone());
|
||||
libcmd::start_linked_monitor(app.handle().clone());
|
||||
@@ -484,6 +514,9 @@ fn main() {
|
||||
api_status,
|
||||
api_new_token,
|
||||
api_publish,
|
||||
discord_status,
|
||||
discord_now,
|
||||
discord_save_assets,
|
||||
frame_color,
|
||||
backup_save,
|
||||
backup_pick,
|
||||
|
||||
@@ -65,6 +65,11 @@ pub struct Settings {
|
||||
pub api_enabled: bool,
|
||||
pub check_updates: bool,
|
||||
pub artist_info: bool,
|
||||
pub discord_enabled: bool,
|
||||
pub discord_client_id: String,
|
||||
pub discord_cover: bool,
|
||||
pub discord_paused: bool,
|
||||
pub discord_status: String,
|
||||
pub api_port: u16,
|
||||
pub api_read: bool,
|
||||
pub api_control: bool,
|
||||
@@ -114,6 +119,11 @@ impl Default for Settings {
|
||||
api_enabled: false,
|
||||
check_updates: true,
|
||||
artist_info: true,
|
||||
discord_enabled: false,
|
||||
discord_client_id: String::new(),
|
||||
discord_cover: true,
|
||||
discord_paused: true,
|
||||
discord_status: "app".into(),
|
||||
api_port: 47823,
|
||||
api_read: true,
|
||||
api_control: true,
|
||||
@@ -161,6 +171,11 @@ pub struct SettingsPatch {
|
||||
pub api_enabled: Option<bool>,
|
||||
pub check_updates: Option<bool>,
|
||||
pub artist_info: Option<bool>,
|
||||
pub discord_enabled: Option<bool>,
|
||||
pub discord_client_id: Option<String>,
|
||||
pub discord_cover: Option<bool>,
|
||||
pub discord_paused: Option<bool>,
|
||||
pub discord_status: Option<String>,
|
||||
pub api_port: Option<u16>,
|
||||
pub api_read: Option<bool>,
|
||||
pub api_control: Option<bool>,
|
||||
@@ -214,6 +229,13 @@ impl Settings {
|
||||
}
|
||||
set!(save_as, embed_metadata, collection_folders, number_tracks, skip_downloaded, sponsorblock, embed_subtitles, embed_chapters, watch_clipboard);
|
||||
set!(api_enabled, api_read, api_control, api_links, check_updates, artist_info, video_keep_audio, prefer_official_audio);
|
||||
set!(discord_enabled, discord_cover, discord_paused);
|
||||
if let Some(v) = p.discord_client_id.map(|v| v.trim().to_string()).filter(|v| v.is_empty() || (v.len() >= 15 && v.len() <= 25 && v.bytes().all(|b| b.is_ascii_digit()))) {
|
||||
self.discord_client_id = v;
|
||||
}
|
||||
if let Some(v) = p.discord_status.filter(|v| matches!(v.as_str(), "app" | "artist" | "song")) {
|
||||
self.discord_status = v;
|
||||
}
|
||||
if let Some(p) = p.api_port.filter(|p| *p >= 1024) {
|
||||
self.api_port = p;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user