diff --git a/Cargo.lock b/Cargo.lock index c1cff5b..6cd7c61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -239,10 +239,12 @@ name = "atmosphere" version = "0.1.0" dependencies = [ "anyhow", + "axum", "base64 0.23.1", "bytes", "dirs", "futures-util", + "getrandom 0.3.4", "image", "lofty", "lzma-rs", @@ -278,6 +280,56 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + [[package]] name = "base64" version = "0.21.7" @@ -1805,6 +1857,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -1828,6 +1886,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2491,6 +2550,12 @@ dependencies = [ "web_atoms 0.3.0", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -3877,6 +3942,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.21" diff --git a/Cargo.toml b/Cargo.toml index 254694b..55a73fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,10 +17,12 @@ strip = true panic = "abort" [dependencies] +axum = { version = "0.8", default-features = false, features = ["http1", "json", "query", "tokio"] } anyhow = "1.0.104" base64 = "0.23.1" bytes = "1.12.2" dirs = "7.0.0" +getrandom = "0.3" futures-util = "0.3.34" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] } lofty = "0.25.5" diff --git a/README.md b/README.md index e6981ab..adcf1df 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ It's built for media you **own or have the rights to keep**, such as your own up - **Songs, Albums, Artists, Liked.** The song list is virtualized, so big libraries scroll smoothly. Search and sort everywhere. - **Artist profiles** with popular tracks, albums, singles & EPs, appears-on, and a photo and bio you can attach. - **Playlists are real folders** on your drive, so phones, USB drives and other players can use them as-is. Songs are hard-linked (no extra space) or copied, and a `playlist.m3u8` keeps the order. +- **Use folders you already have** as playlists. Atmosphere never moves or deletes them. If one goes missing (renamed, moved, or on an unplugged drive), it's marked as missing with **Locate folder**, and it comes back by itself when the drive reconnects. - **Multi-select** with Ctrl/Shift-click. Drag songs onto playlists, play next, add to queue, edit tags, **remove from library** (the file stays) or **delete from device** (sent to the Recycle Bin or Trash). ### Player @@ -101,6 +102,11 @@ It's built for media you **own or have the rights to keep**, such as your own up - Downloads run in **track order**, with progress, retry, history, and skipping of anything downloaded before. - Extras: chapters, subtitles, SponsorBlock, a speed limit, a proxy, and sign-in for your own private uploads, either from your browser or from a `cookies.txt` file. **Check** confirms it works and explains what to do if it doesn't. For example, Chromium browsers lock their sign-in while they're open. +### Connections +- An optional **local API** lets other apps on your computer, like stream overlays, status tools or your own scripts, see what's playing, browse your library, control playback and send links to Get. +- It's off until you turn it on, listens on `127.0.0.1` only, and needs a token that's shown once and stored only as a fingerprint. +- You choose what apps may do, and browser pages are refused. See the [API guide](docs/api.md). + ### Stats - Week, month, year or all time: listening time, plays, songs, artists, time in the app, a by-day chart, and top songs, artists and albums. - Songs you delete are removed from your history. @@ -131,7 +137,7 @@ Grab a build from the [Actions](../../actions) tab, under the latest run's artif | Linux | `.deb`, `.rpm`, `.AppImage` | On first launch: -1. Confirm the three rights statements. +1. Confirm the three rights statements. The Windows installer covers this on its licence page. 2. Let Atmosphere set up its engine: [yt-dlp](https://github.com/yt-dlp/yt-dlp) and [ffmpeg](https://ffmpeg.org), downloaded from their official releases and checksum-verified. On macOS, install ffmpeg with `brew install ffmpeg`. 3. Add your music folders in **Settings → Library**, or paste a link. @@ -178,7 +184,7 @@ On macOS, use `⌘` in place of `Ctrl`. Atmosphere is for media you own or are allowed to keep. -- **Before first use**, you confirm three statements about rights and responsibility. **Each download** also asks for confirmation. The app's backend enforces both, not only the UI. +- **Before first use**, you agree to three statements about rights and responsibility. On Windows, that's the installer's licence page. The portable app, macOS and Linux ask once inside the app. **Each download** also asks for confirmation. The app's backend enforces both, not only the UI. - It **never bypasses DRM or paywalls**, and skips preview-only media, the same way yt-dlp itself refuses encrypted formats. - **Artists recovering their own uploads** can enable downloads on the track and choose **Original file** to get the uploaded master. @@ -195,6 +201,7 @@ Atmosphere is for media you own or are allowed to keep. | `src/storage.rs` | Temp-file cleanup and the Storage report | | `src/direct.rs` | Checks and reads direct audio and video file links | | `src/backup.rs` | Backup and restore of settings, stats and liked songs | +| `src/api.rs` | The opt-in local API for other apps ([guide](docs/api.md)) | | `src/tagging.rs` | Writes tags, cover art and lyrics into files | | `ui/` | The interface in plain HTML, CSS and JS (no build step) | | `branding/`, `tools/` | The logo, wordmark lockups and installer art, all generated from code | diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..1f56c3f --- /dev/null +++ b/docs/api.md @@ -0,0 +1,131 @@ + +# Atmosphere local API + +Atmosphere can let other apps on the same computer see what's playing and control playback. Examples include stream overlays, status tools, keyboard macros and your own scripts. + +It's **off by default**. Turn it on in **Settings → Connections**, then create an access token. + +## Security model + +- **Same computer only.** The server listens on `127.0.0.1` and can't be reached from your network. +- **Token required.** Every request must send `Authorization: Bearer `. + - The token is 256 bits of randomness, shown once. + - Atmosphere stores only its SHA-256 fingerprint, and checks it in constant time. + - Replacing the token disconnects every app that used the old one. +- **Permissions you choose.** Each area can be switched off separately: + - *See what's playing and browse the library* + - *Control playback and the queue* + - *Send links to Get* + + Links only open in Atmosphere. Nothing is saved until you review and confirm it there. +- **No web pages.** Requests carrying browser headers (`Origin`, `Sec-Fetch-Site`) are refused, and so are requests whose `Host` isn't `127.0.0.1:` or `localhost:`. This blocks malicious sites and DNS-rebinding tricks. +- **Brute-force lockout.** After 20 wrong tokens within a minute, every request gets `429` until the minute passes. +- **Small bodies only.** Request bodies over 16 KB are rejected. + +## Basics + +- **Base URL:** `http://127.0.0.1:47823`. The port can be changed in Settings. +- **Data format:** requests and responses are JSON. +- **Errors:** errors look like `{ "error": "message" }`. + +```bash +curl -H "Authorization: Bearer $ATMO_TOKEN" http://127.0.0.1:47823/v1/ping +``` + +| Status | Meaning | +| --- | --- | +| `200` / `202` | OK / accepted (the app carries the action out right away) | +| `400` | Invalid input | +| `401` | Missing or wrong token | +| `403` | That permission is off, or the request came from a web page | +| `404` | Unknown endpoint, track or artwork | +| `413` | Body too large | +| `421` | Wrong `Host` header | +| `429` | Locked out after too many wrong tokens | + +## Endpoints + +### `GET /v1/ping` +This works with any permission. It returns the app version and which permissions are on. + +```json +{ "app": "atmosphere", "version": "0.1.0", "allowed": { "read": true, "control": true, "links": false } } +``` + +### `GET /v1/now-playing` · read +```json +{ + "playing": true, + "track": { "id": "…", "title": "Night Drive", "artist": "Nova Lumen", "album": "Glass Horizon", "albumArtist": "Nova Lumen", "durationMs": 251000, "artwork": "/v1/artwork/…" }, + "positionMs": 73120, + "updatedAt": 1763500000000, + "volume": 0.85, "muted": false, "shuffle": false, "repeat": "off", + "queue": { "index": 3, "length": 12 } +} +``` +`positionMs` was measured at `updatedAt`, a Unix time in milliseconds. While `playing` is true, add the time elapsed since then to get the current position. + +### `GET /v1/events` · read +This is a [Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) stream. Every message is a `now-playing` event with the same body as `/v1/now-playing`: +- one is sent right away +- another follows whenever the track, play state, queue, volume or position jumps +- one also comes every 10 s while playing + +```bash +curl -N -H "Authorization: Bearer $ATMO_TOKEN" http://127.0.0.1:47823/v1/events +``` + +### `GET /v1/library/tracks?q=&limit=<1-500>` · read +This searches titles, artists and albums. The default `limit` is 50. + +### `GET /v1/library/playlists` · read +This lists each playlist's name, its `trackIds` in order, and whether it's a linked folder that's currently missing. + +### `GET /v1/artwork/{trackId}` · read +This returns the cover art as JPEG. + +### `POST /v1/player/{action}` · control +The `action` is one of `play`, `pause`, `toggle`, `next` or `previous`. + +### `POST /v1/player/seek` · control +```json +{ "position": 42.5 } +``` +The position is in seconds. + +### `POST /v1/player/volume` · control +```json +{ "volume": 0.6 } +``` +The volume is between 0 and 1. + +### `POST /v1/queue` · control +```json +{ "ids": ["trackId", "…"], "mode": "next" } +``` +`mode` is one of three values: +- `now` replaces the queue and plays +- `next` plays after the current song +- `end` adds to the end, which is the default + +Unknown ids are skipped. Send between 1 and 500 ids. + +### `POST /v1/links` · links +```json +{ "url": "https://soundcloud.com/artist/track" } +``` +This opens the link in Atmosphere's Get view so you can review it. It never downloads anything by itself. + +## Example: a now-playing overlay feed in Python + +```python +import json, os, urllib.request + +req = urllib.request.Request("http://127.0.0.1:47823/v1/events", headers={"Authorization": f"Bearer {os.environ['ATMO_TOKEN']}"}) +with urllib.request.urlopen(req) as stream: + for line in stream: + if line.startswith(b"data:"): + now = json.loads(line[5:]) + if now["track"]: + print(("▶ " if now["playing"] else "⏸ ") + f"{now['track']['artist']} — {now['track']['title']}") +``` diff --git a/installer/RIGHTS.txt b/installer/RIGHTS.txt index 37bc5ab..21a6321 100644 --- a/installer/RIGHTS.txt +++ b/installer/RIGHTS.txt @@ -16,4 +16,4 @@ Atmosphere downloads two open-source tools on first run, both from their officia - yt-dlp (Unlicense): https://github.com/yt-dlp/yt-dlp - ffmpeg (GPL builds): https://github.com/yt-dlp/FFmpeg-Builds -You'll be asked to confirm these points again the first time you open the app. +Clicking "I Agree" confirms these points, so Atmosphere won't ask again when you first open it. diff --git a/installer/hooks.nsh b/installer/hooks.nsh index 8a05d46..8c59b66 100644 --- a/installer/hooks.nsh +++ b/installer/hooks.nsh @@ -1,4 +1,16 @@ -; atmosphere · hooks.nsh · Uninstaller hooks: offer a backup before removing data, and remove Atmosphere's own data folders only when asked +; atmosphere · hooks.nsh · Installer hooks: record the rights agreement, offer a backup before removing data, and remove Atmosphere's own data only when asked + +!define ATMO_TERMS_VERSION 1 + +!macro NSIS_HOOK_POSTINSTALL + ${If} $PassiveMode <> 1 + ${AndIf} $UpdateMode <> 1 + ${AndIfNot} ${Silent} + FileOpen $R9 "$INSTDIR\rights-accepted" w + FileWrite $R9 "terms=${ATMO_TERMS_VERSION}" + FileClose $R9 + ${EndIf} +!macroend !macro NSIS_HOOK_PREUNINSTALL ${If} $UpdateMode <> 1 @@ -26,6 +38,10 @@ !macroend !macro NSIS_HOOK_POSTUNINSTALL + ${If} $UpdateMode <> 1 + Delete "$INSTDIR\rights-accepted" + RMDir "$INSTDIR" + ${EndIf} ${If} $UpdateMode <> 1 ${AndIf} $DeleteAppDataCheckboxState = 1 SetShellVarContext current diff --git a/src/api.rs b/src/api.rs new file mode 100644 index 0000000..7f19f83 --- /dev/null +++ b/src/api.rs @@ -0,0 +1,432 @@ +// atmosphere · api.rs · Opt-in local API for other apps: loopback only, token-protected, permission-scoped +use crate::AppState; +use axum::extract::{DefaultBodyLimit, Path as UrlPath, Query, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use base64::Engine as _; +use futures_util::StreamExt; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::VecDeque; +use std::convert::Infallible; +use std::sync::{Mutex, RwLock}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use tauri::{AppHandle, Emitter, Manager}; +use tokio::sync::broadcast; + +pub const ACTION_EVENT: &str = "atmosphere://api"; +const MAX_FAILURES: usize = 20; +const FAILURE_WINDOW: Duration = Duration::from_secs(60); + +#[derive(Clone, Copy, PartialEq)] +enum Scope { + Any, + Read, + Control, + Links, +} + +#[derive(Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct TokenFile { + token_hash: String, + created: u64, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Status { + running: bool, + port: u16, + error: Option, + has_token: bool, + token_created: Option, + last_used: Option, + last_client: Option, +} + +pub struct ApiHub { + now: RwLock, + tx: broadcast::Sender, + token: RwLock, + failures: Mutex>, + server: Mutex>>, + status: Mutex, +} + +fn now_secs() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +fn token_path() -> std::path::PathBuf { + crate::settings::path().with_file_name("api.json") +} + +fn digest(token: &str) -> String { + Sha256::digest(token.as_bytes()).iter().map(|b| format!("{b:02x}")).collect() +} + +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +impl ApiHub { + pub fn load() -> Self { + let token: TokenFile = std::fs::read(token_path()).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let status = Status { running: false, port: 0, error: None, has_token: !token.token_hash.is_empty(), token_created: (token.created > 0).then_some(token.created), last_used: None, last_client: None }; + Self { + now: RwLock::new(json!({ "playing": false, "track": null })), + tx: broadcast::channel(32).0, + token: RwLock::new(token), + failures: Mutex::new(VecDeque::new()), + server: Mutex::new(None), + status: Mutex::new(status), + } + } + + pub fn new_token(&self) -> anyhow::Result { + let mut raw = [0u8; 32]; + getrandom::fill(&mut raw).map_err(|e| anyhow::anyhow!("Couldn't create a secure token ({e})"))?; + let token = format!("atmo_{}", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw)); + let file = TokenFile { token_hash: digest(&token), created: now_secs() }; + let path = token_path(); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(&path, serde_json::to_vec(&file)?)?; + { + let mut s = self.status.lock().unwrap(); + s.has_token = true; + s.token_created = Some(file.created); + s.last_used = None; + s.last_client = None; + } + *self.token.write().unwrap() = file; + Ok(token) + } + + fn verify(&self, token: &str) -> bool { + let stored = self.token.read().unwrap(); + !stored.token_hash.is_empty() && same(digest(token).as_bytes(), stored.token_hash.as_bytes()) + } + + fn locked(&self) -> bool { + let mut f = self.failures.lock().unwrap(); + while f.front().is_some_and(|t| t.elapsed() > FAILURE_WINDOW) { + f.pop_front(); + } + f.len() >= MAX_FAILURES + } + + fn fail(&self) { + self.failures.lock().unwrap().push_back(Instant::now()); + } + + fn touch(&self, client: Option<&str>) { + let mut s = self.status.lock().unwrap(); + s.last_used = Some(now_secs()); + s.last_client = client.map(|c| c.chars().take(80).collect()); + } + + pub fn publish(&self, state: Value) { + *self.now.write().unwrap() = state.clone(); + let _ = self.tx.send(state); + } + + pub fn status(&self) -> Status { + self.status.lock().unwrap().clone() + } +} + +#[derive(Clone)] +struct Ctx { + app: AppHandle, + port: u16, +} + +fn deny(code: StatusCode, msg: &str) -> Response { + (code, [(header::CACHE_CONTROL, "no-store")], Json(json!({ "error": msg }))).into_response() +} + +fn guard(ctx: &Ctx, headers: &HeaderMap, scope: Scope) -> Option { + let host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(""); + if host != format!("127.0.0.1:{}", ctx.port) && host != format!("localhost:{}", ctx.port) { + return Some(deny(StatusCode::MISDIRECTED_REQUEST, "Connect to 127.0.0.1 directly.")); + } + if headers.contains_key(header::ORIGIN) || headers.contains_key("sec-fetch-site") { + return Some(deny(StatusCode::FORBIDDEN, "Web pages can't use the Atmosphere API.")); + } + let hub = ctx.app.state::(); + if hub.locked() { + return Some(deny(StatusCode::TOO_MANY_REQUESTS, "Too many wrong tokens. Try again in a minute.")); + } + let token = headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).map(str::trim).unwrap_or(""); + if token.is_empty() || !hub.verify(token) { + hub.fail(); + return Some(deny(StatusCode::UNAUTHORIZED, "Missing or wrong access token.")); + } + let s = ctx.app.state::().snapshot(); + let (allowed, what) = match scope { + Scope::Any => (true, ""), + Scope::Read => (s.api_read, "see what's playing or browse the library"), + Scope::Control => (s.api_control, "control playback"), + Scope::Links => (s.api_links, "send links"), + }; + if !allowed { + return Some(deny(StatusCode::FORBIDDEN, &format!("Atmosphere's settings don't allow apps to {what}."))); + } + hub.touch(headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok())); + None +} + +fn act(ctx: &Ctx, payload: Value) -> Response { + let _ = ctx.app.emit(ACTION_EVENT, payload); + (StatusCode::ACCEPTED, Json(json!({ "ok": true }))).into_response() +} + +async fn ping(State(ctx): State, h: HeaderMap) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Any) { + return r; + } + let s = ctx.app.state::().snapshot(); + Json(json!({ "app": "atmosphere", "version": env!("CARGO_PKG_VERSION"), "allowed": { "read": s.api_read, "control": s.api_control, "links": s.api_links } })).into_response() +} + +async fn now_playing(State(ctx): State, h: HeaderMap) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Read) { + return r; + } + Json(ctx.app.state::().now.read().unwrap().clone()).into_response() +} + +async fn events(State(ctx): State, h: HeaderMap) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Read) { + return r; + } + let hub = ctx.app.state::(); + let first = hub.now.read().unwrap().clone(); + let rx = hub.tx.subscribe(); + let ev = |v: Value| Ok::(Event::default().event("now-playing").data(v.to_string())); + let initial = futures_util::stream::once(async move { ev(first) }); + let updates = futures_util::stream::unfold(rx, move |mut rx| async move { + loop { + match rx.recv().await { + Ok(v) => return Some((ev(v), rx)), + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(_) => return None, + } + } + }); + Sse::new(initial.chain(updates)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response() +} + +#[derive(Deserialize)] +struct TrackQuery { + q: Option, + limit: Option, +} + +async fn tracks(State(ctx): State, h: HeaderMap, Query(q): Query) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Read) { + return r; + } + let state = ctx.app.state::(); + let pl = std::path::PathBuf::from(state.snapshot().playlists_dir); + let snap = state.library.snapshot(&pl); + let needle = q.q.unwrap_or_default().to_lowercase(); + let limit = q.limit.unwrap_or(50).clamp(1, 500); + let list: Vec = snap + .tracks + .iter() + .filter(|t| needle.is_empty() || [&t.title, &t.artist, &t.album].iter().any(|f| f.to_lowercase().contains(&needle))) + .take(limit) + .map(|t| json!({ "id": t.id, "title": t.title, "artist": t.artist, "album": t.album, "albumArtist": t.album_artist, "durationMs": t.duration_ms, "year": t.year, "playlist": t.playlist, "liked": snap.liked.contains(&t.id) })) + .collect(); + Json(json!({ "tracks": list })).into_response() +} + +async fn playlists(State(ctx): State, h: HeaderMap) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Read) { + return r; + } + let state = ctx.app.state::(); + let pl = std::path::PathBuf::from(state.snapshot().playlists_dir); + let list: Vec = state.library.snapshot(&pl).playlists.iter().map(|p| json!({ "name": p.name, "trackIds": p.order, "linkedFolder": p.linked, "missing": p.missing })).collect(); + Json(json!({ "playlists": list })).into_response() +} + +async fn artwork(State(ctx): State, h: HeaderMap, UrlPath(id): UrlPath) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Read) { + return r; + } + let lib = &ctx.app.state::().library; + let Some(path) = lib.track(&id).and_then(|t| t.art).and_then(|k| lib.art_path(&k)) else { + return deny(StatusCode::NOT_FOUND, "No artwork for that track."); + }; + match tokio::fs::read(path).await { + Ok(bytes) => ([(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "private, max-age=3600")], bytes).into_response(), + Err(_) => deny(StatusCode::NOT_FOUND, "No artwork for that track."), + } +} + +async fn player(State(ctx): State, h: HeaderMap, UrlPath(action): UrlPath) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Control) { + return r; + } + if !["play", "pause", "toggle", "next", "previous"].contains(&action.as_str()) { + return deny(StatusCode::NOT_FOUND, "Unknown player action."); + } + act(&ctx, json!({ "action": action })) +} + +#[derive(Deserialize)] +struct Seek { + position: f64, +} + +async fn seek(State(ctx): State, h: HeaderMap, Json(b): Json) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Control) { + return r; + } + if !b.position.is_finite() || b.position < 0.0 { + return deny(StatusCode::BAD_REQUEST, "position must be a number of seconds, 0 or more."); + } + act(&ctx, json!({ "action": "seek", "position": b.position })) +} + +#[derive(Deserialize)] +struct Volume { + volume: f64, +} + +async fn volume(State(ctx): State, h: HeaderMap, Json(b): Json) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Control) { + return r; + } + if !b.volume.is_finite() || !(0.0..=1.0).contains(&b.volume) { + return deny(StatusCode::BAD_REQUEST, "volume must be between 0 and 1."); + } + act(&ctx, json!({ "action": "volume", "volume": b.volume })) +} + +#[derive(Deserialize)] +struct QueueBody { + ids: Vec, + mode: Option, +} + +async fn queue(State(ctx): State, h: HeaderMap, Json(b): Json) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Control) { + return r; + } + let mode = b.mode.unwrap_or_else(|| "end".into()); + if !["now", "next", "end"].contains(&mode.as_str()) { + return deny(StatusCode::BAD_REQUEST, "mode must be now, next or end."); + } + if b.ids.is_empty() || b.ids.len() > 500 { + return deny(StatusCode::BAD_REQUEST, "Send between 1 and 500 track ids."); + } + let lib = &ctx.app.state::().library; + let known: Vec = b.ids.into_iter().filter(|id| lib.track(id).is_some()).collect(); + if known.is_empty() { + return deny(StatusCode::NOT_FOUND, "None of those track ids are in the library."); + } + act(&ctx, json!({ "action": "queue", "ids": known, "mode": mode })) +} + +#[derive(Deserialize)] +struct LinkBody { + url: String, +} + +async fn links(State(ctx): State, h: HeaderMap, Json(b): Json) -> Response { + if let Some(r) = guard(&ctx, &h, Scope::Links) { + return r; + } + let ok = b.url.len() <= 2048 && url::Url::parse(b.url.trim()).is_ok_and(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some()); + if !ok { + return deny(StatusCode::BAD_REQUEST, "url must be a full http or https link."); + } + act(&ctx, json!({ "action": "link", "url": b.url.trim() })) +} + +async fn fallback() -> Response { + deny(StatusCode::NOT_FOUND, "Unknown endpoint. See docs/api.md.") +} + +fn router(ctx: Ctx) -> Router { + Router::new() + .route("/v1/ping", get(ping)) + .route("/v1/now-playing", get(now_playing)) + .route("/v1/events", get(events)) + .route("/v1/library/tracks", get(tracks)) + .route("/v1/library/playlists", get(playlists)) + .route("/v1/artwork/{id}", get(artwork)) + .route("/v1/player/seek", post(seek)) + .route("/v1/player/volume", post(volume)) + .route("/v1/player/{action}", post(player)) + .route("/v1/queue", post(queue)) + .route("/v1/links", post(links)) + .fallback(fallback) + .layer(DefaultBodyLimit::max(16 * 1024)) + .with_state(ctx) +} + +pub fn apply(app: &AppHandle) { + let hub = app.state::(); + if let Some(old) = hub.server.lock().unwrap().take() { + old.abort(); + } + let s = app.state::().snapshot(); + { + let mut st = hub.status.lock().unwrap(); + st.running = false; + st.port = s.api_port; + st.error = None; + } + if !s.api_enabled { + return; + } + if hub.token.read().unwrap().token_hash.is_empty() { + hub.status.lock().unwrap().error = Some("Create an access token to start the API.".into()); + return; + } + let ctx = Ctx { app: app.clone(), port: s.api_port }; + let handle = app.clone(); + let task = tauri::async_runtime::spawn(async move { + let hub = handle.state::(); + match tokio::net::TcpListener::bind(("127.0.0.1", ctx.port)).await { + Ok(listener) => { + hub.status.lock().unwrap().running = true; + let _ = handle.emit(ACTION_EVENT, json!({ "action": "status" })); + if let Err(e) = axum::serve(listener, router(ctx)).await { + hub.status.lock().unwrap().error = Some(format!("The API stopped ({e}).")); + } + hub.status.lock().unwrap().running = false; + } + Err(e) => { + hub.status.lock().unwrap().error = Some(format!("Port {} is unavailable ({e}). Choose another port.", ctx.port)); + } + } + let _ = handle.emit(ACTION_EVENT, json!({ "action": "status" })); + }); + *hub.server.lock().unwrap() = Some(task); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tokens_compare_in_constant_time_and_by_digest() { + assert!(same(b"abc", b"abc")); + assert!(!same(b"abc", b"abd")); + assert!(!same(b"abc", b"abcd")); + assert_eq!(digest("x").len(), 64); + assert_ne!(digest("atmo_a"), digest("atmo_b")); + } +} diff --git a/src/backup.rs b/src/backup.rs index 75c0ac0..fd7f644 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -5,7 +5,7 @@ use serde_json::Value; use std::io::{Read, Write}; use std::path::Path; -const DATA_FILES: &[&str] = &["library.json", "stats.json", "artists.json", "hidden.json", "history.json", "archive.txt"]; +const DATA_FILES: &[&str] = &["library.json", "stats.json", "artists.json", "hidden.json", "history.json", "archive.txt", "linked.json"]; const MARKER: &str = "atmosphere-backup.json"; fn artist_photos(data: &Path) -> Vec { diff --git a/src/libcmd.rs b/src/libcmd.rs index f74e723..17dbc35 100644 --- a/src/libcmd.rs +++ b/src/libcmd.rs @@ -85,7 +85,8 @@ pub fn start_watch(app: AppHandle) { let (roots, pl) = dirs(&app.state::()); let _ = std::fs::create_dir_all(&pl); let mut watched: Vec = Vec::new(); - for r in roots.into_iter().chain(std::iter::once(pl)) { + let linked: Vec = app.state::().library.linked_list().into_iter().map(|l| PathBuf::from(l.path)).collect(); + for r in roots.into_iter().chain(std::iter::once(pl)).chain(linked) { if r.is_dir() && !watched.iter().any(|w| r.starts_with(w)) && watcher.watch(&r, RecursiveMode::Recursive).is_ok() { watched.push(r); } @@ -109,6 +110,77 @@ pub fn start_watch(app: AppHandle) { }); } +pub fn start_linked_monitor(app: AppHandle) { + std::thread::spawn(move || { + let mut seen: std::collections::HashMap = std::collections::HashMap::new(); + loop { + let state = app.state::(); + let (_, pl) = dirs(&state); + let mut changed_any = false; + let mut rewatch = false; + for l in state.library.linked_list() { + let here = Path::new(&l.path).is_dir(); + let before = seen.insert(l.path.clone(), here); + if before == Some(here) || before.is_none() { + continue; + } + changed_any = true; + if here { + state.library.scan_folder(Path::new(&l.path), &pl); + rewatch = true; + } else { + state.library.remove_under(Path::new(&l.path)); + } + } + if rewatch { + start_watch(app.clone()); + } + if changed_any { + changed(&app); + } + std::thread::sleep(Duration::from_secs(10)); + } + }); +} + +async fn pick_folder(app: &AppHandle, title: &str) -> CmdResult> { + let a = app.clone(); + let title = title.to_string(); + let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title(&title).blocking_pick_folder()).await.map_err(|e| e.to_string())?; + Ok(picked.and_then(|p| p.into_path().ok())) +} + +#[tauri::command] +pub async fn playlist_link(app: AppHandle, state: State<'_, AppState>) -> CmdResult> { + let Some(path) = pick_folder(&app, "Add an existing folder as a playlist").await? else { return Ok(None) }; + let (_, pl) = dirs(&state); + let lib = state.library.clone(); + let name = tauri::async_runtime::spawn_blocking(move || lib.playlist_link(&pl, &path)).await.map_err(|e| e.to_string())?.map_err(err)?; + start_watch(app.clone()); + changed(&app); + Ok(Some(name)) +} + +#[tauri::command] +pub async fn playlist_relocate(app: AppHandle, state: State<'_, AppState>, name: String) -> CmdResult { + let Some(path) = pick_folder(&app, &format!("Locate the folder for “{name}”")).await? else { return Ok(false) }; + let (_, pl) = dirs(&state); + let lib = state.library.clone(); + tauri::async_runtime::spawn_blocking(move || lib.playlist_relocate(&pl, &name, &path)).await.map_err(|e| e.to_string())?.map_err(err)?; + start_watch(app.clone()); + changed(&app); + Ok(true) +} + +#[tauri::command] +pub fn playlist_unlink(app: AppHandle, state: State<'_, AppState>, name: String) -> CmdResult<()> { + let (roots, _) = dirs(&state); + state.library.playlist_unlink(&name, &roots).map_err(err)?; + start_watch(app.clone()); + changed(&app); + Ok(()) +} + #[tauri::command] pub fn library_scan(app: AppHandle) { spawn_scan(app); diff --git a/src/library.rs b/src/library.rs index dcaba29..2b93a08 100644 --- a/src/library.rs +++ b/src/library.rs @@ -78,6 +78,14 @@ pub struct Playlist { pub name: String, pub path: String, pub order: Vec, + pub linked: bool, + pub missing: bool, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Linked { + pub name: String, + pub path: String, } #[derive(Serialize)] @@ -98,6 +106,7 @@ pub struct Library { stats: RwLock, artists: RwLock>, hidden: RwLock>, + linked: RwLock>, scanning: AtomicBool, } @@ -234,6 +243,7 @@ impl Library { stats: RwLock::new(load("stats.json")), artists: RwLock::new(load("artists.json")), hidden: RwLock::new(load("hidden.json")), + linked: RwLock::new(load("linked.json")), scanning: AtomicBool::new(false), } } @@ -269,6 +279,7 @@ impl Library { let mut seen = HashSet::new(); let mut all_roots: Vec = roots.to_vec(); all_roots.push(playlists_dir.to_path_buf()); + all_roots.extend(self.linked_folders().into_iter().map(|(_, p)| p)); 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(); @@ -282,7 +293,7 @@ impl Library { let total = files.len(); let mut next: HashMap = HashMap::with_capacity(total); for (i, p) in files.iter().enumerate() { - let playlist = playlist_of(p, playlists_dir); + let playlist = self.playlist_for(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 { @@ -310,7 +321,7 @@ impl Library { if self.hidden.read().unwrap().contains(&*path.to_string_lossy()) { bail!("hidden"); } - let t = read_track(path, playlist_of(path, playlists_dir))?; + let t = read_track(path, self.playlist_for(path, playlists_dir))?; self.tracks.write().unwrap().insert(t.id.clone(), t.clone()); self.persist(); Ok(t) @@ -332,19 +343,24 @@ impl Library { } fn playlists(&self, dir: &Path, tracks: &[Track]) -> Vec { - 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 mut folders: Vec<(String, PathBuf, bool)> = Vec::new(); + if let Ok(rd) = std::fs::read_dir(dir) { + 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('.') { + folders.push((name, entry.path(), false)); + } } - let folder = entry.path(); + } + folders.extend(self.linked_folders().into_iter().map(|(n, p)| (n, p, true))); + let mut out = Vec::new(); + for (name, folder, linked) in folders { 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() }); + let rel = |t: &Track| Path::new(&t.path).strip_prefix(&folder).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); + members.sort_by_key(|t| (order.iter().position(|o| *o == rel(t)).unwrap_or(usize::MAX), rel(t).to_lowercase())); + let missing = linked && !folder.is_dir(); + out.push(Playlist { name, path: folder.to_string_lossy().into_owned(), order: members.iter().map(|t| t.id.clone()).collect(), linked, missing }); } out.sort_by_key(|p| p.name.to_lowercase()); out @@ -353,7 +369,7 @@ impl Library { pub fn playlist_create(&self, dir: &Path, name: &str) -> Result { let clean = sanitize(name.trim()); let folder = dir.join(&clean); - if folder.exists() { + if folder.exists() || self.linked_path(&clean).is_some() { bail!("A playlist called “{clean}” already exists."); } std::fs::create_dir_all(&folder).context("Couldn't create the playlist folder")?; @@ -364,9 +380,23 @@ impl Library { pub fn playlist_rename(&self, dir: &Path, from: &str, to: &str) -> Result { let clean = sanitize(to.trim()); let (a, b) = (dir.join(from), dir.join(&clean)); - if b.exists() { + if b.exists() || (clean != from && self.linked_path(&clean).is_some()) { bail!("A playlist called “{clean}” already exists."); } + if self.linked_path(from).is_some() { + { + let mut linked = self.linked.write().unwrap(); + if let Some(l) = linked.iter_mut().find(|l| l.name == from) { + l.name = clean.clone(); + } + store("linked.json", &*linked); + } + for t in self.tracks.write().unwrap().values_mut().filter(|t| t.playlist.as_deref() == Some(from)) { + t.playlist = Some(clean.clone()); + } + self.persist(); + return Ok(clean); + } std::fs::rename(&a, &b).context("Couldn't rename the playlist folder")?; let moved: Vec = self.tracks.read().unwrap().values().filter(|t| t.playlist.as_deref() == Some(from)).cloned().collect(); let mut tracks = self.tracks.write().unwrap(); @@ -385,6 +415,9 @@ impl Library { } pub fn playlist_delete(&self, dir: &Path, name: &str) -> Result<()> { + if self.linked_path(name).is_some() { + bail!("Linked folders are never deleted by Atmosphere. Remove it from Atmosphere instead."); + } 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(); @@ -392,7 +425,10 @@ impl Library { } pub fn playlist_add(&self, dir: &Path, name: &str, sources: &[PathBuf], link: bool) -> Result { - let folder = dir.join(name); + let folder = self.folder(dir, name); + if self.linked_path(name).is_some() && !folder.is_dir() { + bail!("“{name}” can't be found. Locate its folder first."); + } std::fs::create_dir_all(&folder)?; let mut order = read_order(&folder); let mut added = 0; @@ -423,7 +459,7 @@ impl Library { } pub fn playlist_remove(&self, dir: &Path, name: &str, ids: &[String]) -> Result<()> { - let folder = dir.join(name); + let folder = self.folder(dir, 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 }; @@ -433,7 +469,7 @@ impl Library { if lrc.exists() { let _ = trash::delete(&lrc); } - let fname = p.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + let fname = p.strip_prefix(&folder).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); order.retain(|o| *o != fname); self.tracks.write().unwrap().remove(id); } @@ -443,12 +479,142 @@ impl Library { } pub fn playlist_reorder(&self, dir: &Path, name: &str, ids: &[String]) -> Result<()> { + let folder = self.folder(dir, name); let names: Vec = 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())) + .filter_map(|t| Path::new(&t.path).strip_prefix(&folder).ok().map(|r| r.to_string_lossy().replace('\\', "/"))) .collect(); - write_order(&dir.join(name), &names) + write_order(&folder, &names) + } + + fn linked_folders(&self) -> Vec<(String, PathBuf)> { + self.linked.read().unwrap().iter().map(|l| (l.name.clone(), PathBuf::from(&l.path))).collect() + } + + pub fn linked_list(&self) -> Vec { + self.linked.read().unwrap().clone() + } + + fn linked_path(&self, name: &str) -> Option { + self.linked.read().unwrap().iter().find(|l| l.name == name).map(|l| PathBuf::from(&l.path)) + } + + fn folder(&self, dir: &Path, name: &str) -> PathBuf { + self.linked_path(name).unwrap_or_else(|| dir.join(name)) + } + + fn playlist_for(&self, path: &Path, playlists_dir: &Path) -> Option { + self.linked + .read() + .unwrap() + .iter() + .filter(|l| path.starts_with(&l.path)) + .max_by_key(|l| l.path.len()) + .map(|l| l.name.clone()) + .or_else(|| playlist_of(path, playlists_dir)) + } + + fn unique_name(&self, dir: &Path, base: &str) -> String { + let taken = |n: &str| dir.join(n).exists() || self.linked_path(n).is_some(); + let base = sanitize(base.trim()); + let base = if base.is_empty() { "Folder".to_string() } else { base }; + if !taken(&base) { + return base; + } + (2..).map(|i| format!("{base} ({i})")).find(|n| !taken(n)).unwrap_or(base) + } + + pub fn scan_folder(&self, folder: &Path, playlists_dir: &Path) -> usize { + let hidden = self.hidden.read().unwrap().clone(); + let mut found = Vec::new(); + for e in walkdir::WalkDir::new(folder).follow_links(false).into_iter().filter_entry(|e| !e.file_name().to_string_lossy().starts_with('.')).flatten() { + let p = e.path(); + if e.file_type().is_file() && is_audio(p) && !hidden.contains(&*p.to_string_lossy()) { + if let Ok(t) = read_track(p, self.playlist_for(p, playlists_dir)) { + found.push(t); + } + } + } + let n = found.len(); + let mut tracks = self.tracks.write().unwrap(); + for t in found { + tracks.insert(t.id.clone(), t); + } + drop(tracks); + self.persist(); + n + } + + pub fn playlist_link(&self, dir: &Path, path: &Path) -> Result { + if !path.is_dir() { + bail!("That folder can't be found."); + } + if path.parent().is_none() { + bail!("Choose a folder rather than a whole drive."); + } + if path.starts_with(dir) { + bail!("That folder is already one of your playlists."); + } + let key = path.to_string_lossy().into_owned(); + if let Some(l) = self.linked.read().unwrap().iter().find(|l| l.path == key) { + return Ok(l.name.clone()); + } + if self.linked.read().unwrap().iter().any(|l| path.starts_with(&l.path) || Path::new(&l.path).starts_with(path)) { + bail!("That folder overlaps one you've already added."); + } + let base = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let name = self.unique_name(dir, &base); + { + let mut linked = self.linked.write().unwrap(); + linked.push(Linked { name: name.clone(), path: key }); + store("linked.json", &*linked); + } + self.scan_folder(path, dir); + Ok(name) + } + + pub fn playlist_relocate(&self, dir: &Path, name: &str, path: &Path) -> Result<()> { + if !path.is_dir() { + bail!("That folder can't be found."); + } + if path.starts_with(dir) { + bail!("That folder is already one of your playlists."); + } + let key = path.to_string_lossy().into_owned(); + if self.linked.read().unwrap().iter().any(|l| l.name != name && (path.starts_with(&l.path) || Path::new(&l.path).starts_with(path))) { + bail!("That folder overlaps one you've already added."); + } + let old = { + let mut linked = self.linked.write().unwrap(); + let Some(l) = linked.iter_mut().find(|l| l.name == name) else { bail!("That playlist isn't a linked folder.") }; + let old = std::mem::replace(&mut l.path, key); + store("linked.json", &*linked); + old + }; + self.tracks.write().unwrap().retain(|_, t| !(t.playlist.as_deref() == Some(name) && Path::new(&t.path).starts_with(&old))); + self.scan_folder(path, dir); + Ok(()) + } + + pub fn playlist_unlink(&self, name: &str, library_roots: &[PathBuf]) -> Result<()> { + { + let mut linked = self.linked.write().unwrap(); + let before = linked.len(); + linked.retain(|l| l.name != name); + if linked.len() == before { + bail!("That playlist isn't a linked folder."); + } + store("linked.json", &*linked); + } + let mut tracks = self.tracks.write().unwrap(); + tracks.retain(|_, t| t.playlist.as_deref() != Some(name) || library_roots.iter().any(|r| Path::new(&t.path).starts_with(r))); + for t in tracks.values_mut().filter(|t| t.playlist.as_deref() == Some(name)) { + t.playlist = None; + } + drop(tracks); + self.persist(); + Ok(()) } pub fn remove_under(&self, path: &Path) -> usize { @@ -526,8 +692,8 @@ impl Library { 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 folder = self.folder(playlists_dir, name); + let fname = p.strip_prefix(&folder).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); let mut order = read_order(&folder); order.retain(|o| *o != fname); let _ = write_order(&folder, &order); @@ -690,6 +856,44 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + #[test] + fn linked_folders_link_go_missing_relocate_and_unlink() { + let root = std::env::temp_dir().join(format!("atmo-link-{}-{}", std::process::id(), now())); + std::env::set_var("ATMOSPHERE_DATA_DIR", root.join("data")); + let lists = root.join("Playlists"); + std::fs::create_dir_all(lists.join("Gym")).unwrap(); + let mine = root.join("Elsewhere").join("Gym"); + wav(&mine.join("a.wav"), 2); + wav(&mine.join("Sub").join("b.wav"), 3); + let lib = Library::load(); + let name = lib.playlist_link(&lists, &mine).unwrap(); + assert_eq!(name, "Gym (2)"); + assert_eq!(lib.playlist_link(&lists, &mine).unwrap(), name); + assert!(lib.playlist_link(&lists, &mine.join("Sub")).is_err()); + assert!(lib.playlist_link(&lists, &lists.join("Gym")).is_err()); + let snap = lib.snapshot(&lists); + let p = snap.playlists.iter().find(|p| p.name == name).unwrap(); + assert!(p.linked && !p.missing); + assert_eq!(p.order.len(), 2); + assert!(lib.playlist_delete(&lists, &name).is_err()); + assert!(mine.exists()); + let moved = root.join("Moved"); + std::fs::rename(&mine, &moved).unwrap(); + lib.remove_under(&mine); + let p = lib.snapshot(&lists).playlists.into_iter().find(|p| p.name == name).unwrap(); + assert!(p.missing && p.order.is_empty()); + lib.playlist_relocate(&lists, &name, &moved).unwrap(); + let p = lib.snapshot(&lists).playlists.into_iter().find(|p| p.name == name).unwrap(); + assert!(!p.missing && p.order.len() == 2); + let renamed = lib.playlist_rename(&lists, &name, "Lifting").unwrap(); + assert!(moved.exists() && lib.snapshot(&lists).playlists.iter().any(|p| p.name == renamed && p.order.len() == 2)); + lib.playlist_unlink(&renamed, &[]).unwrap(); + let snap = lib.snapshot(&lists); + assert!(snap.playlists.iter().all(|p| !p.linked) && snap.tracks.is_empty()); + assert!(moved.join("a.wav").exists()); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn playlist_order_roundtrip() { let dir = std::env::temp_dir().join(format!("atmo-test-{}", now())); diff --git a/src/main.rs b/src/main.rs index d66fd44..1b78d01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ // 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 api; mod backup; mod direct; mod downloader; @@ -97,15 +98,35 @@ fn revoke_rights(state: State<'_, AppState>) -> CmdResult { } #[tauri::command] -fn save_settings(state: State<'_, AppState>, patch: SettingsPatch) -> CmdResult { - let before = state.snapshot().concurrency; +fn save_settings(app: AppHandle, state: State<'_, AppState>, patch: SettingsPatch) -> CmdResult { + let before = state.snapshot(); let after = state.update(|s| s.apply(patch))?; - if after.concurrency != before { + if after.concurrency != before.concurrency { state.dl.set_concurrency(after.concurrency); } + if (after.api_enabled, after.api_port) != (before.api_enabled, before.api_port) { + api::apply(&app); + } Ok(view(after)) } +#[tauri::command] +fn api_status(hub: State<'_, api::ApiHub>) -> api::Status { + hub.status() +} + +#[tauri::command] +fn api_new_token(app: AppHandle, hub: State<'_, api::ApiHub>) -> CmdResult { + let token = hub.new_token().map_err(err)?; + api::apply(&app); + Ok(token) +} + +#[tauri::command] +fn api_publish(hub: State<'_, api::ApiHub>, state: serde_json::Value) { + hub.publish(state); +} + #[tauri::command] async fn tools_status(state: State<'_, AppState>) -> CmdResult { let s = state.snapshot(); @@ -407,7 +428,11 @@ fn main() { }; std::process::exit(code); } - let settings = Arc::new(Mutex::new(settings::load())); + let mut loaded = settings::load(); + if loaded.accept_from_installer() { + let _ = settings::save(&loaded); + } + let settings = Arc::new(Mutex::new(loaded)); let http = reqwest::Client::builder() .user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION"))) .connect_timeout(Duration::from_secs(15)) @@ -429,12 +454,18 @@ fn main() { 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)) }); + app.manage(api::ApiHub::load()); + api::apply(app.handle()); libcmd::spawn_scan(app.handle().clone()); + libcmd::start_linked_monitor(app.handle().clone()); libcmd::start_watch(app.handle().clone()); Ok(()) }) .invoke_handler(tauri::generate_handler![ signin_check, + api_status, + api_new_token, + api_publish, frame_color, backup_save, backup_pick, @@ -494,7 +525,10 @@ fn main() { libcmd::lyrics_get, libcmd::lyrics_save, libcmd::lyrics_save_text, - libcmd::set_fullscreen + libcmd::set_fullscreen, + libcmd::playlist_link, + libcmd::playlist_relocate, + libcmd::playlist_unlink ]) .build(tauri::generate_context!()) .expect("error while building atmosphere") diff --git a/src/settings.rs b/src/settings.rs index be8911b..923ab1b 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -60,6 +60,11 @@ pub struct Settings { pub embed_chapters: bool, pub cookies_browser: String, pub cookies_file: String, + pub api_enabled: bool, + pub api_port: u16, + pub api_read: bool, + pub api_control: bool, + pub api_links: bool, pub proxy: String, pub rate_limit: String, pub ytdlp_path: String, @@ -100,6 +105,11 @@ impl Default for Settings { embed_chapters: true, cookies_browser: String::new(), cookies_file: String::new(), + api_enabled: false, + api_port: 47823, + api_read: true, + api_control: true, + api_links: false, proxy: String::new(), rate_limit: String::new(), ytdlp_path: String::new(), @@ -138,6 +148,11 @@ pub struct SettingsPatch { pub embed_chapters: Option, pub cookies_browser: Option, pub cookies_file: Option, + pub api_enabled: Option, + pub api_port: Option, + pub api_read: Option, + pub api_control: Option, + pub api_links: Option, pub proxy: Option, pub rate_limit: Option, pub ytdlp_path: Option, @@ -155,6 +170,18 @@ pub struct SettingsPatch { } impl Settings { + pub fn accept_from_installer(&mut self) -> bool { + if self.rights_ok() || !cfg!(windows) { + return false; + } + let marker = std::env::current_exe().ok().and_then(|e| e.parent().map(|d| d.join("rights-accepted"))); + let ok = marker.and_then(|m| std::fs::read_to_string(m).ok()).is_some_and(|t| t.trim() == format!("terms={TERMS_VERSION}")); + if ok { + self.accept_rights(); + } + ok + } + pub fn rights_ok(&self) -> bool { self.rights_version == TERMS_VERSION } @@ -174,6 +201,10 @@ impl Settings { ($($f:ident),*) => { $( if let Some(v) = p.$f { self.$f = v; } )* }; } set!(save_as, embed_metadata, collection_folders, number_tracks, skip_downloaded, sponsorblock, embed_subtitles, embed_chapters, watch_clipboard); + set!(api_enabled, api_read, api_control, api_links); + if let Some(p) = p.api_port.filter(|p| *p >= 1024) { + self.api_port = p; + } set!(cookies_browser, cookies_file, proxy, rate_limit, ytdlp_path, ffmpeg_path, subtitle_langs, musixmatch_key, playlist_copy, lyrics_on_download, custom_lyrics, fx_presets); if let Some(v) = p.library_folders { let mut seen = std::collections::HashSet::new(); @@ -265,3 +296,12 @@ mod tests { assert_eq!(s.mp3_bitrate, 192); } } + +#[cfg(test)] +mod terms_tests { + #[test] + fn installer_records_the_current_terms_version() { + let hooks = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/installer/hooks.nsh")).unwrap(); + assert!(hooks.contains(&format!("!define ATMO_TERMS_VERSION {}", super::TERMS_VERSION)), "bump ATMO_TERMS_VERSION in installer/hooks.nsh along with TERMS_VERSION"); + } +} diff --git a/ui/app.js b/ui/app.js index b6b2211..212c0fc 100644 --- a/ui/app.js +++ b/ui/app.js @@ -156,6 +156,7 @@ async function init() { bindLyrics(); bindBackup(); bindMini(); + bindConnect(); bindStats(); await listen("atmosphere://job", (e) => onJob(e.payload)); await listen("atmosphere://probe", (e) => onProbe(e.payload)); @@ -1384,9 +1385,10 @@ function renderSettings() { $("#concValue").textContent = String(s.concurrency); $$("[data-seg=theme] button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.value === s.theme))); const at = s.rightsAcceptedAt ? new Intl.DateTimeFormat(undefined, { dateStyle: "long" }).format(new Date(s.rightsAcceptedAt * 1000)) : ""; - $("#rightsInfo").textContent = at ? `You confirmed it on ${at}. Withdrawing it cancels downloads and asks again.` : "Not confirmed yet."; + $("#rightsInfo").textContent = at ? `You agreed on ${at}. Withdrawing it cancels downloads and asks again in the app.` : "Not confirmed yet."; renderTemplatePreview(); renderSignin(); + if (typeof renderApiSettings === "function") renderApiSettings(); renderToolSettings(); renderLibrarySettings(); renderLyricsSettings(); diff --git a/ui/connect.js b/ui/connect.js new file mode 100644 index 0000000..b18cbd0 --- /dev/null +++ b/ui/connect.js @@ -0,0 +1,124 @@ +// atmosphere · connect.js · Settings and player bridge for the opt-in local API other apps can use +const Connect = { timer: null, beat: null }; +const API_DOCS = "https://github.com/pvrzz/atmosphere/blob/main/docs/api.md"; + +function apiSnapshot() { + const t = Player.current; + const a = Player.audio; + return { + playing: !!t && !a.paused, + track: t ? { id: t.id, title: t.title, artist: t.artist, album: t.album, albumArtist: t.albumArtist, durationMs: t.durationMs, artwork: t.art ? `/v1/artwork/${t.id}` : null } : null, + positionMs: Math.round((a.currentTime || 0) * 1000), + updatedAt: Date.now(), + volume: Player.volume, + muted: !!Player.muted, + shuffle: !!Player.shuffle, + repeat: Player.repeat || "off", + queue: { index: Player.index, length: Player.queue.length }, + }; +} + +function apiPublishSoon() { + if (!state.settings?.apiEnabled) return; + clearTimeout(Connect.timer); + Connect.timer = setTimeout(() => invoke("api_publish", { state: apiSnapshot() }).catch(() => {}), 120); +} + +function ago(secs) { + const d = Math.max(0, Date.now() / 1000 - secs); + if (d < 60) return "just now"; + if (d < 3600) return `${Math.round(d / 60)} min ago`; + if (d < 86400) return `${Math.round(d / 3600)} h ago`; + return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(new Date(secs * 1000)); +} + +async function renderApiSettings() { + const el = $("#apiStatus"); + if (!el || !state.settings) return; + const st = await invoke("api_status").catch(() => null); + if (!st) return; + const s = state.settings; + el.dataset.kind = ""; + if (!s.apiEnabled) el.textContent = "Off. No other app can reach Atmosphere."; + else if (st.error) { + el.textContent = st.error; + el.dataset.kind = "err"; + } else if (st.running) { + el.textContent = `On at http://127.0.0.1:${st.port}${st.lastUsed ? ` · last used ${ago(st.lastUsed)}${st.lastClient ? ` by ${st.lastClient}` : ""}` : " · not used yet"}`; + el.dataset.kind = "ok"; + } else el.textContent = "Starting…"; + $("#apiTokenBtn").textContent = st.hasToken ? "Replace token" : "Create token"; + $("#apiTokenNote").textContent = st.hasToken + ? `Created ${ago(st.tokenCreated)}. Replacing it disconnects every app using the old one.` + : "Apps send this token with every request. It's shown once; Atmosphere keeps only a fingerprint."; + const port = $("#apiPort"); + if (document.activeElement !== port) port.value = String(s.apiPort || 47823); + $$(".api-scope").forEach((row) => row.classList.toggle("dim", !s.apiEnabled)); +} + +async function newApiToken() { + const had = (await invoke("api_status").catch(() => null))?.hasToken; + if (had && !(await confirmBox("Replace the access token?", "Apps using the current token stop working until you give them the new one.", "Replace"))) return; + try { + const token = await invoke("api_new_token"); + $("#apiTokenValue").textContent = token; + $("#apiTokenBox").hidden = false; + renderApiSettings(); + } catch (e) { + toast(errText(e), "err"); + } +} + +function runApiAction(p) { + switch (p.action) { + case "status": return renderApiSettings(); + case "play": return Player.play(); + case "pause": return Player.pause(); + case "toggle": return Player.toggle(); + case "next": return Player.next(); + case "previous": return Player.prev(); + case "seek": return Player.seek(p.position); + case "volume": Player.muted = false; return Player.setVolume(p.volume); + case "queue": { + const tracks = (p.ids || []).map((id) => Lib.byId.get(id)).filter(Boolean); + if (!tracks.length) return; + if (p.mode === "now") return Player.setQueue(tracks, 0); + if (p.mode === "next") return Player.playNext(tracks); + return Player.addToQueue(tracks); + } + case "link": + if (Mini?.on) closeMini(); + go("get"); + fetchText(p.url); + return toast("Another app sent a link. Review it before saving anything.", ""); + } +} + +function bindConnect() { + listen("atmosphere://api", (e) => runApiAction(e.payload || {})); + window.addEventListener("player", (e) => { + if (e.detail.type !== "time") apiPublishSoon(); + }); + Player.audio.addEventListener("seeked", apiPublishSoon); + Connect.beat = setInterval(() => { + if (!Player.audio.paused) apiPublishSoon(); + }, 10000); + $("#apiTokenBtn")?.addEventListener("click", newApiToken); + $("#apiTokenCopy")?.addEventListener("click", async () => { + await invoke("clipboard_write", { text: $("#apiTokenValue").textContent }).catch(() => {}); + toast("Token copied", "ok"); + }); + $("#apiDocs")?.addEventListener("click", () => invoke("open_link", { url: API_DOCS }).catch(() => {})); + $("#apiEnabledToggle")?.addEventListener("change", () => setTimeout(() => { renderApiSettings(); apiPublishSoon(); }, 400)); + $("#apiPort")?.addEventListener("change", async (e) => { + const n = parseInt(e.target.value, 10); + if (!(n >= 1024 && n <= 65535)) { + toast("Choose a port between 1024 and 65535.", "err"); + e.target.value = String(state.settings.apiPort || 47823); + return; + } + await patch({ apiPort: n }); + setTimeout(renderApiSettings, 400); + }); + renderApiSettings(); +} diff --git a/ui/index.html b/ui/index.html index 1827bda..ed7a8b6 100644 --- a/ui/index.html +++ b/ui/index.html @@ -44,10 +44,10 @@ +

Connections

+

Let other apps on this computer, like stream overlays, status tools or your own scripts, see what's playing and control Atmosphere. It stays off unless you turn it on.

+
+ +
+
Access tokenApps send this token with every request. It's shown once; Atmosphere keeps only a fingerprint. + +
+ +
+ + + +
PortOnly reachable from this computer.
+
+

Storage

Temporary files are removed automatically on every launch and exit. Here's everything else Atmosphere keeps.

@@ -333,7 +349,6 @@ -

Atmosphere never bypasses DRM or paywalls, and skips preview-only media.

@@ -359,5 +374,6 @@ + diff --git a/ui/library.js b/ui/library.js index df367a2..2a431f5 100644 --- a/ui/library.js +++ b/ui/library.js @@ -335,7 +335,7 @@ function renderPlaylistNav() { const lists = Lib.data?.playlists || []; nav.replaceChildren( ...lists.map((p) => { - const b = h("button", { class: "nav-item small", "data-playlist": p.name, onclick: () => openLib("playlist", p.name) }, icon("playlist"), h("span", { class: "nav-label" }, p.name), h("span", { class: "nav-meta" }, String(p.order.length))); + const b = h("button", { class: `nav-item small ${p.missing ? "missing" : ""}`, "data-playlist": p.name, title: p.missing ? `Folder not found: ${p.path}` : p.linked ? p.path : null, onclick: () => openLib("playlist", p.name) }, icon(p.missing ? "alert-circle" : p.linked ? "folder" : "playlist"), h("span", { class: "nav-label" }, p.name), h("span", { class: "nav-meta" }, p.missing ? "Missing" : String(p.order.length))); b.addEventListener("dragover", (e) => { if (e.dataTransfer.types.includes("application/x-atmo-tracks")) { e.preventDefault(); b.classList.add("drop"); } }); b.addEventListener("dragleave", () => b.classList.remove("drop")); b.addEventListener("drop", (e) => { @@ -362,7 +362,11 @@ async function addToPlaylist(name, tracks) { } async function removeFromPlaylist(name, tracks) { - const ok = await confirmBox(`Remove ${tracks.length === 1 ? `“${tracks[0].title}”` : plural(tracks.length, "song")} from ${name}?`, `The playlist's copy goes to your ${isMac ? "Trash" : "Recycle Bin"}. The song stays in your library.`, "Remove"); + const pl = (Lib.data?.playlists || []).find((x) => x.name === name); + const bin = isMac ? "Trash" : "Recycle Bin"; + const ok = pl?.linked + ? await confirmBox(`Remove ${tracks.length === 1 ? `“${tracks[0].title}”` : plural(tracks.length, "song")} from ${name}?`, `This is your own folder, so the file itself moves from it to your ${bin}. If it's the only copy, it leaves your library too. You can restore it from the ${bin}.`, "Move to " + bin) + : await confirmBox(`Remove ${tracks.length === 1 ? `“${tracks[0].title}”` : plural(tracks.length, "song")} from ${name}?`, `The playlist's copy goes to your ${isMac ? "Trash" : "Recycle Bin"}. The song stays in your library.`, "Remove"); if (!ok) return; try { await invoke("playlist_remove", { name, ids: tracks.map((t) => t.id) }); @@ -409,6 +413,49 @@ function modal(title, body, actions) { const confirmBox = (title, text, label) => modal(title, h("p", { class: "muted" }, text), [{ label: "Cancel", value: false }, { label, value: true, primary: true }]); +async function linkFolder() { + try { + const name = await invoke("playlist_link"); + if (!name) return; + toast(`Added “${name}” as a playlist. Atmosphere won't move or delete the folder.`, "ok"); + await loadLibrary(); + openLib("playlist", name); + } catch (e) { + toast(errText(e), "err"); + } +} + +async function relocateFolder(name) { + try { + if (await invoke("playlist_relocate", { name })) { + toast(`Found “${name}” again`, "ok"); + await loadLibrary(); + } + } catch (e) { + toast(errText(e), "err"); + } +} + +async function unlinkFolder(name) { + const ok = await confirmBox(`Remove “${name}” from Atmosphere?`, "The folder and every song in it stay exactly where they are on your device. Atmosphere just stops showing it as a playlist.", "Remove"); + if (!ok) return; + try { + await invoke("playlist_unlink", { name }); + openLib("songs", null, false); + } catch (e) { + toast(errText(e), "err"); + } +} + +function playlistAddMenu(e) { + e.stopPropagation(); + const r = e.currentTarget.getBoundingClientRect(); + menuAt(r.left, r.bottom + 4, [ + { label: "New playlist", run: () => newPlaylist() }, + { label: "Add existing folder…", run: linkFolder }, + ]); +} + async function newPlaylist(tracks = []) { const input = h("input", { class: "text wide", placeholder: "Playlist name", "aria-label": "Playlist name" }); const ok = await modal("New playlist", h("div", { class: "stack" }, input, h("p", { class: "muted small" }, "It's a folder of songs on this device. Phones, USB drives and other players can use it as-is.")), [{ label: "Cancel", value: false }, { label: "Create", value: true, primary: true }]); @@ -608,6 +655,20 @@ function mosaic(tracks) { function playlistView(root, name) { const p = (Lib.data?.playlists || []).find((x) => x.name === name); if (!p) return root.append(libHead("Playlist not found", "Its folder may have been moved or deleted.")); + if (p.missing) { + root.append( + libHead(p.name, "Linked folder"), + h("div", { class: "lib-empty missing-folder" }, + icon("alert-circle"), + h("h2", {}, "This folder can't be found"), + h("p", {}, "It may have been moved or renamed, or it's on a drive that isn't connected. Atmosphere checks again every few seconds and brings it back as soon as it's there."), + h("code", { class: "path" }, p.path), + h("div", { class: "row center" }, + h("button", { class: "btn primary", onclick: () => relocateFolder(p.name) }, icon("folder-open"), "Locate folder…"), + h("button", { class: "btn ghost", onclick: () => unlinkFolder(p.name) }, "Remove from Atmosphere"))) + ); + return; + } const tracks = p.order.map((id) => Lib.byId.get(id)).filter(Boolean); const dur = tracks.reduce((n, t) => n + (t.durationMs || 0), 0); const title = h("h1", { class: "hero-title editable", contenteditable: "plaintext-only", spellcheck: "false", "aria-label": "Playlist name", onkeydown: (e) => { if (e.key === "Enter") { e.preventDefault(); e.target.blur(); } } }, p.name); @@ -627,17 +688,19 @@ function playlistView(root, name) { h("div", { class: "hero-bg", style: tracks[0]?.art ? `background-image:url("${artUrl(tracks[0].art)}")` : "" }), mosaic(tracks), h("div", { class: "hero-meta" }, - h("div", { class: "kind-line" }, h("span", { class: "kind-btn", style: "cursor:default" }, icon("folder"), "Playlist folder")), + h("div", { class: "kind-line" }, h("span", { class: "kind-btn", style: "cursor:default" }, icon(p.linked ? "link" : "folder"), p.linked ? "Your folder" : "Playlist folder")), title, h("p", { class: "view-sub" }, `${plural(tracks.length, "song")}${dur ? " · " + fmtLong(dur) : ""}`), h("button", { class: "link path", title: "Open this folder", onclick: () => invoke("reveal", { path: p.path }) }, p.path), h("div", { class: "row" }, ...playBtns(tracks), h("button", { class: "btn ghost", onclick: async () => { try { const n = await invoke("playlist_add_files", { name: p.name }); if (n) toast(`Added ${plural(n, "song")}`, "ok"); } catch (e) { toast(errText(e), "err"); } } }, icon("plus"), "Add files…"), - h("button", { class: "btn ghost danger", onclick: async () => { if (await confirmBox(`Delete “${p.name}”?`, "The playlist folder goes to your Recycle Bin or Trash. Songs in your library aren't touched.", "Delete")) { await invoke("playlist_delete", { name: p.name }).catch((e) => toast(errText(e), "err")); openLib("songs", null, false); } } }, icon("trash"), "Delete")))) + p.linked + ? h("button", { class: "btn ghost", onclick: () => unlinkFolder(p.name) }, icon("x"), "Remove from Atmosphere") + : h("button", { class: "btn ghost danger", onclick: async () => { if (await confirmBox(`Delete “${p.name}”?`, "The playlist folder goes to your Recycle Bin or Trash. Songs in your library aren't touched.", "Delete")) { await invoke("playlist_delete", { name: p.name }).catch((e) => toast(errText(e), "err")); openLib("songs", null, false); } } }, icon("trash"), "Delete")))) ); if (Lib.back.length) root.firstChild.prepend(h("button", { class: "icon-btn back on-hero", "aria-label": "Back", onclick: libBack }, icon("arrow-left"))); if (!tracks.length) return root.append(h("div", { class: "lib-empty slim" }, h("p", {}, "Drag songs onto this playlist in the sidebar, use “Add to playlist” from any song's menu, or add files from your computer."))); - root.append(h("div", { class: "pad-x" }, h("p", { class: "muted small hint-line" }, "Drag rows to reorder. The order is saved in the folder's playlist.m3u8, so other players see it too."), trackList(tracks, { cover: true, playlist: p.name }))); + root.append(h("div", { class: "pad-x" }, h("p", { class: "muted small hint-line" }, p.linked ? "This is your own folder; songs in subfolders are included. Drag rows to reorder, saved in a playlist.m3u8 inside it." : "Drag rows to reorder. The order is saved in the folder's playlist.m3u8, so other players see it too."), trackList(tracks, { cover: true, playlist: p.name }))); } function likedView(root) { @@ -755,7 +818,7 @@ async function cleanStorage(ids) { /* boot */ function bindLibrary() { $$("[data-lib]").forEach((b) => b.addEventListener("click", () => { Lib.back = []; openLib(b.dataset.lib, null, false); })); - $("#newPlaylistBtn").addEventListener("click", () => newPlaylist()); + $("#newPlaylistBtn").addEventListener("click", playlistAddMenu); $("#libScroll").addEventListener("scroll", () => Lib.drawSongs && requestAnimationFrame(Lib.drawSongs), { passive: true }); window.addEventListener("resize", () => Lib.drawSongs && Lib.drawSongs()); window.addEventListener("player", (e) => { if (e.detail.type === "track") markPlaying(); }); @@ -844,6 +907,26 @@ function playlistMenu(e, name) { const p = (Lib.data?.playlists || []).find((x) => x.name === name); if (!p) return; const tracks = p.order.map((id) => Lib.byId.get(id)).filter(Boolean); + if (p.missing) { + return menuAt(e.clientX, e.clientY, [ + { label: "Locate folder…", run: () => relocateFolder(name) }, + "-", + { label: "Remove from Atmosphere…", run: () => unlinkFolder(name) }, + ]); + } + if (p.linked) { + return menuAt(e.clientX, e.clientY, [ + { label: "Play", disabled: !tracks.length, run: () => playList(tracks, 0, false) }, + { label: "Shuffle", disabled: !tracks.length, run: () => playList(tracks, Math.floor(Math.random() * tracks.length), true) }, + "-", + { label: "Add files…", run: () => invoke("playlist_add_files", { name }).catch((err) => toast(errText(err), "err")) }, + { label: "Rename in Atmosphere…", run: () => renamePlaylist(name) }, + { label: "Show in folder", run: () => invoke("reveal", { path: p.path }) }, + { label: "Locate a different folder…", run: () => relocateFolder(name) }, + "-", + { label: "Remove from Atmosphere…", run: () => unlinkFolder(name) }, + ]); + } menuAt(e.clientX, e.clientY, [ { label: "Play", disabled: !tracks.length, run: () => playList(tracks, 0, false) }, { label: "Shuffle", disabled: !tracks.length, run: () => playList(tracks, Math.floor(Math.random() * tracks.length), true) }, diff --git a/ui/styles.css b/ui/styles.css index d231927..dbbafb1 100644 --- a/ui/styles.css +++ b/ui/styles.css @@ -949,3 +949,23 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa @media (prefers-reduced-motion: reduce) { .mini-bg, .mini-play { transition: none; } } .mini.mac .mini-top { padding-left: 78px; } .mini.mac .mini-brand { display: none; } + +/* linked playlist folders */ +.nav-item.missing { color: var(--text-3); } +.nav-item.missing .nav-meta { color: var(--warn, #d9a441); font-size: 11px; } +.missing-folder { max-width: 520px; margin: var(--s6) auto; text-align: center; gap: var(--s3); } +.missing-folder > .i svg { width: 36px; height: 36px; color: var(--warn, #d9a441); } +.missing-folder h2 { font: 650 18px/1.3 var(--font-display); margin: 0; } +.missing-folder p { margin: 0; color: var(--text-2); } +.missing-folder code.path { font-size: 12px; color: var(--text-3); overflow-wrap: anywhere; padding: 6px 10px; border-radius: 8px; background: var(--surface); border: 1px solid var(--hairline); } +.row.center { justify-content: center; } + +/* connections */ +.api-status[data-kind="ok"] { color: var(--ok); } +.api-status[data-kind="err"] { color: var(--err); } +.api-token { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s2); margin-top: var(--s2); } +.api-token code { font: 12px/1.4 ui-monospace, "Cascadia Code", Consolas, monospace; padding: 6px 10px; border-radius: 8px; background: var(--surface-2, var(--surface)); border: 1px solid var(--border); user-select: all; overflow-wrap: anywhere; max-width: 100%; } +.api-token p { flex-basis: 100%; margin: 0; } +.api-scope.dim { opacity: 0.55; } +#apiDocs { color: var(--accent); font: inherit; padding: 0; text-decoration: underline; text-underline-offset: 2px; text-decoration-color: color-mix(in srgb, var(--accent) 40%, transparent); } +#apiDocs:hover { text-decoration-color: currentColor; }