T-011: Login-Flow in der App (AudibleClient-Trait, Auth- Erkennung über ~/.audible, Terminal-Login, Minimale Bibliothek; spec-Abweichung: kein Kopieren nach ~/.config, app nutzt audible-cli-pfad)
This commit is contained in:
292
src-tauri/src/audible.rs
Normal file
292
src-tauri/src/audible.rs
Normal file
@ -0,0 +1,292 @@
|
||||
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<String>,
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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<AuthStatus, String>;
|
||||
/// Startet die interaktive Anmeldung (audible quickstart) im Terminal.
|
||||
/// true = Terminal gestartet, der Nutzer meldet sich dort an; dann
|
||||
/// `auth_status` erneut prüfen.
|
||||
fn start_login(&self) -> Result<bool, String>;
|
||||
fn library(&self) -> Result<Vec<Book>, String>;
|
||||
}
|
||||
|
||||
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.
|
||||
fn audible_binary(&self) -> Result<PathBuf, String> {
|
||||
if let Some(home) = home_dir() {
|
||||
let p = home.join(".local/bin/audible");
|
||||
if p.is_file() {
|
||||
return Ok(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 Ok(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("audible-cli nicht gefunden — Installation: pipx install audible-cli".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CliAudibleClient {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn home_dir() -> Option<PathBuf> {
|
||||
env::var("HOME").ok().map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn default_auth_dir() -> PathBuf {
|
||||
home_dir()
|
||||
.map(|h| h.join(".audible"))
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
}
|
||||
|
||||
impl AudibleClient for CliAudibleClient {
|
||||
fn auth_status(&self) -> Result<AuthStatus, String> {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
fn start_login(&self) -> Result<bool, String> {
|
||||
let bin = self.audible_binary()?;
|
||||
let Some((term, needs_e)) = find_terminal() else {
|
||||
return Err("kein unterstütztes Terminal gefunden — bitte in deiner Shell ausführen: audible quickstart".to_string());
|
||||
};
|
||||
// Argumentliste, keine Shell und kein zusammengesetzter String (spec).
|
||||
let mut cmd = Command::new(term);
|
||||
if needs_e {
|
||||
cmd.arg("-e");
|
||||
}
|
||||
cmd.arg(&bin).arg("quickstart");
|
||||
cmd.spawn()
|
||||
.map_err(|e| format!("Terminal konnte nicht gestartet werden: {e}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn library(&self) -> Result<Vec<Book>, String> {
|
||||
let bin = self.audible_binary()?;
|
||||
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);
|
||||
parse_library(&content)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandelt den Bibliotheks-Export in `Book`s (separat getestet).
|
||||
pub fn parse_library(content: &str) -> Result<Vec<Book>, String> {
|
||||
serde_json::from_str(content).map_err(|e| format!("Bibliothek-JSON nicht parsebar: {e}"))
|
||||
}
|
||||
|
||||
/// Taugt stderr von audible-cli: Warnungen und Passwort-Prompts raus,
|
||||
/// echte Fehlertexte bleiben.
|
||||
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)> {
|
||||
// (Programm, heißt „-e Programm Args“)
|
||||
const CANDIDATES: [(&str, bool); 5] = [
|
||||
("konsole", true),
|
||||
("kitty", true),
|
||||
("alacritty", true),
|
||||
("foot", false),
|
||||
("xterm", true),
|
||||
];
|
||||
for (name, needs_e) in CANDIDATES {
|
||||
if is_in_path(name) {
|
||||
return Some((name, needs_e));
|
||||
}
|
||||
}
|
||||
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"}]"#;
|
||||
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!(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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user