Altersangaben: Genre-Signal-Chip (Kinder/Jugend aus Audible-Genres) + manuelle Altersnote pro Buch (labels.json, Inline-Edit mit Stift-Button)

This commit is contained in:
2026-11-06 20:20:51 +01:00
parent 14b93e2fb1
commit 0b7e223ad5
7 changed files with 162 additions and 2 deletions

View File

@ -32,6 +32,8 @@ pub struct Book {
pub is_finished: bool, pub is_finished: bool,
#[serde(default)] #[serde(default)]
pub date_added: String, pub date_added: String,
#[serde(default)]
pub genres: String,
/// lokal vorhanden (book.m4b im Datenverzeichnis) — vom Backend gesetzt /// lokal vorhanden (book.m4b im Datenverzeichnis) — vom Backend gesetzt
#[serde(default, skip_deserializing)] #[serde(default, skip_deserializing)]
pub local: bool, pub local: bool,
@ -263,6 +265,7 @@ pub fn local_books() -> Vec<Book> {
percent_complete: 0.0, percent_complete: 0.0,
is_finished: false, is_finished: false,
date_added: String::new(), date_added: String::new(),
genres: String::new(),
local: true, local: true,
}); });
} }
@ -306,6 +309,54 @@ fn probe_m4b(m4b: &Path) -> (String, String, i64) {
(title, artist, minutes) (title, artist, minutes)
} }
// Manuelle Altersnotizen (bewertbar pro Buch, lokale JSON-Ablage)
#[derive(Debug, Clone, Serialize)]
pub struct Labels(pub std::collections::BTreeMap<String, String>);
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<String, String> = 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<String>) -> 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}")
)
}
// Manuelle Altersnotizen — lokale JSON-Ablage (siehe labels_path)
/// Taugt stderr von audible-cli: Warnungen und Passwort-Prompts raus, /// Taugt stderr von audible-cli: Warnungen und Passwort-Prompts raus,
/// echte Fehlertexte bleiben. /// echte Fehlertexte bleiben.
pub(crate) fn reduce_noise(s: &str) -> String { pub(crate) fn reduce_noise(s: &str) -> String {

View File

@ -730,6 +730,23 @@ mod tests {
let _ = fs::remove_dir_all(&root); let _ = fs::remove_dir_all(&root);
} }
#[test]
fn alter_note_roundtrip() {
let tmp = std::env::temp_dir().join(format!("hw-labels-{}", std::process::id()));
unsafe {
std::env::set_var("HOERWERK_BOOKS_DIR", &tmp);
}
crate::audible::set_alter_note("B08L4WJMDM", Some("ab 6".into())).unwrap();
let l = crate::audible::alter_notes();
assert_eq!(l.0.get("B08L4WJMDM").map(|s| s.as_str()), Some("ab 6"));
crate::audible::set_alter_note("B08L4WJMDM", None).unwrap();
assert!(crate::audible::alter_notes().0.get("B08L4WJMDM").is_none());
unsafe {
std::env::remove_var("HOERWERK_BOOKS_DIR");
}
let _ = fs::remove_dir_all(&tmp);
}
#[test] #[test]
fn dl_item_serde_status() { fn dl_item_serde_status() {
let it = DlItem { let it = DlItem {

View File

@ -68,6 +68,23 @@ async fn stream_only() -> Result<Vec<String>, String> {
.await .await
.map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}")) .map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}"))
} }
#[tauri::command]
async fn get_alter_notes() -> Result<audible::Labels, String> {
tauri::async_runtime::spawn_blocking(audible::alter_notes)
.await
.map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}"))
}
#[tauri::command]
async fn set_alter_note(
asin: String,
note: Option<String>,
) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || audible::set_alter_note(&asin, note))
.await
.map_err(|e| format!("Hintergrundthread fehlgeschlagen: {e}"))?
}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
@ -86,6 +103,8 @@ pub fn run() {
get_library, get_library,
get_local_books, get_local_books,
stream_only, stream_only,
get_alter_notes,
set_alter_note,
download_list, download_list,
download_enqueue, download_enqueue,
download_cancel, download_cancel,

View File

@ -6,6 +6,8 @@
getLibrary, getLibrary,
getLocalBooks, getLocalBooks,
getStreamOnly, getStreamOnly,
getAlterNotes,
setAlterNote,
downloadList, downloadList,
downloadEnqueue, downloadEnqueue,
downloadCancel, downloadCancel,
@ -35,6 +37,40 @@
let loadedOverride = $state<Record<string, boolean>>({}) let loadedOverride = $state<Record<string, boolean>>({})
let removedLocals = $state<Record<string, boolean>>({}) let removedLocals = $state<Record<string, boolean>>({})
let streamOnly = $state<Record<string, boolean>>({}) let streamOnly = $state<Record<string, boolean>>({})
let alterNotes = $state<Record<string, string>>({})
let editingAlter = $state<string | null>(null)
let alterDraft = $state('')
function ageTag(b: Book): 'Kinder' | 'Jugend' | null {
const g = (b.genres || '').toLowerCase()
if (g.includes('kinder')) return 'Kinder'
if (g.includes('jugend')) return 'Jugend'
return null
}
function alterNote(b: Book): string {
return alterNotes[b.asin] ?? ''
}
function startEditAlter(b: Book): void {
editingAlter = b.asin
alterDraft = alterNote(b)
}
async function saveAlter(b: Book): Promise<void> {
try {
await setAlterNote(b.asin, alterDraft.trim() || null)
alterNotes = { ...alterNotes, [b.asin]: alterDraft.trim() }
if (!alterDraft.trim()) {
const rest = { ...alterNotes }
delete rest[b.asin]
alterNotes = rest
}
editingAlter = null
} catch (e) {
error = String(e)
}
}
const actives = $derived.by(() => { const actives = $derived.by(() => {
let n = 0 let n = 0
@ -256,6 +292,9 @@
// periodische Abgleich macht den Backend-Stand zur Autorität. // periodische Abgleich macht den Backend-Stand zur Autorität.
const syncId = setInterval(syncDownloads, 3000) const syncId = setInterval(syncDownloads, 3000)
syncDownloads() syncDownloads()
getAlterNotes()
.then((all) => (alterNotes = all))
.catch(() => {})
return () => { return () => {
clearPoll() clearPoll()
clearInterval(syncId) clearInterval(syncId)
@ -381,6 +420,11 @@
{#if b.is_finished && !isLocal(b)} {#if b.is_finished && !isLocal(b)}
<span class="chip done" title="Buch abgehört"><Icon name="play" size={12} /> fertig</span> <span class="chip done" title="Buch abgehört"><Icon name="play" size={12} /> fertig</span>
{/if} {/if}
{#if alterNote(b)}
<span class="chip age" title="Manuelle Altersnote">{alterNote(b)}</span>
{:else if ageTag(b)}
<span class="chip" title="Audible-Genre (Hinweis, keine Altersfreigabe)">{ageTag(b)}</span>
{/if}
{#if b.runtime_length_min > 0}<span class="chip">{fmtRuntime(b.runtime_length_min)}</span>{/if} {#if b.runtime_length_min > 0}<span class="chip">{fmtRuntime(b.runtime_length_min)}</span>{/if}
{#if d && d.status === 'failed'}<span class="chip err" title={d.msg}>Fehlgeschlagen</span>{/if} {#if d && d.status === 'failed'}<span class="chip err" title={d.msg}>Fehlgeschlagen</span>{/if}
</div> </div>
@ -393,8 +437,20 @@
<div class="progress indeterminate slow"><div class="fill"></div></div> <div class="progress indeterminate slow"><div class="fill"></div></div>
{/if} {/if}
<div class="actions"> <div class="actions">
{#if isLocal(b)} {#if editingAlter === b.asin}
<button class="ghost" onclick={() => loeschen(b)}>Löschen</button> <input
class="input"
placeholder="z. B. ab 6"
bind:value={alterDraft}
onkeydown={(e) => e.key === 'Enter' && saveAlter(b)}
/>
<button class="primary" onclick={() => saveAlter(b)}>Speichern</button>
<button class="ghost" onclick={() => (editingAlter = null)}><Icon name="x" size={13} /></button>
{:else if isLocal(b)}
<button class="ghost" onclick={() => loeschen(b)}><Icon name="trash" size={14} /> Löschen</button>
<button class="ghost" title="Altersnote setzen" onclick={() => startEditAlter(b)}>
<Icon name="pencil" size={13} /> Alter
</button>
{:else if streamOnly[b.asin]} {:else if streamOnly[b.asin]}
<button <button
class="ghost" class="ghost"

View File

@ -275,6 +275,17 @@ button.activechip {
border-color: var(--accent); border-color: var(--accent);
} }
.chip.age {
color: var(--ok);
border-color: var(--ok);
}
.actions input.input {
width: 7rem;
font-size: 0.85rem;
padding: 0.25rem 0.5rem;
}
.progress { .progress {
height: 3px; height: 3px;
border-radius: 2px; border-radius: 2px;

View File

@ -8,6 +8,8 @@
trash: trash:
'<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="M6.5 7l1 14h9l1-14"/>', '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="M6.5 7l1 14h9l1-14"/>',
play: '<path d="M8 5v14l11-7z" fill="currentColor" stroke="none"/>', play: '<path d="M8 5v14l11-7z" fill="currentColor" stroke="none"/>',
pencil:
'<path d="M4 20h4L20 8l-4-4L4 16v4z"/><path d="M13.5 6.5l4 4"/>',
x: '<path d="M5 5l14 14"/><path d="M19 5 5 19"/>', x: '<path d="M5 5l14 14"/><path d="M19 5 5 19"/>',
} }

View File

@ -17,6 +17,7 @@ export interface Book {
percent_complete: number percent_complete: number
is_finished: boolean is_finished: boolean
date_added: string date_added: string
genres: string
local: boolean local: boolean
} }
@ -26,6 +27,9 @@ export const startDecrypt = () => invoke<boolean>('start_decrypt')
export const getLibrary = () => invoke<Book[]>('get_library') export const getLibrary = () => invoke<Book[]>('get_library')
export const getLocalBooks = () => invoke<Book[]>('get_local_books') export const getLocalBooks = () => invoke<Book[]>('get_local_books')
export const getStreamOnly = () => invoke<string[]>('stream_only') export const getStreamOnly = () => invoke<string[]>('stream_only')
export const getAlterNotes = () => invoke<Record<string, string>>('get_alter_notes')
export const setAlterNote = (asin: string, note: string | null) =>
invoke<void>('set_alter_note', { asin, note })
export interface DlItem { export interface DlItem {
asin: string asin: string