use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; use serde::{Deserialize, Serialize}; /// Status der Anmeldung beim Audible-Konto. #[derive(Debug, Serialize)] pub struct AuthStatus { pub logged_in: bool, pub profiles: Vec, pub auth_dir: String, } /// Ein Buch aus der Audible-Bibliothek (Export-JSON, Felder nach Spike). #[derive(Debug, Deserialize, Clone, Serialize)] pub struct Book { pub asin: String, pub title: String, #[serde(default)] pub authors: String, #[serde(default)] pub narrators: String, #[serde(default)] pub runtime_length_min: i64, #[serde(default)] pub cover_url: String, #[serde(default)] pub percent_complete: f64, #[serde(default)] pub is_finished: bool, #[serde(default)] pub date_added: String, #[serde(default)] pub genres: String, /// lokal vorhanden (book.m4b im Datenverzeichnis) — vom Backend gesetzt #[serde(default, skip_deserializing)] pub local: bool, } /// Zugriffsschicht auf Audible — hinter diesem Trait kapseln, damit /// `audible-cli` später austauschbar bleibt (spec E-02). pub trait AudibleClient: Send + Sync { fn auth_status(&self) -> Result; /// Startet die interaktive Anmeldung (audible-cli) im Terminal. /// true = Terminal gestartet, der Nutzer meldet sich dort an; dann /// `auth_status` erneut prüfen. fn start_login(&self) -> Result; /// Startet `manage auth-file decrypt` im Terminal — nötig, wenn die /// Auth-Datei verschlüsselt erzeugt wurde. fn start_decrypt(&self) -> Result; fn library(&self) -> Result, String>; } #[derive(Clone)] pub struct CliAudibleClient { auth_dir: PathBuf, } impl CliAudibleClient { /// Standard: `~/.audible` (audible-cli-Standardpfad), per /// `HOERWERK_AUDIBLE_DIR` überschreibbar (z. B. für KT-010). pub fn new() -> Self { Self::with_auth_dir(default_auth_dir()) } pub fn with_auth_dir(dir: PathBuf) -> Self { Self { auth_dir: dir } } } /// Findet die audible-CLI: bevorzugt `~/.local/bin/audible` (pipx), /// sonst `$PATH`. Übergabe als Argumentliste, nie über eine Shell. pub fn audible_binary() -> Option { if let Some(home) = home_dir() { let p = home.join(".local/bin/audible"); if p.is_file() { return Some(p); } } if let Ok(path) = env::var("PATH") { for dir in env::split_paths(&path) { let p = dir.join("audible"); if p.is_file() { return Some(p); } } } None } impl Default for CliAudibleClient { fn default() -> Self { Self::new() } } pub(crate) fn home_dir() -> Option { env::var("HOME").ok().map(PathBuf::from) } fn default_auth_dir() -> PathBuf { home_dir() .map(|h| h.join(".audible")) .unwrap_or_else(|| PathBuf::from(".")) } /// Lokale Bücherablage (spec): ~/.local/share/hoerwerk/books//book.m4b, /// per HOERWERK_BOOKS_DIR überschreibbar. pub(crate) fn books_dir() -> PathBuf { env::var("HOERWERK_BOOKS_DIR") .map(PathBuf::from) .unwrap_or_else(|_| { home_dir() .map(|h| h.join(".local/share/hoerwerk/books")) .unwrap_or_else(|| PathBuf::from("books")) }) } impl AudibleClient for CliAudibleClient { fn auth_status(&self) -> Result { let mut profiles = Vec::new(); let entries = fs::read_dir(&self.auth_dir).map_err(|e| { format!( "Auth-Verzeichnis nicht lesbar ({}): {e}", self.auth_dir.display() ) })?; for entry in entries.flatten() { let p = entry.path(); let is_json = p .extension() .and_then(|e| e.to_str()) .map(|e| e.eq_ignore_ascii_case("json")) .unwrap_or(false); if is_json { if let Some(stem) = p.file_stem().and_then(|s| s.to_str()) { profiles.push(stem.to_string()); } } } Ok(AuthStatus { logged_in: !profiles.is_empty(), profiles, auth_dir: self.auth_dir.display().to_string(), }) } /// Startet `manage auth-file decrypt` im Terminal (interaktiv, Passwort /// bleibt im Terminal). Bekannter Profilname wird mitgeliefert. fn start_decrypt(&self) -> Result { let bin = audible_binary().ok_or_else(|| { "audible-cli nicht gefunden — Installation: pipx install audible-cli".to_string() })?; let Some((term, needs_e, hold)) = find_terminal() else { return Err("kein unterstütztes Terminal gefunden — bitte in deiner Shell: audible manage auth-file decrypt".to_string()); }; let mut cmd = Command::new(term); if !hold.is_empty() { cmd.arg(hold); } if needs_e { cmd.arg("-e"); } cmd.arg(&bin).args(["manage", "auth-file", "decrypt"]); if let Ok(s) = self.auth_status() { if let Some(name) = s.profiles.first() { cmd.arg("-f").arg(name); } } cmd.spawn() .map_err(|e| format!("Terminal konnte nicht gestartet werden: {e}"))?; Ok(true) } fn start_login(&self) -> Result { let bin = audible_binary().ok_or_else(|| { "audible-cli nicht gefunden — Installation: pipx install audible-cli".to_string() })?; let Some((term, needs_e, hold)) = find_terminal() else { return Err("kein unterstütztes Terminal gefunden — bitte in deiner Shell ausführen: audible manage auth-file add".to_string()); }; // Argumentliste, keine Shell und kein zusammengesetzter String (spec). // Reihenfolge: Terminal-flags (--hold) VOR -e, danach Programm+Args. // `manage auth-file add` statt `quickstart`: funktioniert auch, wenn // schon eine Konfig existiert (quickstart verweigert dann). let mut cmd = Command::new(term); if !hold.is_empty() { cmd.arg(hold); } if needs_e { cmd.arg("-e"); } cmd.arg(&bin) .args(["manage", "auth-file", "add", "-cc", "de"]); cmd.spawn() .map_err(|e| format!("Terminal konnte nicht gestartet werden: {e}"))?; Ok(true) } fn library(&self) -> Result, String> { let bin = audible_binary().ok_or_else(|| { "audible-cli nicht gefunden — Installation: pipx install audible-cli".to_string() })?; let out = env::temp_dir().join(format!("hoerwerk-library-{}.json", std::process::id())); let exported = Command::new(&bin) .args(["library", "export", "-f", "json", "-o"]) .arg(&out) .output() .map_err(|e| format!("audible library export fehlgeschlagen: {e}"))?; let stderr = String::from_utf8_lossy(&exported.stderr); if !exported.status.success() { let _ = fs::remove_file(&out); return Err(reduce_noise(&stderr)); } let content = match fs::read_to_string(&out) { Ok(c) => c, Err(e) => { return Err(format!("Export-Datei nicht lesbar: {e}")); } }; let _ = fs::remove_file(&out); let mut books = parse_library(&content)?; let dir = books_dir(); for b in &mut books { b.local = dir.join(&b.asin).join("book.m4b").is_file(); } Ok(books) } } /// Wandelt den Bibliotheks-Export in `Book`s (separat getestet). pub fn parse_library(content: &str) -> Result, String> { serde_json::from_str(content).map_err(|e| format!("Bibliothek-JSON nicht parsebar: {e}")) } /// Lokal abgelegte Bücher (book.m4b im Bücher-Verzeichnis) — auch nutzbar, /// wenn Audible gerade nicht erreichbar ist. Metadaten aus m4b-Tags. pub fn local_books() -> Vec { let dir = books_dir(); let mut out = Vec::new(); let Ok(rd) = fs::read_dir(dir) else { return out; }; for e in rd.flatten() { let book_dir = e.path(); let m4b = book_dir.join("book.m4b"); if !m4b.is_file() { continue; } let asin = book_dir .file_name() .and_then(|n| n.to_str()) .unwrap_or("?") .to_string(); let (title, authors, runtime_min) = probe_m4b(&m4b); let cover_file = book_dir.join("cover.jpg"); let cover_url = if cover_file.is_file() { cover_file.to_string_lossy().to_string() } else { String::new() }; out.push(Book { asin: asin.clone(), title: if title.is_empty() { format!("Unbekannt ({asin})") } else { title }, authors, narrators: String::new(), runtime_length_min: runtime_min.max(0), cover_url, percent_complete: 0.0, is_finished: false, date_added: String::new(), genres: String::new(), local: true, }); } out } /// ffprobe: Tag title/artist + Dauer in Minuten. fn probe_m4b(m4b: &Path) -> (String, String, i64) { let out = std::process::Command::new("ffprobe") .args(["-v", "error", "-show_format", "-of", "json"]) .arg(m4b) .output(); let mut title = String::new(); let mut artist = String::new(); let mut minutes = 0i64; if let Ok(o) = out { let txt = String::from_utf8_lossy(&o.stdout); if let Ok(v) = serde_json::from_str::(&txt) { title = v["format"]["tags"]["title"] .as_str() .unwrap_or("") .to_string(); artist = v["format"]["tags"]["artist"] .as_str() .unwrap_or("") .to_string(); if let Some(sec) = v["format"]["duration"].as_str().and_then(|s| s.parse::().ok()) { minutes = (sec / 60.0).round() as i64; } } } // Falls kein Titel im Tag: ASIN-Ordnername als Anhaltspunkt. if title.is_empty() { if let Some(p) = m4b.parent() { title = p .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); } } (title, artist, minutes) } // Manuelle Altersnotizen (bewertbar pro Buch, lokale JSON-Ablage) #[derive(Debug, Clone, Serialize)] pub struct Labels(pub std::collections::BTreeMap); fn labels_path() -> PathBuf { books_dir() .parent() .map(|p| p.join("labels.json")) .unwrap_or_else(|| PathBuf::from("labels.json")) } pub fn alter_notes() -> Labels { let map: std::collections::BTreeMap = fs::read_to_string(labels_path()) .ok() .and_then(|txt| serde_json::from_str(&txt).ok()) .unwrap_or_default(); Labels(map) } pub fn set_alter_note(asin: &str, note: Option) -> Result<(), String> { let asin = asin.trim().to_string(); if asin.is_empty() { return Err("keine ASIN angegeben".to_string()); } let mut l = alter_notes(); let note = note.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()); match note { Some(n) => { l.0.insert(asin, n); } None => { l.0.remove(&asin); } } if let Some(parent) = labels_path().parent() { fs::create_dir_all(parent).map_err(|e| format!("Notiz-Ordner: {e}"))?; } let path = labels_path(); let tmp = path.with_extension("json.tmp"); fs::write(&tmp, serde_json::to_vec(&l).unwrap_or_default()) .map_err(|e| format!("Notiz schreiben: {e}"))?; fs::rename(&tmp, &path).map_err(|e| format!("Notiz speichern: {e}") ) } /// Einzeldetails per Audible-API (Beschreibung u. a.) — on demand. #[derive(Debug, Clone, Serialize)] #[derive(serde::Deserialize)] pub struct BookExtra { pub description: String, pub language: String, pub format_type: String, pub release_date: String, } pub fn fetch_details(asin: &str) -> Result { // Cache im Buchordner (falls lokal vorhanden): einmalig holen, danach offline nutzbar let cache = books_dir().join(asin).join("details.json"); if let Ok(txt) = fs::read_to_string(&cache) { if let Ok(x) = serde_json::from_str::(&txt) { return Ok(x); } } let fetched = fetch_details_online(asin)?; if cache.parent().is_some_and(|p| p.is_dir()) { let _ = fs::write(&cache, serde_json::to_vec(&fetched).unwrap_or_default()); } Ok(fetched) } fn fetch_details_online(asin: &str) -> Result { let bin = audible_binary().ok_or_else(|| { "audible-cli nicht gefunden — pipx install audible-cli".to_string() })?; let endpoint = format!( "/1.0/catalog/products/{asin}?response_groups=product_desc,product_attrs" ); let out = Command::new(&bin) .args(["api", &endpoint]) .stderr(std::process::Stdio::piped()) .output() .map_err(|e| format!("audible api: {e}"))?; let text = String::from_utf8_lossy(&out.stdout); let v: serde_json::Value = serde_json::from_str(text.trim()) .map_err(|e| format!("Details-JSON: {e}"))?; let p = &v["product"]; let strip_tags = |h: &str| -> String { let mut out = String::new(); let mut tags = 0usize; for ch in h.chars() { match ch { '<' => tags += 1, '>' => tags = tags.saturating_sub(1), c if tags == 0 => out.push(c), _ => {} } } out.trim().to_string() }; let desc = p["description"] .as_str() .or_else(|| p["merchandising_summary"].as_str()) .map(strip_tags) .unwrap_or_default(); Ok(BookExtra { description: desc, language: p["language"].as_str().unwrap_or("").to_string(), format_type: p["format_type"].as_str().unwrap_or("").to_string(), release_date: p["release_date"].as_str().unwrap_or("").to_string(), }) } fn now_ms() -> u128 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis()) .unwrap_or(0) } /// Serien-Zuordnung fürs Gruppieren (T-Feedback): asin → (Titel, Position). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SerieRef { pub title: String, pub sequence: f64, } fn series_path() -> PathBuf { books_dir() .parent() .map(|p| p.join("series.json")) .unwrap_or_else(|| PathBuf::from("series.json")) } #[derive(Serialize, Deserialize)] struct SerieCache { fetched_ms: u128, series: BTreeMap, } use std::collections::BTreeMap; pub fn series_bulk(refresh: bool) -> Result, String> { if !refresh { if let Ok(txt) = fs::read_to_string(series_path()) { if let Ok(c) = serde_json::from_str::(&txt) { if now_ms().saturating_sub(c.fetched_ms) < 24 * 3600 * 1000 { return Ok(c.series); } } } } let bin = audible_binary().ok_or_else(|| { "audible-cli nicht gefunden — pipx install audible-cli".to_string() })?; let mut map: BTreeMap = BTreeMap::new(); let mut page = 1u32; loop { let out = Command::new(&bin) .args(["api", "/1.0/library", "-p", "response_groups=series", "-p", "num_results=100", "-p", &format!("page={page}")]) .stderr(std::process::Stdio::null()) .output() .map_err(|e| format!("audible api library: {e}"))?; let txt = String::from_utf8_lossy(&out.stdout); let v: serde_json::Value = match serde_json::from_str(txt.trim()) { Ok(v) => v, Err(_) => break, }; let empty = Vec::new(); let items = v["items"].as_array().unwrap_or(&empty); if items.is_empty() { break; } for it in items { if let Some(asin) = it["asin"].as_str() { if let Some(s0) = it["series"].get(0) { let title = s0["title"].as_str().unwrap_or("").to_string(); if !title.is_empty() { let seq = s0["sequence"].as_str().and_then(|x| x.parse::().ok()).unwrap_or(0.0); map.insert(asin.to_string(), SerieRef { title, sequence: seq }); } } } } page += 1; if page > 30 { break; } } let cache = SerieCache { fetched_ms: now_ms(), series: map.clone() }; if let Some(parent) = series_path().parent() { let _ = fs::create_dir_all(parent); } let path = series_path(); let tmp = path.with_extension("json.tmp"); if fs::write(&tmp, serde_json::to_vec(&cache).unwrap_or_default()).is_ok() { let _ = fs::rename(&tmp, &path); } Ok(map) } // Manuelle Altersnotizen — lokale JSON-Ablage (siehe labels_path) /// Taugt stderr von audible-cli: Warnungen und Passwort-Prompts raus, /// echte Fehlertexte bleiben. pub(crate) fn reduce_noise(s: &str) -> String { let lower = |l: &str| l.to_lowercase(); let kept: Vec<&str> = s .lines() .filter(|l| { let l = lower(l); !(l.contains("userwarning") || l.contains("warning: password input") || l.contains("please enter") || l.contains("getpass") || l.contains("passwd =") || l.contains("press enter")) }) .collect(); let joined = kept.join("\n"); if joined.trim().is_empty() { "audible-cli meldete keinen Fehler, aber der Befehl schlug fehl.".to_string() } else { joined } } fn find_terminal() -> Option<(&'static str, bool, &'static str)> { // (Programm, heißt „-e Programm Args“, Flag das das Fenster nach Ende offenhält) const CANDIDATES: [(&str, bool, &str); 5] = [ ("konsole", true, "--hold"), ("kitty", true, "--hold"), ("alacritty", true, "--hold"), ("foot", false, ""), ("xterm", true, "-hold"), ]; for (name, needs_e, hold) in CANDIDATES { if is_in_path(name) { return Some((name, needs_e, hold)); } } None } fn is_in_path(name: &str) -> bool { if let Ok(path) = env::var("PATH") { for dir in env::split_paths(&path) { if dir.join(name).is_file() { return true; } } } false } #[cfg(test)] mod tests { use super::*; fn temp_dir() -> PathBuf { let d = env::temp_dir().join(format!( "hoerwerk-test-{}-{}", std::process::id(), chrono_len() )); fs::create_dir_all(&d).unwrap(); d } fn chrono_len() -> String { // kleiner uniq-Suffix ohne chrono: nanos seit Start via std use std::time::{SystemTime, UNIX_EPOCH}; let n = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); format!("{}", n.subsec_nanos()) } #[test] fn logged_in_wenn_auth_datei_vorhanden() { let d = temp_dir(); fs::write(d.join("testprof.json"), "{}").unwrap(); let c = CliAudibleClient::with_auth_dir(d.clone()); let s = c.auth_status().unwrap(); assert!(s.logged_in); assert_eq!(s.profiles, vec!["testprof".to_string()]); fs::remove_dir_all(d).unwrap(); } #[test] fn ausgeloggt_wenn_nichts_da() { let d = temp_dir(); let c = CliAudibleClient::with_auth_dir(d); let s = c.auth_status().unwrap(); assert!(!s.logged_in); } #[test] fn json_nur_fuer_auth_dateien() { let d = temp_dir(); fs::write(d.join("a.json"), "{}").unwrap(); fs::write(d.join("config.toml"), "").unwrap(); fs::write(d.join("txt.txt"), "{}").unwrap(); let c = CliAudibleClient::with_auth_dir(d); let s = c.auth_status().unwrap(); assert_eq!(s.profiles.len(), 1); assert!(s.profiles[0] == "a"); } #[test] fn parse_library_nimmt_pfelder() { let json = r#"[{"asin":"B08L4WJMDM","title":"Elfe 2","date_added":"2020-01-01"}]"#; let books = parse_library(json).unwrap(); assert_eq!(books.len(), 1); assert_eq!(books[0].asin, "B08L4WJMDM"); assert_eq!(books[0].runtime_length_min, 0); assert!(!books[0].is_finished); assert!(!books[0].local); assert_eq!(books[0].date_added, "2020-01-01"); assert!(parse_library("kaputt").is_err()); } #[test] fn noise_wird_gefiltert() { let s = "UserWarning: legace\nerror: 401\nPlease enter the auth-file password"; assert_eq!(reduce_noise(s), "error: 401"); } }