M1-Politur nach Feedback: lokal statt fertig-Chip + Löschen für lokale Bücher, 'Nur lokale'-Filter, Offline-Scan über ffprobe (lokale Titel auch ohne Netz), Klartext-Fehler ('nicht als Datei', Timeout)

This commit is contained in:
2026-11-06 20:09:07 +01:00
parent 560361004a
commit 5b1749ec78
6 changed files with 196 additions and 31 deletions

View File

@ -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<Vec<Book>, 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<Book> {
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::<serde_json::Value>(&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::<f64>().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 {

View File

@ -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<PathBuf> {
None
}
/// Sucht die aufschlussreichste Zeile aus dem stderr-Fehlerprotokoll:
/// bevorzugt „error: <job> 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::<Vec<_>>());
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn dl_item_serde_status() {
let it = DlItem {

View File

@ -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<Vec<Book>, 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,