diff --git a/src-tauri/src/audible.rs b/src-tauri/src/audible.rs index ab64be9..6dbae90 100644 --- a/src-tauri/src/audible.rs +++ b/src-tauri/src/audible.rs @@ -1,6 +1,6 @@ use std::env; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::Command; use serde::{Deserialize, Serialize}; @@ -233,6 +233,79 @@ 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); + 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: String::new(), + percent_complete: 0.0, + is_finished: false, + date_added: 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) +} + /// Taugt stderr von audible-cli: Warnungen und Passwort-Prompts raus, /// echte Fehlertexte bleiben. pub(crate) fn reduce_noise(s: &str) -> String { diff --git a/src-tauri/src/download.rs b/src-tauri/src/download.rs index 44b6c13..20685d8 100644 --- a/src-tauri/src/download.rs +++ b/src-tauri/src/download.rs @@ -178,9 +178,10 @@ impl DownloadMgr { } } - /// Geladene/gebrochene Rohdaten eines Buchs entfernen (Job-Verzeichnis - /// + Eintrag). Läuft gerade ein Job dafür, wird er gestoppt. - pub fn delete(&self, asin: &str) -> Result<(), String> { let asin = asin.trim().to_string(); + /// Alles eines Asins entfernen: Rohdaten (Cache) UND lokales Buch + /// (book.m4b/cover/chapters). Läuft gerade ein Job dafür, wird er gestoppt. + pub fn delete(&self, asin: &str) -> Result<(), String> { + let asin = asin.trim().to_string(); let mut g = self.inner.lock().unwrap(); g.queue.retain(|a| a != &asin); if g.items.get(&asin).map(|i| i.status == DlStatus::Running).unwrap_or(false) { @@ -198,8 +199,13 @@ impl DownloadMgr { if dir.exists() { fs::remove_dir_all(&dir).map_err(|e| format!("Verzeichnis löschen: {e}"))?; } - if !removed { - return Err(format!("{} hat keine geladenen Daten", asin)); + // lokales Buch entfernen (bestehend seit T-014) + let book_dir = crate::audible::books_dir().join(&asin); + if book_dir.exists() { + fs::remove_dir_all(&book_dir).map_err(|e| format!("Buch löschen: {e}"))?; + } + if !removed && !book_dir.exists() { + return Err(format!("{} hat nichts zu löschen", asin)); } Ok(()) } @@ -563,29 +569,43 @@ fn find_chapters(dir: &Path) -> Option { None } -/// Sucht die aufschlussreichste Zeile aus dem stderr-Fehlerprotokoll: -/// bevorzugt „error: failed for …“ (Enzeljob-Kontext), sonst letzte -/// „error:“-Zeile als Fallback. Zusammenfassung-Zeilen („1 job(s) failed“) -/// sollen nicht als Meldung landen. +/// Sucht die aufschlussreichste Zeile aus dem stderr-Fehlerprotokoll und +/// kürzt auf Klartext: "download_aaxc failed for X: AudibleCliException: …" +/// → "X: …"; bekannter Muster → verständliche Ursache. fn pick_download_error(stderr: &str) -> String { let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect(); - if let Some(job_line) = lines + let raw = if let Some(job_line) = lines .iter() .find(|l| l.starts_with("error:") && l.contains("failed for")) { - return job_line.trim_start_matches("error: ").to_string(); - } - if let Some(err_line) = lines + job_line.trim_start_matches("error: ").to_string() + } else if let Some(err_line) = lines .iter() .rev() .find(|l| l.starts_with("error:") && !l.contains("job(s) failed")) { - return err_line.trim_start_matches("error: ").to_string(); + err_line.trim_start_matches("error: ").to_string() + } else { + lines + .last() + .map(|l| l.to_string()) + .unwrap_or_else(|| "Download endete ohne vollständige AAXC-Datei".to_string()) + }; + human_download_error(&raw) +} + +fn human_download_error(raw: &str) -> String { + let mut s = raw + .trim_start_matches("download_aaxc failed for ") + .trim_start_matches("download_cover failed for ") + .trim_start_matches("AudibleCliException: ") + .to_string(); + if s.to_lowercase().contains("is not downloadable") { + s = "Dieser Titel liefert Audible nicht als Datei (nur Streaming).".to_string(); + } else if s.to_lowercase().contains("timeout") { + s = "Audible Zeitüberschreitung beim Download — bitte nochmal versuchen.".to_string(); } - if let Some(last) = lines.last() { - return last.to_string(); - } - "Download endete ohne vollständige AAXC-Datei".to_string() + s } /// Größe der größten AAXC/AXP-Datei im Job-Verzeichnis. @@ -632,16 +652,40 @@ mod tests { #[test] fn pick_download_error_waehlt_job_fehler() { let s = "File x.jpg downloaded\nChapter file saved\nerror: download_aaxc failed for Einhornprinz (B015HG6T6A): AudibleCliException: is not downloadable.\nThe download ended with the following result:\nerror: 1 job(s) failed. Use --ignore-errors to download the rest anyway"; - assert_eq!( - pick_download_error(s), - "download_aaxc failed for Einhornprinz (B015HG6T6A): AudibleCliException: is not downloadable." - ); + let s = pick_download_error(s); + assert!(s.contains("nicht als Datei"), "erwartet Klartext: {s}"); // Fallback: keine Job-Zeile, aber error:-Zeile assert_eq!(pick_download_error("error: 401 unauthorized\nerror: 1 job(s) failed"), "401 unauthorized"); // gar nichts da assert_eq!(pick_download_error(""), "Download endete ohne vollständige AAXC-Datei"); } + #[test] + fn download_error_klartext() { + let raw = "Der Einhornprinz: Sternenfohlen 2 (B015HG6T6A): AudibleCliException: Der Einhornprinz is not downloadable."; + let s = human_download_error(raw); + assert!(s.contains("nicht als Datei")); + } + + #[test] + fn local_books_findet_testbuch() { + // books_dir per env-Override — in Rust 2024 unsicher, deshalb unsafe-Block + let tmp = std::env::temp_dir().join(format!("hw-localtest-{}", std::process::id())); + unsafe { + std::env::set_var("HOERWERK_BOOKS_DIR", &tmp); + } + let b = tmp.join("B08L4WJMDM"); + fs::create_dir_all(&b).unwrap(); + fs::write(b.join("book.m4b"), &vec![0u8; 4096]).unwrap(); + let found = crate::audible::local_books(); + unsafe { + std::env::remove_var("HOERWERK_BOOKS_DIR"); + } + let hit = found.iter().any(|bk| bk.asin == "B08L4WJMDM" && bk.local); + assert!(hit, "lokales Buch muss gefunden werden: {:?}", found.iter().map(|bk| bk.asin.clone()).collect::>()); + let _ = fs::remove_dir_all(&tmp); + } + #[test] fn dl_item_serde_status() { let it = DlItem { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b5f803e..d557854 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -52,6 +52,14 @@ async fn get_library( .await .map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}"))? } + +/// Lokale Titel auch ohne Netz/Anmeldung — ffprobe-basiert. +#[tauri::command] +async fn get_local_books() -> Result, String> { + tauri::async_runtime::spawn_blocking(audible::local_books) + .await + .map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}")) +} #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() @@ -68,6 +76,7 @@ pub fn run() { start_login, start_decrypt, get_library, + get_local_books, download_list, download_enqueue, download_cancel, diff --git a/src/App.svelte b/src/App.svelte index ee2a112..88563e4 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -4,6 +4,7 @@ startLogin, startDecrypt, getLibrary, + getLocalBooks, downloadList, downloadEnqueue, downloadCancel, @@ -27,8 +28,10 @@ let query = $state('') let sortBy = $state('added') + let onlyLocal = $state(false) let downloads = $state>({}) let loadedOverride = $state>({}) + let removedLocals = $state>({}) const actives = $derived.by(() => { let n = 0 @@ -45,6 +48,7 @@ const filtered = $derived.by(() => { const q = query.trim().toLowerCase() const hits = books.filter((b) => { + if (onlyLocal && !isLocal(b)) return false if (!q) return true return ( b.title.toLowerCase().includes(q) || @@ -74,6 +78,7 @@ } function isLocal(b: Book): boolean { + if (removedLocals[b.asin]) return false return Boolean(b.local || loadedOverride[b.asin]) } @@ -140,17 +145,32 @@ error = '' try { books = await getLibrary() + // Lokale Titel einpflügen, die (noch) nicht im Online-Export sind + try { + const locals = await getLocalBooks() + const have = new Set(books.map((b) => b.asin)) + books = [...books, ...locals.filter((l) => !have.has(l.asin))] + } catch { + // Scan optional + } view = 'library' } catch (e) { const msg = String(e) if (msg.toLowerCase().includes('encrypted')) { // Auth-Datei verschlüsselt — Entschlüsselung im Terminal anbieten - error = 'Auth-Datei ist verschlüsselt. Bitte einmal entsprichern:' + error = 'Auth-Datei ist verschlüsselt. Bitte einmal entschließen:' view = 'login' } else { - error = msg - view = 'library' - books = [] + // Offline-Modus: lokale Titel trotzdem anzeigen + try { + books = await getLocalBooks() + view = 'library' + info = 'Audible nicht erreichbar — zeige nur lokale Titel.' + } catch { + error = msg + view = 'library' + books = [] + } } } finally { checking = false @@ -250,7 +270,7 @@ - {#if error === 'Auth-Datei ist verschlüsselt. Bitte einmal entsprichern:'} + {#if error === 'Auth-Datei ist verschlüsselt. Bitte einmal entschließen:'} @@ -281,6 +301,14 @@ + @@ -320,8 +348,11 @@
{b.title}
{b.authors}
- {#if isLocal(b)}lokal{/if} - {#if b.is_finished}fertig{/if} + {#if isLocal(b)} + lokal + {:else if b.is_finished} + fertig + {/if} {#if b.runtime_length_min > 0}{fmtRuntime(b.runtime_length_min)}{/if} {#if d && d.status === 'failed'}Fehlgeschlagen{/if}
@@ -334,7 +365,9 @@
{/if}
- {#if dlg === 'running' || dlg === 'queued' || dlg === 'decrypting'} + {#if isLocal(b)} + + {:else if dlg === 'running' || dlg === 'queued' || dlg === 'decrypting'} diff --git a/src/app.css b/src/app.css index 6dc63bf..399b448 100644 --- a/src/app.css +++ b/src/app.css @@ -173,6 +173,11 @@ button.ghost { background: transparent; } +button.activechip { + border-color: var(--ok); + color: var(--ok); +} + .info { color: #7fa9d4; } diff --git a/src/lib/audible.ts b/src/lib/audible.ts index 74b145e..82570e1 100644 --- a/src/lib/audible.ts +++ b/src/lib/audible.ts @@ -24,6 +24,7 @@ export const authStatus = () => invoke('auth_status') export const startLogin = () => invoke('start_login') export const startDecrypt = () => invoke('start_decrypt') export const getLibrary = () => invoke('get_library') +export const getLocalBooks = () => invoke('get_local_books') export interface DlItem { asin: string