mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Linked playlist folders, local API, installer agreement
- Add existing folders as playlists; they're never moved or deleted by Atmosphere - Missing linked folders show Locate and Remove, and return when the drive reconnects - Opt-in local API for other apps: loopback only, hashed token, per-permission access, browser and DNS-rebinding requests refused, lockout after repeated bad tokens - Live now-playing events, library browsing, playback and queue control, links to Get - API guide in docs/api.md - Agreeing on the Windows installer's licence page counts as the rights agreement - Drop the redundant DRM line from the welcome screen
This commit is contained in:
+432
@@ -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<String>,
|
||||
has_token: bool,
|
||||
token_created: Option<u64>,
|
||||
last_used: Option<u64>,
|
||||
last_client: Option<String>,
|
||||
}
|
||||
|
||||
pub struct ApiHub {
|
||||
now: RwLock<Value>,
|
||||
tx: broadcast::Sender<Value>,
|
||||
token: RwLock<TokenFile>,
|
||||
failures: Mutex<VecDeque<Instant>>,
|
||||
server: Mutex<Option<tauri::async_runtime::JoinHandle<()>>>,
|
||||
status: Mutex<Status>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<Response> {
|
||||
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::<ApiHub>();
|
||||
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::<AppState>().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<Ctx>, h: HeaderMap) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Any) {
|
||||
return r;
|
||||
}
|
||||
let s = ctx.app.state::<AppState>().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<Ctx>, h: HeaderMap) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Read) {
|
||||
return r;
|
||||
}
|
||||
Json(ctx.app.state::<ApiHub>().now.read().unwrap().clone()).into_response()
|
||||
}
|
||||
|
||||
async fn events(State(ctx): State<Ctx>, h: HeaderMap) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Read) {
|
||||
return r;
|
||||
}
|
||||
let hub = ctx.app.state::<ApiHub>();
|
||||
let first = hub.now.read().unwrap().clone();
|
||||
let rx = hub.tx.subscribe();
|
||||
let ev = |v: Value| Ok::<Event, Infallible>(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<String>,
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
async fn tracks(State(ctx): State<Ctx>, h: HeaderMap, Query(q): Query<TrackQuery>) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Read) {
|
||||
return r;
|
||||
}
|
||||
let state = ctx.app.state::<AppState>();
|
||||
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<Value> = 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<Ctx>, h: HeaderMap) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Read) {
|
||||
return r;
|
||||
}
|
||||
let state = ctx.app.state::<AppState>();
|
||||
let pl = std::path::PathBuf::from(state.snapshot().playlists_dir);
|
||||
let list: Vec<Value> = 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<Ctx>, h: HeaderMap, UrlPath(id): UrlPath<String>) -> Response {
|
||||
if let Some(r) = guard(&ctx, &h, Scope::Read) {
|
||||
return r;
|
||||
}
|
||||
let lib = &ctx.app.state::<AppState>().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<Ctx>, h: HeaderMap, UrlPath(action): UrlPath<String>) -> 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<Ctx>, h: HeaderMap, Json(b): Json<Seek>) -> 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<Ctx>, h: HeaderMap, Json(b): Json<Volume>) -> 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<String>,
|
||||
mode: Option<String>,
|
||||
}
|
||||
|
||||
async fn queue(State(ctx): State<Ctx>, h: HeaderMap, Json(b): Json<QueueBody>) -> 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::<AppState>().library;
|
||||
let known: Vec<String> = 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<Ctx>, h: HeaderMap, Json(b): Json<LinkBody>) -> 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::<ApiHub>();
|
||||
if let Some(old) = hub.server.lock().unwrap().take() {
|
||||
old.abort();
|
||||
}
|
||||
let s = app.state::<AppState>().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::<ApiHub>();
|
||||
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"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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<String> {
|
||||
|
||||
+73
-1
@@ -85,7 +85,8 @@ pub fn start_watch(app: AppHandle) {
|
||||
let (roots, pl) = dirs(&app.state::<AppState>());
|
||||
let _ = std::fs::create_dir_all(&pl);
|
||||
let mut watched: Vec<PathBuf> = Vec::new();
|
||||
for r in roots.into_iter().chain(std::iter::once(pl)) {
|
||||
let linked: Vec<PathBuf> = app.state::<AppState>().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<String, bool> = std::collections::HashMap::new();
|
||||
loop {
|
||||
let state = app.state::<AppState>();
|
||||
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<Option<PathBuf>> {
|
||||
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<Option<String>> {
|
||||
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<bool> {
|
||||
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);
|
||||
|
||||
+225
-21
@@ -78,6 +78,14 @@ pub struct Playlist {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub order: Vec<String>,
|
||||
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<Stats>,
|
||||
artists: RwLock<HashMap<String, ArtistMeta>>,
|
||||
hidden: RwLock<HashSet<String>>,
|
||||
linked: RwLock<Vec<Linked>>,
|
||||
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<PathBuf> = 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<String, Track> = 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<Playlist> {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for entry in rd.flatten().filter(|e| e.path().is_dir()) {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
let 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<String> {
|
||||
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<String> {
|
||||
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<Track> = 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<usize> {
|
||||
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<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| self.track(id))
|
||||
.filter_map(|t| Path::new(&t.path).file_name().map(|f| f.to_string_lossy().into_owned()))
|
||||
.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<Linked> {
|
||||
self.linked.read().unwrap().clone()
|
||||
}
|
||||
|
||||
fn linked_path(&self, name: &str) -> Option<PathBuf> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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()));
|
||||
|
||||
+39
-5
@@ -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<SettingsView> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn save_settings(state: State<'_, AppState>, patch: SettingsPatch) -> CmdResult<SettingsView> {
|
||||
let before = state.snapshot().concurrency;
|
||||
fn save_settings(app: AppHandle, state: State<'_, AppState>, patch: SettingsPatch) -> CmdResult<SettingsView> {
|
||||
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<String> {
|
||||
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<engine::ToolStatus> {
|
||||
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")
|
||||
|
||||
@@ -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<bool>,
|
||||
pub cookies_browser: Option<String>,
|
||||
pub cookies_file: Option<String>,
|
||||
pub api_enabled: Option<bool>,
|
||||
pub api_port: Option<u16>,
|
||||
pub api_read: Option<bool>,
|
||||
pub api_control: Option<bool>,
|
||||
pub api_links: Option<bool>,
|
||||
pub proxy: Option<String>,
|
||||
pub rate_limit: Option<String>,
|
||||
pub ytdlp_path: Option<String>,
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user