Files
hoerwerk/src/App.svelte

310 lines
9.9 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script lang="ts">
import {
authStatus,
startLogin,
startDecrypt,
getLibrary,
downloadList,
downloadEnqueue,
downloadCancel,
onDownloadUpdate,
type Book,
type DlItem,
} from './lib/audible'
type View = 'loading' | 'login' | 'library'
type SortKey = 'added' | 'title' | 'author' | 'runtime' | 'percent'
let view = $state<View>('loading')
let loadingMsg = $state<string>('Prüfe Anmeldung…')
let error = $state('')
let info = $state('')
let books = $state<Book[]>([])
let starting = $state(false)
let checking = $state(false)
let pollTimer = $state<ReturnType<typeof setInterval> | null>(null)
let query = $state('')
let sortBy = $state<SortKey>('added')
let downloads = $state<Record<string, DlItem>>({})
let localOverride = $state<Record<string, boolean>>({})
const filtered = $derived.by(() => {
const q = query.trim().toLowerCase()
const hits = books.filter((b) => {
if (!q) return true
return (
b.title.toLowerCase().includes(q) ||
b.authors.toLowerCase().includes(q) ||
b.narrators.toLowerCase().includes(q)
)
})
const cmp: Record<SortKey, (a: Book, b: Book) => number> = {
added: (a, b) => b.date_added.localeCompare(a.date_added),
title: (a, b) => a.title.localeCompare(b.title, 'de'),
author: (a, b) => a.authors.localeCompare(b.authors, 'de') || a.title.localeCompare(b.title, 'de'),
runtime: (a, b) => b.runtime_length_min - a.runtime_length_min,
percent: (a, b) => b.percent_complete - a.percent_complete,
}
return [...hits].sort(cmp[sortBy])
})
function fmtRuntime(min: number): string {
if (!min || min <= 0) return ''
const h = Math.floor(min / 60)
const m = min % 60
return m ? `${h} h ${m} min` : `${h} h`
}
function mb(bytes: number): string {
return bytes >= 1e6 ? `${(bytes / 1e6).toFixed(1)} MB` : `${Math.round(bytes / 1e3)} KB`
}
function isLocal(b: Book): boolean {
return Boolean(b.local || localOverride[b.asin])
}
function activeDl(b: Book): 'running' | 'queued' | undefined {
const d = downloads[b.asin]
if (!d) return undefined
if (d.status === 'running') return 'running'
if (d.status === 'queued') return 'queued'
return undefined
}
async function laden(b: Book): Promise<void> {
error = ''
info = ''
try {
const it = await downloadEnqueue(b.asin)
downloads = { ...downloads, [b.asin]: it }
info = `„${b.title}“ in der Download-Queue.`
} catch (e) {
error = String(e)
}
}
async function abbrechen(b: Book): Promise<void> {
error = ''
try {
const it = await downloadCancel(b.asin)
downloads = { ...downloads, [b.asin]: it }
} catch (e) {
error = String(e)
}
}
function hideBrokenCover(e: Event): void {
;(e.currentTarget as HTMLElement).style.display = 'none'
}
function clearPoll() {
if (pollTimer !== null) {
clearInterval(pollTimer)
pollTimer = null
}
}
async function loadLibrary(): Promise<void> {
checking = true
error = ''
try {
books = await getLibrary()
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:'
view = 'login'
} else {
error = msg
view = 'library'
books = []
}
} finally {
checking = false
loadingMsg = 'Prüfe Anmeldung…'
}
}
async function checkAuth(): Promise<void> {
checking = true
error = ''
try {
const s = await authStatus()
if (s.logged_in) {
clearPoll()
view = 'loading'
loadingMsg = 'Lade Bibliothek…'
await loadLibrary()
} else if (view !== 'login') {
view = 'login'
} else {
info = 'Noch nicht angemeldet — nach der Anmeldung klicken oder kurz warten.'
}
} catch (e) {
view = 'login'
error = String(e)
} finally {
checking = false
}
}
async function doLogin(): Promise<void> {
starting = true
error = ''
info = ''
try {
await startLogin()
info = 'Anmeldung läuft im Terminal. Danach hier „Jetzt prüfen“ oder kurz warten.'
clearPoll()
pollTimer = setInterval(checkAuth, 3000)
} catch (e) {
error = String(e)
} finally {
starting = false
}
}
// Beim Start: auth prüfen, Download-Events abonnieren, Queue-Stand laden.
$effect(() => {
checkAuth()
const unlisten = onDownloadUpdate((it) => {
downloads = { ...downloads, [it.asin]: it }
if (it.status === 'done') {
localOverride = { ...localOverride, [it.asin]: true }
info = `„Download fertig: ${it.asin}“`
}
})
downloadList().then((list) => {
const m: Record<string, DlItem> = {}
for (const it of list) m[it.asin] = it
downloads = m
})
return () => {
clearPoll()
unlisten.then((f) => f())
}
})
</script>
{#if view === 'loading'}
<main class="center">
<h1>Hörwerk</h1>
<p class="muted">{loadingMsg}</p>
{#if error}<p class="error">{error}</p>{/if}
</main>
{:else if view === 'login'}
<main class="center">
<h1>Hörwerk</h1>
<p class="muted">
Melden dich mit deinem Audible-Konto an. Der Anmeldedialog läuft über
<code>audible-cli</code> im Terminal (Benutzername, Passwort, ggf. 2FA).
Nur dein eigenes, gekauftes Konto — keine Daten gehen über die App hinaus.
</p>
<button class="primary" onclick={() => doLogin()} disabled={starting}>
{starting ? 'Starte…' : 'Anmeldung starten'}
</button>
<button class="ghost" onclick={() => checkAuth()} disabled={checking}>
{checking ? 'Prüfe…' : 'Jetzt prüfen'}
</button>
{#if error === 'Auth-Datei ist verschlüsselt. Bitte einmal entsprichern:'}
<button class="ghost" onclick={() => startDecrypt().catch((e) => (error = String(e)))}>
Entschlüsseln im Terminal…
</button>
{/if}
{#if info}<p class="info">{info}</p>{/if}
{#if error}<p class="error">{error}</p>{/if}
</main>
{:else if view === 'library'}
<main>
<header class="bar">
<h1>Hörwerk</h1>
<span class="muted small">{filtered.length} / {books.length} Titel</span>
<input
class="search"
type="search"
placeholder="Suche Titel, Autor, Sprecher…"
bind:value={query}
/>
<select bind:value={sortBy}>
<option value="added">Zuletzt hinzugefügt</option>
<option value="title">Titel A–Z</option>
<option value="author">Autor</option>
<option value="runtime">Laufzeit</option>
<option value="percent">Fortschritt</option>
</select>
<button class="ghost" onclick={() => checkAuth()} disabled={checking}>
{checking ? '…' : 'Auffrischen'}
</button>
</header>
{#if error}
<div class="statespace">
<p class="error">{error}</p>
<button class="ghost" onclick={() => checkAuth()} disabled={checking}>Nochmal versuchen</button>
</div>
{:else if filtered.length === 0}
<div class="statespace">
<p class="muted">{query ? 'Kein Treffer für „' + query + '“' : 'Bibliothek leer.'}</p>
</div>
{:else}
<div class="grid">
{#each filtered as b (b.asin)}
{@const d = downloads[b.asin]}
{@const dlg = activeDl(b)}
<article class="card">
<div class="cover">
<img
src={b.cover_url}
alt="Cover von {b.title}"
loading="lazy"
onerror={hideBrokenCover}
/>
{#if dlg}
<div class="overlay">
<span class="muted small">
{dlg === 'running' ? (d ? mb(d.bytes) : '') : 'in Warteschlange…'}
</span>
</div>
{/if}
</div>
<div class="meta">
<div class="t">{b.title}</div>
<div class="muted small">{b.authors}</div>
<div class="chips">
{#if isLocal(b)}<span class="chip ok" title="book.m4b liegt lokal vor">lokal</span>{/if}
{#if b.is_finished}<span class="chip done">fertig</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}
</div>
{#if b.percent_complete > 0 && !dlg}
<div class="progress"><div class="fill" style={`width:${b.percent_complete}%`}></div></div>
{/if}
{#if dlg === 'running'}
<div class="progress indeterminate"><div class="fill"></div></div>
{:else if dlg === 'queued'}
<div class="progress indeterminate slow"><div class="fill"></div></div>
{/if}
<div class="actions">
{#if dlg === 'running' || dlg === 'queued'}
<button class="ghost" onclick={() => abbrechen(b)}>
{dlg === 'queued' ? 'In der Queue — abbrechen?' : 'Abbrechen'}
</button>
{#if dlg === 'queued'}<span class="muted small">wartet…</span>{/if}
{:else if d && d.status === 'failed'}
<button class="ghost" onclick={() => laden(b)}>Nochmal laden</button>
<span class="muted small" title={d.msg}>{d.msg.slice(0, 60)}</span>
{:else if !isLocal(b)}
<button class="primary" onclick={() => laden(b)}>Laden</button>
{/if}
</div>
</div>
</article>
{/each}
</div>
{/if}
</main>
{/if}