From 2fe919f5af09783de19e202c46b857e6e7cca0b1 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:08:07 +0000 Subject: [PATCH 1/9] Record why a completed Audible backup could not match its title Migration 0093 stores the refused fold's reason code and time on the Audible title, in the same transaction as the refusal, and clears them when a later import or accepted match succeeds. The admin API returns them and the console explains each reason from the stored code instead of reading it from the job; older titles keep their wording. bridge#47 (record a refused fold on the title). --- CONVENTIONS.md | 7 ++- admin-ui/src/api/types.ts | 3 + .../src/features/audible/audible-model.ts | 2 +- .../src/features/audible/audible-topic.tsx | 5 ++ .../src/features/audible/audible.test.tsx | 32 ++++++++++ admin-ui/src/i18n/locales/de.json | 5 ++ admin-ui/src/i18n/locales/en.json | 5 ++ admin-ui/src/i18n/locales/es.json | 5 ++ admin-ui/src/i18n/locales/fr.json | 5 ++ admin-ui/src/i18n/locales/it.json | 5 ++ admin-ui/src/i18n/locales/pt.json | 5 ++ internal/api/audible_import_test.go | 30 ++++++++++ internal/bridge/audible.go | 3 +- internal/catalog/audible.go | 9 ++- internal/catalog/audible_import.go | 60 +++++++++++++------ internal/catalog/audible_import_test.go | 59 +++++++++++++++--- internal/store/migration_0093_test.go | 29 +++++++++ .../migrations/0093_audible_fold_refusal.sql | 13 ++++ 18 files changed, 251 insertions(+), 31 deletions(-) create mode 100644 internal/store/migration_0093_test.go create mode 100644 internal/store/migrations/0093_audible_fold_refusal.sql diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 3f7777db..761c9bdd 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4477,7 +4477,12 @@ every session. CLAUDE.md keeps a one-line index of these topics. the title's own (`importOwnBook`, else `ErrImportNotOwn`, logged): a book carrying the title's ASIN, or one holding only the files the backup placed (a single-file book is its file), so a file placed into a folder book already there (the scan makes it one book) never makes that book, nor another title's, the title's - match; and never the book the admin marked Not this book for the title. It sets the match + match; and never the book the admin marked Not this book for the title. On refusal, the same transaction + records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until + a later import or accepted match clears them. Settings > Audible explains an unusable report (`invalid_result`), + a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked + Not this book (`rejected_match`), even after the job is gone. Older rows keep their existing backup status. + A successful import sets the match (`match_how:"import"`), clears rejected and pending, only while `import_job_id` is still this job. A poll keeps an `import` match while its book is indexed and the poll names no other. A failure's code is the result's `code` (or a `code:` error prefix, or a park's code): `AudibleImportCodes`, shown on the title diff --git a/admin-ui/src/api/types.ts b/admin-ui/src/api/types.ts index ada2a2ce..750663c6 100644 --- a/admin-ui/src/api/types.ts +++ b/admin-ui/src/api/types.ts @@ -3411,6 +3411,9 @@ export interface AudibleTitle { import_job_id: number | null; /** Its backup (Phase 4b); null when none was asked for. */ import: AudibleImport | null; + /** Why the server could not match a completed backup to this title, and when it tried. */ + fold_refusal_reason?: string; + fold_refused_at?: string; /** A preorder still not available 14 days after its release date. */ needs_attention: boolean; /** Where a backup would go, as the Bridge planned it at its last check; null when matched or not planned. */ diff --git a/admin-ui/src/features/audible/audible-model.ts b/admin-ui/src/features/audible/audible-model.ts index 083b78d2..c5217ad4 100644 --- a/admin-ui/src/features/audible/audible-model.ts +++ b/admin-ui/src/features/audible/audible-model.ts @@ -217,7 +217,7 @@ export function importStatus( case 'needs_attention': return { key: 'audible.import.parked', tone: 'warn', code }; case 'done': - return { key: 'audible.import.done', tone: 'ok' }; + return x.fold_refusal_reason ? null : { key: 'audible.import.done', tone: 'ok' }; case 'failed': return { key: 'audible.import.failed', tone: 'bad', code }; case 'cancelled': diff --git a/admin-ui/src/features/audible/audible-topic.tsx b/admin-ui/src/features/audible/audible-topic.tsx index b199c2b7..4d54ebb8 100644 --- a/admin-ui/src/features/audible/audible-topic.tsx +++ b/admin-ui/src/features/audible/audible-topic.tsx @@ -268,6 +268,11 @@ function TitleRow({ {details.join(' · ')} + {x.fold_refusal_reason ? ( + + {t([`audible.fold.${x.fold_refusal_reason}`, 'audible.fold.other'])} + + ) : null} {backup?.code ? ( {t(backup.code)} ) : null} diff --git a/admin-ui/src/features/audible/audible.test.tsx b/admin-ui/src/features/audible/audible.test.tsx index 9fd15e4f..40198131 100644 --- a/admin-ui/src/features/audible/audible.test.tsx +++ b/admin-ui/src/features/audible/audible.test.tsx @@ -747,6 +747,38 @@ describe('settings > audible', () => { }); describe('audible backups', () => { + it("shows the title's stored reason even after the job is gone or another backup starts", async () => { + const done = { job_id: 4, state: 'done', code: '' } as const; + const reasons = ['invalid_result', 'not_indexed', 'not_own_book', 'rejected_match', 'new_code']; + const titles = reasons.map((reason, i) => + title({ + asin: `B00000000${i}`, + match: null, + fold_refusal_reason: reason, + fold_refused_at: '2026-11-01T09:00:00Z', + import: i === 0 ? null : i === 1 ? { ...done, state: 'queued' } : done, + }), + ); + titles.push(title({ asin: 'B000000009', match: null, import: done })); + mockFetch(routes(true, { 'GET /admin/audible/titles': { body: { titles, next: '' } } })); + renderApp('/server?topic=audible'); + const list = await screen.findByRole('list', { name: 'Audible titles' }); + const rows = within(list).getAllByRole('listitem'); + const messages = [ + "The server couldn't use the backup details to match this title to a book in its library.", + "The server couldn't find the backed-up book in the library index.", + "The server couldn't confirm that the book at the backup destination belongs to this title.", + 'The backup found the book marked “Not this book” for this title.', + "The server couldn't match the backup to this title.", + ]; + messages.forEach((message, i) => + expect(within(rows[i]).getByText(message)).toBeInTheDocument(), + ); + expect(within(rows[1]).getByText(en['audible.import.queued'])).toBeInTheDocument(); + expect(within(list).getAllByText('Backed up')).toHaveLength(1); + expect(within(rows[5]).getByText('Backed up')).toBeInTheDocument(); + }); + it('offers Not this book except on a backup of its own, and reads a rejected match as not here', () => { expect(canReject(title())).toBe(true); expect(canReject(title({ match: null }))).toBe(true); diff --git a/admin-ui/src/i18n/locales/de.json b/admin-ui/src/i18n/locales/de.json index ab0fd9f8..d163e999 100644 --- a/admin-ui/src/i18n/locales/de.json +++ b/admin-ui/src/i18n/locales/de.json @@ -3904,6 +3904,11 @@ "audible.import.running": "Wird gesichert", "audible.import.parked": "Sicherung braucht Aufmerksamkeit", "audible.import.done": "Gesichert", + "audible.fold.invalid_result": "Der Server konnte diesen Titel anhand der Sicherungsdaten keinem Buch in der Bibliothek zuordnen.", + "audible.fold.not_indexed": "Der Server konnte das gesicherte Buch im Bibliotheksindex nicht finden.", + "audible.fold.not_own_book": "Der Server konnte nicht bestätigen, dass das Buch am Sicherungsziel zu diesem Titel gehört.", + "audible.fold.rejected_match": "Die Sicherung hat das Buch gefunden, das für diesen Titel mit „Nicht dieses Buch“ markiert ist.", + "audible.fold.other": "Der Server konnte die Sicherung diesem Titel nicht zuordnen.", "audible.import.failed": "Sicherung fehlgeschlagen", "audible.import.cancelled": "Sicherung abgebrochen", "audible.code.not_released": "Audible lässt den Download noch nicht zu.", diff --git a/admin-ui/src/i18n/locales/en.json b/admin-ui/src/i18n/locales/en.json index 8163f601..2d616236 100644 --- a/admin-ui/src/i18n/locales/en.json +++ b/admin-ui/src/i18n/locales/en.json @@ -3904,6 +3904,11 @@ "audible.import.running": "Backing up", "audible.import.parked": "Backup needs attention", "audible.import.done": "Backed up", + "audible.fold.invalid_result": "The server couldn't use the backup details to match this title to a book in its library.", + "audible.fold.not_indexed": "The server couldn't find the backed-up book in the library index.", + "audible.fold.not_own_book": "The server couldn't confirm that the book at the backup destination belongs to this title.", + "audible.fold.rejected_match": "The backup found the book marked “Not this book” for this title.", + "audible.fold.other": "The server couldn't match the backup to this title.", "audible.import.failed": "Backup failed", "audible.import.cancelled": "Backup cancelled", "audible.code.not_released": "Audible doesn't let it be downloaded yet.", diff --git a/admin-ui/src/i18n/locales/es.json b/admin-ui/src/i18n/locales/es.json index 8aa5b8d3..ae678ace 100644 --- a/admin-ui/src/i18n/locales/es.json +++ b/admin-ui/src/i18n/locales/es.json @@ -4117,6 +4117,11 @@ "audible.import.running": "Copiando", "audible.import.parked": "La copia necesita atención", "audible.import.done": "Copiado", + "audible.fold.invalid_result": "El servidor no pudo usar los datos de la copia para asociar este título con un libro de la biblioteca.", + "audible.fold.not_indexed": "El servidor no encontró el libro copiado en el índice de la biblioteca.", + "audible.fold.not_own_book": "El servidor no pudo confirmar que el libro en el destino de la copia corresponde a este título.", + "audible.fold.rejected_match": "La copia encontró el libro marcado como «No es este libro» para este título.", + "audible.fold.other": "El servidor no pudo asociar la copia con este título.", "audible.import.failed": "La copia falló", "audible.import.cancelled": "Copia cancelada", "audible.code.not_released": "Audible aún no permite descargarlo.", diff --git a/admin-ui/src/i18n/locales/fr.json b/admin-ui/src/i18n/locales/fr.json index a082bb5b..61998df8 100644 --- a/admin-ui/src/i18n/locales/fr.json +++ b/admin-ui/src/i18n/locales/fr.json @@ -4117,6 +4117,11 @@ "audible.import.running": "Sauvegarde en cours", "audible.import.parked": "La sauvegarde demande votre attention", "audible.import.done": "Sauvegardé", + "audible.fold.invalid_result": "Le serveur n’a pas pu utiliser les informations de la sauvegarde pour associer ce titre à un livre de la bibliothèque.", + "audible.fold.not_indexed": "Le serveur n’a pas trouvé le livre sauvegardé dans l’index de la bibliothèque.", + "audible.fold.not_own_book": "Le serveur n’a pas pu confirmer que le livre à l’emplacement de la sauvegarde correspond à ce titre.", + "audible.fold.rejected_match": "La sauvegarde a trouvé le livre marqué « Pas ce livre » pour ce titre.", + "audible.fold.other": "Le serveur n’a pas pu associer la sauvegarde à ce titre.", "audible.import.failed": "Échec de la sauvegarde", "audible.import.cancelled": "Sauvegarde annulée", "audible.code.not_released": "Audible ne permet pas encore de le télécharger.", diff --git a/admin-ui/src/i18n/locales/it.json b/admin-ui/src/i18n/locales/it.json index 4d0072b9..202accbd 100644 --- a/admin-ui/src/i18n/locales/it.json +++ b/admin-ui/src/i18n/locales/it.json @@ -4117,6 +4117,11 @@ "audible.import.running": "Backup in corso", "audible.import.parked": "Il backup richiede attenzione", "audible.import.done": "Backup fatto", + "audible.fold.invalid_result": "Il server non è riuscito a usare i dati del backup per abbinare questo titolo a un libro della libreria.", + "audible.fold.not_indexed": "Il server non ha trovato il libro del backup nell’indice della libreria.", + "audible.fold.not_own_book": "Il server non ha potuto confermare che il libro nella destinazione del backup corrisponda a questo titolo.", + "audible.fold.rejected_match": "Il backup ha trovato il libro contrassegnato come «Non è questo libro» per questo titolo.", + "audible.fold.other": "Il server non è riuscito ad abbinare il backup a questo titolo.", "audible.import.failed": "Backup non riuscito", "audible.import.cancelled": "Backup annullato", "audible.code.not_released": "Audible non ne consente ancora il download.", diff --git a/admin-ui/src/i18n/locales/pt.json b/admin-ui/src/i18n/locales/pt.json index 2ff39ed9..7e7c9066 100644 --- a/admin-ui/src/i18n/locales/pt.json +++ b/admin-ui/src/i18n/locales/pt.json @@ -4117,6 +4117,11 @@ "audible.import.running": "A copiar", "audible.import.parked": "A cópia precisa de atenção", "audible.import.done": "Copiado", + "audible.fold.invalid_result": "O servidor não conseguiu usar os dados da cópia para associar este título a um livro da biblioteca.", + "audible.fold.not_indexed": "O servidor não encontrou o livro copiado no índice da biblioteca.", + "audible.fold.not_own_book": "O servidor não conseguiu confirmar que o livro no destino da cópia corresponde a este título.", + "audible.fold.rejected_match": "A cópia encontrou o livro marcado como «Não é este livro» para este título.", + "audible.fold.other": "O servidor não conseguiu associar a cópia a este título.", "audible.import.failed": "A cópia falhou", "audible.import.cancelled": "Cópia cancelada", "audible.code.not_released": "A Audible ainda não permite transferi-lo.", diff --git a/internal/api/audible_import_test.go b/internal/api/audible_import_test.go index 0c754584..ea427d2e 100644 --- a/internal/api/audible_import_test.go +++ b/internal/api/audible_import_test.go @@ -408,6 +408,36 @@ func (b *bridgeEnv) finish(t *testing.T, j bridge.Job, state, result, errText st } } +func TestAudibleAdminTitleFoldRefusal(t *testing.T) { + t.Parallel() + const asin = "B000000001" + b := backupEnv(t, title(asin, "One", "available", 0, "")) + if resp, out := b.do(t, "POST", backupPath(asin), b.adminTok, ""); resp.StatusCode != http.StatusAccepted { + t.Fatalf("queue backup: %d %s", resp.StatusCode, out) + } + job := b.claim(t, bridge.KindAudibleImport) + b.finish(t, job, "done", fmt.Sprintf(`{"library_id":%d,"path":"Missing"}`, b.lib.ID), "") + // The reason belongs to the title even after the completed job is gone. + if _, err := b.db.ExecContext(context.Background(), `DELETE FROM bridge_jobs WHERE id = ?`, job.ID); err != nil { + t.Fatal(err) + } + page := adminTitles(t, b, "account="+testAccount) + if len(page.Titles) != 1 { + t.Fatalf("titles = %+v", page) + } + x := page.Titles[0] + if x.Import != nil || x.Match != nil || x.FoldRefusalReason != "not_indexed" || x.FoldRefusedAt == nil { + t.Fatalf("title after the job was removed = %+v", x) + } + if code, out := b.putTitles(t, testAccount, "p2", true, title(asin, "One", "available", b.lib.ID, mistbornBook)); code != http.StatusOK { + t.Fatalf("poll: %d %s", code, out) + } + x = adminTitles(t, b, "account="+testAccount).Titles[0] + if x.Match == nil || x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { + t.Fatalf("title after a match = %+v", x) + } +} + // contestedTitle is title's unmatched title the Bridge stored with reason // contested (another title claimed the same book). func contestedTitle(asin, name string) string { diff --git a/internal/bridge/audible.go b/internal/bridge/audible.go index 33140084..8985179d 100644 --- a/internal/bridge/audible.go +++ b/internal/bridge/audible.go @@ -395,9 +395,10 @@ type AudibleImportResult struct { } // AudibleImportOf reads a job's params and, when it is done, its result. +// On a read error only fully decoded params can identify the affected title. func AudibleImportOf(j Job) (p AudibleImportParams, r AudibleImportResult, err error) { if err = json.Unmarshal(j.Params, &p); err != nil { - return p, r, err + return AudibleImportParams{}, r, err } if j.State == StateDone && len(j.Result) > 0 { err = json.Unmarshal(j.Result, &r) diff --git a/internal/catalog/audible.go b/internal/catalog/audible.go index 3958e293..e14c02ef 100644 --- a/internal/catalog/audible.go +++ b/internal/catalog/audible.go @@ -586,6 +586,10 @@ type AudibleTitle struct { // Import is the title's backup (Phase 4b): its job's state and code, or a // console request waiting for a preorder ("pending"); nil for none. Import *AudibleImport `json:"import"` + // FoldRefusalReason and FoldRefusedAt record why and when a completed + // backup could not be matched. An accepted match clears both. + FoldRefusalReason string `json:"fold_refusal_reason,omitempty"` + FoldRefusedAt *string `json:"fold_refused_at,omitempty"` // NeedsAttention: a preorder still not available AudiblePreorderWait after // its release date; the account is no longer checked hourly for it. NeedsAttention bool `json:"needs_attention"` @@ -1049,7 +1053,7 @@ func (c *Catalog) fillContests(ctx context.Context, titles []AudibleTitle) error const audibleTitleSelect = `SELECT t.account, t.asin, t.title, t.authors, t.series, t.release_date, t.runtime_s, t.state, t.reason, t.match_library_id, t.match_path, t.match_how, t.rejected, t.ignored, t.no_sync, t.dest_path, t.first_seen, t.updated_at, t.import_job_id, t.import_pending, j.state, j.error, j.result, j.progress, - t.planned, t.contest_library_id, t.contest_path, acct.library_id + t.planned, t.contest_library_id, t.contest_path, acct.library_id, t.fold_refusal_reason, t.fold_refused_at FROM audible_titles t LEFT JOIN bridge_jobs j ON j.id = t.import_job_id LEFT JOIN audible_accounts acct ON acct.account = t.account` @@ -1069,7 +1073,8 @@ func scanAudibleTitle(row rowScanner, now time.Time) (*AudibleTitle, error) { ) if err := row.Scan(&t.Account, &t.ASIN, &t.Title, &authors, &series, &t.ReleaseDate, &t.RuntimeS, &t.State, &t.Reason, &matchLib, &matchPath, &how, &t.Rejected, &t.Ignored, &t.NoSync, &t.DestPath, &t.FirstSeen, &t.UpdatedAt, - &jobID, &pending, &jobState, &jobErr, &jobRes, &jobProgrs, &planned, &contestLib, &contest, &acctLib); err != nil { + &jobID, &pending, &jobState, &jobErr, &jobRes, &jobProgrs, &planned, &contestLib, &contest, &acctLib, + &t.FoldRefusalReason, &t.FoldRefusedAt); err != nil { return nil, err } if json.Unmarshal([]byte(authors), &t.Authors) != nil || t.Authors == nil { diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index 7972a054..0440a420 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -646,24 +646,42 @@ var ( // own) and what the last poll said of it unmatched (its planned destination // and contested book). The result must name the job's own library and a book indexed there // (the Bridge rescans before it reports done), else ErrImportNotIndexed, and -// the title's own book (importOwnBook), else ErrImportNotOwn. A job that isn't +// the title's own book (importOwnBook), else ErrImportNotOwn. A refusal is +// committed on the title before its error is returned to the caller. A job that isn't // a done audible.import, or whose title has another backup since, changes // nothing. A user-state write. func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { if j.Kind != bridge.KindAudibleImport || j.State != bridge.StateDone || j.LibraryID == nil { return nil } - p, r, err := bridge.AudibleImportOf(j) - if err != nil { - return fmt.Errorf("read backup %d: %w", j.ID, err) - } - if r.LibraryID != *j.LibraryID || r.LibraryID != p.LibraryID || !bridgeBookPath(r.Path) { - return ErrImportNotIndexed + p, r, readErr := bridge.AudibleImportOf(j) + if readErr != nil { + readErr = fmt.Errorf("read backup %d: %w", j.ID, readErr) + if p.Account == "" { // Unreadable params cannot identify a title. + return readErr + } } - return c.db.WithUserStateTx(ctx, "FoldAudibleImport", func(tx *sql.Tx) error { - if err := importOwnBook(ctx, tx, p, r); err != nil { + var refusal error + err := c.db.WithUserStateTx(ctx, "FoldAudibleImport", func(tx *sql.Tx) error { + var reason string + switch { + case readErr != nil: + reason, refusal = "invalid_result", readErr + case r.LibraryID != *j.LibraryID || r.LibraryID != p.LibraryID || !bridgeBookPath(r.Path): + reason, refusal = "invalid_result", ErrImportNotIndexed + default: + reason, refusal = importOwnBook(ctx, tx, p, r) + } + if reason != "" { + _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET fold_refusal_reason = ?1, fold_refused_at = ?2, + updated_at = ?2, import_job_id = ?3 + WHERE account = ?4 AND asin = ?5 AND (import_job_id IS NULL OR import_job_id = ?3)`, + reason, c.ts(), j.ID, p.Account, p.ASIN) return err } + if refusal != nil { + return refusal // A database error rolls back the fold. + } _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET match_library_id = ?, match_path = ?, match_how = ?, rejected = 0, import_pending = 0, import_job_id = ?, planned = '', contest_library_id = NULL, contest_path = '', updated_at = ? @@ -671,6 +689,10 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { r.LibraryID, r.Path, AudibleMatchImport, j.ID, c.ts(), p.Account, p.ASIN, j.ID) return err }) + if err != nil { + return err + } + return refusal } // importOwnBook checks, through tx, that the book a done backup's result names @@ -680,8 +702,8 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { // backup placed (a book the backup made). A file the Bridge placed into a // folder book already there (the scan makes a folder one book) joins that // book, which stays its own title's. Never the book the admin marked "Not -// this book" for the title. -func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams, r bridge.AudibleImportResult) error { +// this book" for the title. Only a match refusal has a reason to store. +func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams, r bridge.AudibleImportResult) (string, error) { var ( id int64 folder bool @@ -696,13 +718,13 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams p.Account, p.ASIN, r.LibraryID, r.Path, KindBooks).Scan(&id, &folder, &asin, &rejected) switch { case errors.Is(err, sql.ErrNoRows): - return ErrImportNotIndexed + return "not_indexed", ErrImportNotIndexed case err != nil: - return err + return "", err case rejected: - return ErrImportNotOwn + return "rejected_match", ErrImportNotOwn case strings.EqualFold(asin, p.ASIN): - return nil + return "", nil } placed := make(map[string]bool, len(r.Files)) for _, f := range r.Files { @@ -712,16 +734,16 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams if folder { if files, err = queryRows(ctx, tx, func(rows *sql.Rows, path *string) error { return rows.Scan(path) }, `SELECT rel_path FROM book_files WHERE book_id = ?`, id); err != nil { - return err + return "", err } } if len(files) == 0 { - return ErrImportNotOwn + return "not_own_book", ErrImportNotOwn } for _, f := range files { if !placed[f] { - return ErrImportNotOwn + return "not_own_book", ErrImportNotOwn } } - return nil + return "", nil } diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index de251f59..62d3a18a 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -427,7 +427,7 @@ func TestAudiblePreorderClock(t *testing.T) { } // A done backup becomes its title's match (how import, Not this book cleared); -// a result naming another library or no indexed book changes nothing; the next +// a result naming another library or no indexed book records a refusal; the next // poll keeps the match while the book is indexed and the poll names no other. func TestFoldAudibleImport(t *testing.T) { t.Parallel() @@ -446,9 +446,37 @@ func TestFoldAudibleImport(t *testing.T) { Result: json.RawMessage(fmt.Sprintf(`{"library_id":%d,"path":%q,"files":[{"path":%q,"size":1}],"bytes":1,"enriched":false}`, libID, path, path+"/Book.m4b"))} } + checkRefusal := func(reason, at string) { + t.Helper() + x, err := f.c.AudibleTitle(f.ctx, "acct0001", "B000000001") + if err != nil { + t.Fatal(err) + } + if x.FoldRefusalReason != reason || x.FoldRefusedAt == nil || *x.FoldRefusedAt != at { + t.Fatalf("want refusal %q at %s, got %+v", reason, at, x) + } + } + bad := job(5, lib, "Author/Book") + bad.Result = json.RawMessage(`{"library_id":"bad"}`) + if err := f.c.FoldAudibleImport(f.ctx, bad); err == nil { + t.Fatal("accepted unreadable backup result") + } + invalidAt := f.c.ts() + checkRefusal("invalid_result", invalidAt) + f.tick(time.Second) + // A bad params field can leave the account and ASIN partially decoded. + // Such a job cannot identify a title on which to record a refusal. + bad.Params = json.RawMessage(`{"account":"acct0001","asin":"B000000001","library_id":"bad"}`) + if err := f.c.FoldAudibleImport(f.ctx, bad); err == nil { + t.Fatal("accepted unreadable backup params") + } + checkRefusal("invalid_result", invalidAt) if err := f.c.FoldAudibleImport(f.ctx, job(5, lib, "Author/Book")); !errors.Is(err, ErrImportNotIndexed) { t.Fatalf("no book there: %v", err) } + refusedAt := f.c.ts() + f.poll(t, "unmatched", avail("B000000001", "")) + checkRefusal("not_indexed", refusedAt) // The book the backup made: its one file is the placed one. if _, err := f.c.UpsertBook(f.ctx, &Book{LibraryID: lib, RelPath: "Author/Book", IsFolder: true, Title: "Book", Files: []BookFile{{RelPath: "Author/Book/Book.m4b"}}}); err != nil { @@ -457,6 +485,7 @@ func TestFoldAudibleImport(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, job(5, lib+1, "Author/Book")); !errors.Is(err, ErrImportNotIndexed) { t.Fatalf("another library: %v", err) } + checkRefusal("invalid_result", f.c.ts()) // Another backup's job leaves the title alone. if err := f.c.FoldAudibleImport(f.ctx, job(6, lib, "Author/Book")); err != nil { t.Fatal(err) @@ -464,11 +493,20 @@ func TestFoldAudibleImport(t *testing.T) { if tt, _ := f.c.AudibleTitle(f.ctx, "acct0001", "B000000001"); tt.Match != nil { t.Fatalf("another job matched it: %+v", tt.Match) } - if err := f.c.FoldAudibleImport(f.ctx, job(5, lib, "Author/Book")); err != nil { + if err := f.setImport("acct0001", "B000000001", 7); err != nil { + t.Fatal(err) + } + checkRefusal("invalid_result", f.c.ts()) + if err := f.c.FoldAudibleImport(f.ctx, job(7, lib, "Author/Book")); err != nil { + t.Fatal(err) + } + // A late refusal from the previous backup cannot overwrite this success. + if err := f.c.FoldAudibleImport(f.ctx, job(5, lib, "Missing")); !errors.Is(err, ErrImportNotIndexed) { t.Fatal(err) } tt, _ := f.c.AudibleTitle(f.ctx, "acct0001", "B000000001") - if tt.Match == nil || tt.Match.How != AudibleMatchImport || tt.Match.Path != "Author/Book" || tt.Rejected { + if tt.Match == nil || tt.Match.How != AudibleMatchImport || tt.Match.Path != "Author/Book" || tt.Rejected || + tt.FoldRefusalReason != "" || tt.FoldRefusedAt != nil { t.Fatalf("after the fold = %+v", tt) } // A poll that names no match keeps it; one naming the same book keeps "import". @@ -540,8 +578,8 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, done(1, "B000000001", "Author/Other", "Author/Other/One.m4b")); !errors.Is(err, ErrImportNotOwn) { t.Fatalf("joined another title's book: %v, want ErrImportNotOwn", err) } - if x := match("B000000001"); x.Match != nil { - t.Fatalf("One claimed the joined book: %+v", x.Match) + if x := match("B000000001"); x.Match != nil || x.FoldRefusalReason != "not_own_book" || x.FoldRefusedAt == nil { + t.Fatalf("One after joining another book: %+v", x) } if x := match("B000000002"); x.Match == nil || x.Match.Path != "Author/Other" || x.Match.How != "fuzzy" { t.Fatalf("Other's match = %+v", x.Match) @@ -561,8 +599,15 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, done(3, "B000000003", "Author/Wrong", "Author/Wrong/Wrong.m4b")); !errors.Is(err, ErrImportNotOwn) { t.Fatalf("the rejected book: %v, want ErrImportNotOwn", err) } - if x := match("B000000003"); !x.Rejected || x.Match == nil || x.Match.How != "fuzzy" { - t.Fatalf("Wrong after the fold = rejected %t, match %+v", x.Rejected, x.Match) + refusedAt := f.c.ts() + f.poll(t, "p2", wrong) + if x := match("B000000003"); !x.Rejected || x.Match == nil || x.Match.How != "fuzzy" || + x.FoldRefusalReason != "rejected_match" || x.FoldRefusedAt == nil || *x.FoldRefusedAt != refusedAt { + t.Fatalf("poll reporting the rejected match: %+v", x) + } + if x, err := f.c.PatchAudibleTitle(f.ctx, "acct0001", wrong.ASIN, AudibleTitlePatch{Rejected: new(false)}); err != nil || + x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { + t.Fatalf("accepting the match: %+v, %v", x, err) } // A single-file book made by the backup. if err := f.c.FoldAudibleImport(f.ctx, done(4, "B000000004", "Solo.m4b", "Solo.m4b")); err != nil { diff --git a/internal/store/migration_0093_test.go b/internal/store/migration_0093_test.go new file mode 100644 index 00000000..4cc0d98a --- /dev/null +++ b/internal/store/migration_0093_test.go @@ -0,0 +1,29 @@ +package store + +import ( + "context" + "testing" +) + +func TestMigration0093KeepsExistingAudibleTitle(t *testing.T) { + t.Parallel() + dsn, exec, closeRaw := openBefore(t, "0093") + exec(`INSERT INTO users(id, username, password_hash, role, created_at, updated_at) VALUES(1, 'u', 'x', 'admin', 't', 't')`) + exec(`INSERT INTO audible_accounts(account, marketplace, user_id, created_at, updated_at) VALUES('acct0001', 'us', 1, 't', 't')`) + exec(`INSERT INTO audible_titles(account, asin, state, reason, import_job_id, first_seen, updated_at) + VALUES('acct0001', 'B000000001', 'available', 'contested', 42, 'f', 'u')`) + closeRaw() + ctx := context.Background() + db, err := Open(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + var oldTitle bool + err = db.QueryRowContext(ctx, `SELECT reason = 'contested' AND import_job_id = 42 AND updated_at = 'u' + AND fold_refusal_reason = '' AND fold_refused_at IS NULL + FROM audible_titles WHERE account = 'acct0001' AND asin = 'B000000001'`).Scan(&oldTitle) + if err != nil || !oldTitle { + t.Fatalf("legacy title after migration: %t, %v", oldTitle, err) + } +} diff --git a/internal/store/migrations/0093_audible_fold_refusal.sql b/internal/store/migrations/0093_audible_fold_refusal.sql new file mode 100644 index 00000000..b84b871a --- /dev/null +++ b/internal/store/migrations/0093_audible_fold_refusal.sql @@ -0,0 +1,13 @@ +-- A completed backup can place files without matching its Audible title. +ALTER TABLE audible_titles ADD COLUMN fold_refusal_reason TEXT NOT NULL DEFAULT ''; +ALTER TABLE audible_titles ADD COLUMN fold_refused_at TEXT; + +-- A successful import, a poll's accepted match, or undoing "Not this book" +-- resolves the refusal in the same write that accepts the match. +CREATE TRIGGER audible_title_match_clears_refusal +AFTER UPDATE OF match_how, rejected ON audible_titles +WHEN NEW.fold_refused_at IS NOT NULL AND NEW.match_path IS NOT NULL AND NEW.rejected = 0 +BEGIN + UPDATE audible_titles SET fold_refusal_reason = '', fold_refused_at = NULL + WHERE account = NEW.account AND asin = NEW.asin; +END; From 705b62bcf42e6c64312b0bf22408f8fbf3365112 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:23:00 +0000 Subject: [PATCH 2/9] Carry a backup's fold refusal as a typed error with named codes importOwnBook returned a reason string beside a sentinel error, and the four stored codes were bare literals in the code and tests, so a typo compiled and showed the console's generic text. A foldRefusal now carries both (errors.Is still matches ErrImport*), the codes are AudibleFold* constants, and the fold decodes params and result itself so bridge.AudibleImportOf keeps its old contract. The clearing trigger also watches match_library_id and match_path, as audible_title_match_update does. Part of KodeStar/audiosilo-bridge#47. --- CONVENTIONS.md | 2 +- internal/api/audible_import_test.go | 2 +- internal/bridge/audible.go | 3 +- internal/catalog/audible_import.go | 94 ++++++++++++------- internal/catalog/audible_import_test.go | 20 ++-- internal/store/migration_0093_test.go | 11 +-- .../migrations/0093_audible_fold_refusal.sql | 2 +- 7 files changed, 77 insertions(+), 57 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 761c9bdd..b48d0216 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4481,7 +4481,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until a later import or accepted match clears them. Settings > Audible explains an unusable report (`invalid_result`), a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked - Not this book (`rejected_match`), even after the job is gone. Older rows keep their existing backup status. + Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone. Older rows keep their existing backup status. A successful import sets the match (`match_how:"import"`), clears rejected and pending, only while `import_job_id` is still this job. A poll keeps an `import` match while its book is indexed and the poll names no other. A failure's code is the diff --git a/internal/api/audible_import_test.go b/internal/api/audible_import_test.go index ea427d2e..a831bf6d 100644 --- a/internal/api/audible_import_test.go +++ b/internal/api/audible_import_test.go @@ -426,7 +426,7 @@ func TestAudibleAdminTitleFoldRefusal(t *testing.T) { t.Fatalf("titles = %+v", page) } x := page.Titles[0] - if x.Import != nil || x.Match != nil || x.FoldRefusalReason != "not_indexed" || x.FoldRefusedAt == nil { + if x.Import != nil || x.Match != nil || x.FoldRefusalReason != catalog.AudibleFoldNotIndexed || x.FoldRefusedAt == nil { t.Fatalf("title after the job was removed = %+v", x) } if code, out := b.putTitles(t, testAccount, "p2", true, title(asin, "One", "available", b.lib.ID, mistbornBook)); code != http.StatusOK { diff --git a/internal/bridge/audible.go b/internal/bridge/audible.go index 8985179d..33140084 100644 --- a/internal/bridge/audible.go +++ b/internal/bridge/audible.go @@ -395,10 +395,9 @@ type AudibleImportResult struct { } // AudibleImportOf reads a job's params and, when it is done, its result. -// On a read error only fully decoded params can identify the affected title. func AudibleImportOf(j Job) (p AudibleImportParams, r AudibleImportResult, err error) { if err = json.Unmarshal(j.Params, &p); err != nil { - return AudibleImportParams{}, r, err + return p, r, err } if j.State == StateDone && len(j.Result) > 0 { err = json.Unmarshal(j.Result, &r) diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index 0440a420..f3309b7c 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -641,47 +641,73 @@ var ( ErrImportNotOwn = errors.New("the backup's book is not the title's own") ) +// The reasons a done backup could not become its title's match, stored on the +// title (fold_refusal_reason, 0093) and worded by the console. +const ( + // AudibleFoldInvalidResult: the result is unreadable, names another + // library or no usable book path. + AudibleFoldInvalidResult = "invalid_result" + // AudibleFoldNotIndexed: no book is indexed at the result's path. + AudibleFoldNotIndexed = "not_indexed" + // AudibleFoldNotOwnBook: the book there isn't the title's own. + AudibleFoldNotOwnBook = "not_own_book" + // AudibleFoldRejectedMatch: the book there is the one marked Not this book. + AudibleFoldRejectedMatch = "rejected_match" +) + +// foldRefusal is a done backup the fold refused: the reason it stores on the +// title, and the error (ErrImport*, or the result's read error) it returns. +type foldRefusal struct { + reason string + err error +} + +func (e *foldRefusal) Error() string { return e.err.Error() } +func (e *foldRefusal) Unwrap() error { return e.err } + // FoldAudibleImport takes a done backup's place as its title's match (how // "import"), and clears its "Not this book" (the match is now this title's // own) and what the last poll said of it unmatched (its planned destination // and contested book). The result must name the job's own library and a book indexed there // (the Bridge rescans before it reports done), else ErrImportNotIndexed, and // the title's own book (importOwnBook), else ErrImportNotOwn. A refusal is -// committed on the title before its error is returned to the caller. A job that isn't -// a done audible.import, or whose title has another backup since, changes -// nothing. A user-state write. +// recorded on the title (fold_refusal_reason, fold_refused_at) in the same +// transaction, then returned. Unreadable params name no title and change +// nothing. A job that isn't a done audible.import, or whose title has another +// backup since, changes nothing. A user-state write. func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { if j.Kind != bridge.KindAudibleImport || j.State != bridge.StateDone || j.LibraryID == nil { return nil } - p, r, readErr := bridge.AudibleImportOf(j) - if readErr != nil { - readErr = fmt.Errorf("read backup %d: %w", j.ID, readErr) - if p.Account == "" { // Unreadable params cannot identify a title. - return readErr + var ( + p bridge.AudibleImportParams + r bridge.AudibleImportResult + refused *foldRefusal + ) + if err := json.Unmarshal(j.Params, &p); err != nil { + return fmt.Errorf("read backup %d: %w", j.ID, err) + } + if len(j.Result) > 0 { + if err := json.Unmarshal(j.Result, &r); err != nil { + refused = &foldRefusal{AudibleFoldInvalidResult, fmt.Errorf("read backup %d: %w", j.ID, err)} } } - var refusal error + if refused == nil && (r.LibraryID != *j.LibraryID || r.LibraryID != p.LibraryID || !bridgeBookPath(r.Path)) { + refused = &foldRefusal{AudibleFoldInvalidResult, ErrImportNotIndexed} + } err := c.db.WithUserStateTx(ctx, "FoldAudibleImport", func(tx *sql.Tx) error { - var reason string - switch { - case readErr != nil: - reason, refusal = "invalid_result", readErr - case r.LibraryID != *j.LibraryID || r.LibraryID != p.LibraryID || !bridgeBookPath(r.Path): - reason, refusal = "invalid_result", ErrImportNotIndexed - default: - reason, refusal = importOwnBook(ctx, tx, p, r) + if refused == nil { + if err := importOwnBook(ctx, tx, p, r); !errors.As(err, &refused) && err != nil { + return err + } } - if reason != "" { + if refused != nil { _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET fold_refusal_reason = ?1, fold_refused_at = ?2, updated_at = ?2, import_job_id = ?3 WHERE account = ?4 AND asin = ?5 AND (import_job_id IS NULL OR import_job_id = ?3)`, - reason, c.ts(), j.ID, p.Account, p.ASIN) + refused.reason, c.ts(), j.ID, p.Account, p.ASIN) return err } - if refusal != nil { - return refusal // A database error rolls back the fold. - } _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET match_library_id = ?, match_path = ?, match_how = ?, rejected = 0, import_pending = 0, import_job_id = ?, planned = '', contest_library_id = NULL, contest_path = '', updated_at = ? @@ -689,10 +715,10 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { r.LibraryID, r.Path, AudibleMatchImport, j.ID, c.ts(), p.Account, p.ASIN, j.ID) return err }) - if err != nil { + if err != nil || refused == nil { return err } - return refusal + return refused } // importOwnBook checks, through tx, that the book a done backup's result names @@ -702,8 +728,8 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { // backup placed (a book the backup made). A file the Bridge placed into a // folder book already there (the scan makes a folder one book) joins that // book, which stays its own title's. Never the book the admin marked "Not -// this book" for the title. Only a match refusal has a reason to store. -func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams, r bridge.AudibleImportResult) (string, error) { +// this book" for the title. A refusal is a *foldRefusal. +func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams, r bridge.AudibleImportResult) error { var ( id int64 folder bool @@ -718,13 +744,13 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams p.Account, p.ASIN, r.LibraryID, r.Path, KindBooks).Scan(&id, &folder, &asin, &rejected) switch { case errors.Is(err, sql.ErrNoRows): - return "not_indexed", ErrImportNotIndexed + return &foldRefusal{AudibleFoldNotIndexed, ErrImportNotIndexed} case err != nil: - return "", err + return err case rejected: - return "rejected_match", ErrImportNotOwn + return &foldRefusal{AudibleFoldRejectedMatch, ErrImportNotOwn} case strings.EqualFold(asin, p.ASIN): - return "", nil + return nil } placed := make(map[string]bool, len(r.Files)) for _, f := range r.Files { @@ -734,16 +760,16 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams if folder { if files, err = queryRows(ctx, tx, func(rows *sql.Rows, path *string) error { return rows.Scan(path) }, `SELECT rel_path FROM book_files WHERE book_id = ?`, id); err != nil { - return "", err + return err } } if len(files) == 0 { - return "not_own_book", ErrImportNotOwn + return &foldRefusal{AudibleFoldNotOwnBook, ErrImportNotOwn} } for _, f := range files { if !placed[f] { - return "not_own_book", ErrImportNotOwn + return &foldRefusal{AudibleFoldNotOwnBook, ErrImportNotOwn} } } - return "", nil + return nil } diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 62d3a18a..064dcd08 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -448,11 +448,7 @@ func TestFoldAudibleImport(t *testing.T) { } checkRefusal := func(reason, at string) { t.Helper() - x, err := f.c.AudibleTitle(f.ctx, "acct0001", "B000000001") - if err != nil { - t.Fatal(err) - } - if x.FoldRefusalReason != reason || x.FoldRefusedAt == nil || *x.FoldRefusedAt != at { + if x := f.title(t, "B000000001"); x.FoldRefusalReason != reason || x.FoldRefusedAt == nil || *x.FoldRefusedAt != at { t.Fatalf("want refusal %q at %s, got %+v", reason, at, x) } } @@ -462,7 +458,7 @@ func TestFoldAudibleImport(t *testing.T) { t.Fatal("accepted unreadable backup result") } invalidAt := f.c.ts() - checkRefusal("invalid_result", invalidAt) + checkRefusal(AudibleFoldInvalidResult, invalidAt) f.tick(time.Second) // A bad params field can leave the account and ASIN partially decoded. // Such a job cannot identify a title on which to record a refusal. @@ -470,13 +466,13 @@ func TestFoldAudibleImport(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, bad); err == nil { t.Fatal("accepted unreadable backup params") } - checkRefusal("invalid_result", invalidAt) + checkRefusal(AudibleFoldInvalidResult, invalidAt) if err := f.c.FoldAudibleImport(f.ctx, job(5, lib, "Author/Book")); !errors.Is(err, ErrImportNotIndexed) { t.Fatalf("no book there: %v", err) } refusedAt := f.c.ts() f.poll(t, "unmatched", avail("B000000001", "")) - checkRefusal("not_indexed", refusedAt) + checkRefusal(AudibleFoldNotIndexed, refusedAt) // The book the backup made: its one file is the placed one. if _, err := f.c.UpsertBook(f.ctx, &Book{LibraryID: lib, RelPath: "Author/Book", IsFolder: true, Title: "Book", Files: []BookFile{{RelPath: "Author/Book/Book.m4b"}}}); err != nil { @@ -485,7 +481,7 @@ func TestFoldAudibleImport(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, job(5, lib+1, "Author/Book")); !errors.Is(err, ErrImportNotIndexed) { t.Fatalf("another library: %v", err) } - checkRefusal("invalid_result", f.c.ts()) + checkRefusal(AudibleFoldInvalidResult, f.c.ts()) // Another backup's job leaves the title alone. if err := f.c.FoldAudibleImport(f.ctx, job(6, lib, "Author/Book")); err != nil { t.Fatal(err) @@ -496,7 +492,7 @@ func TestFoldAudibleImport(t *testing.T) { if err := f.setImport("acct0001", "B000000001", 7); err != nil { t.Fatal(err) } - checkRefusal("invalid_result", f.c.ts()) + checkRefusal(AudibleFoldInvalidResult, f.c.ts()) if err := f.c.FoldAudibleImport(f.ctx, job(7, lib, "Author/Book")); err != nil { t.Fatal(err) } @@ -578,7 +574,7 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { if err := f.c.FoldAudibleImport(f.ctx, done(1, "B000000001", "Author/Other", "Author/Other/One.m4b")); !errors.Is(err, ErrImportNotOwn) { t.Fatalf("joined another title's book: %v, want ErrImportNotOwn", err) } - if x := match("B000000001"); x.Match != nil || x.FoldRefusalReason != "not_own_book" || x.FoldRefusedAt == nil { + if x := match("B000000001"); x.Match != nil || x.FoldRefusalReason != AudibleFoldNotOwnBook || x.FoldRefusedAt == nil { t.Fatalf("One after joining another book: %+v", x) } if x := match("B000000002"); x.Match == nil || x.Match.Path != "Author/Other" || x.Match.How != "fuzzy" { @@ -602,7 +598,7 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { refusedAt := f.c.ts() f.poll(t, "p2", wrong) if x := match("B000000003"); !x.Rejected || x.Match == nil || x.Match.How != "fuzzy" || - x.FoldRefusalReason != "rejected_match" || x.FoldRefusedAt == nil || *x.FoldRefusedAt != refusedAt { + x.FoldRefusalReason != AudibleFoldRejectedMatch || x.FoldRefusedAt == nil || *x.FoldRefusedAt != refusedAt { t.Fatalf("poll reporting the rejected match: %+v", x) } if x, err := f.c.PatchAudibleTitle(f.ctx, "acct0001", wrong.ASIN, AudibleTitlePatch{Rejected: new(false)}); err != nil || diff --git a/internal/store/migration_0093_test.go b/internal/store/migration_0093_test.go index 4cc0d98a..38a30d8d 100644 --- a/internal/store/migration_0093_test.go +++ b/internal/store/migration_0093_test.go @@ -2,6 +2,7 @@ package store import ( "context" + "slices" "testing" ) @@ -19,11 +20,9 @@ func TestMigration0093KeepsExistingAudibleTitle(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { db.Close() }) - var oldTitle bool - err = db.QueryRowContext(ctx, `SELECT reason = 'contested' AND import_job_id = 42 AND updated_at = 'u' - AND fold_refusal_reason = '' AND fold_refused_at IS NULL - FROM audible_titles WHERE account = 'acct0001' AND asin = 'B000000001'`).Scan(&oldTitle) - if err != nil || !oldTitle { - t.Fatalf("legacy title after migration: %t, %v", oldTitle, err) + got := lines(t, db, `SELECT reason || ' ' || import_job_id || ' ' || updated_at || ' [' || fold_refusal_reason || '] ' || + COALESCE(fold_refused_at, 'null') FROM audible_titles WHERE account = 'acct0001' AND asin = 'B000000001'`) + if want := []string{"contested 42 u [] null"}; !slices.Equal(got, want) { + t.Fatalf("legacy title after migration = %q, want %q", got, want) } } diff --git a/internal/store/migrations/0093_audible_fold_refusal.sql b/internal/store/migrations/0093_audible_fold_refusal.sql index b84b871a..4fcc3f15 100644 --- a/internal/store/migrations/0093_audible_fold_refusal.sql +++ b/internal/store/migrations/0093_audible_fold_refusal.sql @@ -5,7 +5,7 @@ ALTER TABLE audible_titles ADD COLUMN fold_refused_at TEXT; -- A successful import, a poll's accepted match, or undoing "Not this book" -- resolves the refusal in the same write that accepts the match. CREATE TRIGGER audible_title_match_clears_refusal -AFTER UPDATE OF match_how, rejected ON audible_titles +AFTER UPDATE OF match_library_id, match_path, match_how, rejected ON audible_titles WHEN NEW.fold_refused_at IS NOT NULL AND NEW.match_path IS NOT NULL AND NEW.rejected = 0 BEGIN UPDATE audible_titles SET fold_refusal_reason = '', fold_refused_at = NULL From 0a652a9e8c345111e905e0fca31821abb8ffee1d Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:23:00 +0000 Subject: [PATCH 3/9] Word a stored backup refusal through FOLD_REASONS and a FoldNote The row looked the reason up inline with an i18next fallback array, so no list of the codes existed for a test to check. foldReasonKey maps the four codes (a newer one reads as other) and a test asserts each has English words, as the podcast codes do. Part of KodeStar/audiosilo-bridge#47. --- .../src/features/audible/audible-model.ts | 20 +++++++++++++++++++ .../src/features/audible/audible-topic.tsx | 19 +++++++++++++----- .../src/features/audible/audible.test.tsx | 10 ++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/admin-ui/src/features/audible/audible-model.ts b/admin-ui/src/features/audible/audible-model.ts index c5217ad4..4ba302bc 100644 --- a/admin-ui/src/features/audible/audible-model.ts +++ b/admin-ui/src/features/audible/audible-model.ts @@ -337,6 +337,26 @@ export function reasonKey(reason: string): string | null { return /^[a-z][a-z0-9_]*$/.test(reason) ? 'audible.reason.other' : null; } +/** + * The reasons the server stores on a title whose completed backup it could not + * match (`fold_refusal_reason`), each worded as `audible.fold.`. + */ +export const FOLD_REASONS = [ + 'invalid_result', + 'not_indexed', + 'not_own_book', + 'rejected_match', +] as const; + +/** The i18n key a title's stored backup refusal reads as, null for none; a newer code reads as `other`. */ +export function foldReasonKey(x: Pick): string | null { + const reason = x.fold_refusal_reason; + if (!reason) return null; + return (FOLD_REASONS as readonly string[]).includes(reason) + ? `audible.fold.${reason}` + : 'audible.fold.other'; +} + /** * The destination field's placeholder: where the Bridge planned the backup at * its last check, else an example. Never the field's value: a saved value diff --git a/admin-ui/src/features/audible/audible-topic.tsx b/admin-ui/src/features/audible/audible-topic.tsx index 4d54ebb8..8f26ca1a 100644 --- a/admin-ui/src/features/audible/audible-topic.tsx +++ b/admin-ui/src/features/audible/audible-topic.tsx @@ -16,6 +16,7 @@ import { CardEmpty } from '@/features/settings/card-empty'; import { accountName, chosenAccount, + foldReasonKey, importStatus, lookList, onServer, @@ -268,11 +269,7 @@ function TitleRow({ {details.join(' · ')} - {x.fold_refusal_reason ? ( - - {t([`audible.fold.${x.fold_refusal_reason}`, 'audible.fold.other'])} - - ) : null} + {backup?.code ? ( {t(backup.code)} ) : null} @@ -372,6 +369,18 @@ function PlannedNote({ title: x, template }: { title: AudibleTitle; template?: s * for and the account's other titles on it (or says so plainly without them), * an unknown code reads as a sentence, and Audible's own words stay. */ +/** Why the server could not match the title's completed backup, when it recorded why. */ +function FoldNote({ title: x }: { title: AudibleTitle }) { + const { t } = useTranslation(); + const key = foldReasonKey(x); + if (!key) return null; + return ( + + {t(key)} + + ); +} + function ReasonNote({ title: x }: { title: AudibleTitle }) { const { t, i18n } = useTranslation(); if (!x.reason) return null; diff --git a/admin-ui/src/features/audible/audible.test.tsx b/admin-ui/src/features/audible/audible.test.tsx index 40198131..2730fc0c 100644 --- a/admin-ui/src/features/audible/audible.test.tsx +++ b/admin-ui/src/features/audible/audible.test.tsx @@ -24,6 +24,8 @@ import { canSync, chosenAccount, cleanDest, + FOLD_REASONS, + foldReasonKey, importStatus, lookList, matchedParam, @@ -779,6 +781,14 @@ describe('audible backups', () => { expect(within(rows[5]).getByText('Backed up')).toBeInTheDocument(); }); + it('words every stored backup refusal, a newer one plainly', () => { + const dict = en as Record; + const keys = FOLD_REASONS.map((r) => foldReasonKey({ fold_refusal_reason: r })); + expect(keys.filter((k) => !k || !dict[k])).toEqual([]); + expect(foldReasonKey({ fold_refusal_reason: 'new_code' })).toBe('audible.fold.other'); + expect(foldReasonKey({})).toBeNull(); + }); + it('offers Not this book except on a backup of its own, and reads a rejected match as not here', () => { expect(canReject(title())).toBe(true); expect(canReject(title({ match: null }))).toBe(true); From 6f26c133ad3d06b02cbe42fac5eb19b60baad6e5 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:41:41 +0000 Subject: [PATCH 4/9] Keep a backup refusal when a write leaves the title's match as it was The clearing trigger fired whenever a write named the match columns, and the poll upsert names them on every poll, so a refusal recorded on a title a poll had already matched (a backup that joined that book) was wiped by the next poll repeating the same match, or by a no-op undo of Not this book. The trigger now clears only when the match changes or rejected goes from 1 to 0, and a successful import clears the refusal in its own UPDATE, since it may land on the path already matched. Part of KodeStar/audiosilo-bridge#47. --- CONVENTIONS.md | 4 +- internal/catalog/audible_import.go | 6 +-- internal/catalog/audible_import_test.go | 46 +++++++++++++++++++ .../migrations/0093_audible_fold_refusal.sql | 9 ++-- 4 files changed, 58 insertions(+), 7 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index b48d0216..02daaedf 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4479,7 +4479,9 @@ every session. CLAUDE.md keeps a one-line index of these topics. book already there (the scan makes it one book) never makes that book, nor another title's, the title's match; and never the book the admin marked Not this book for the title. On refusal, the same transaction records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until - a later import or accepted match clears them. Settings > Audible explains an unusable report (`invalid_result`), + a later import clears them, or a newly accepted match does (a poll naming another book, Not this book undone: + the `0093` trigger compares old and new, so a poll repeating the match keeps them). Settings > Audible + explains an unusable report (`invalid_result`), a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone. Older rows keep their existing backup status. A successful import sets the match diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index f3309b7c..670eb041 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -667,8 +667,8 @@ func (e *foldRefusal) Unwrap() error { return e.err } // FoldAudibleImport takes a done backup's place as its title's match (how // "import"), and clears its "Not this book" (the match is now this title's -// own) and what the last poll said of it unmatched (its planned destination -// and contested book). The result must name the job's own library and a book indexed there +// own), what the last poll said of it unmatched (its planned destination +// and contested book) and an earlier backup's refusal. The result must name the job's own library and a book indexed there // (the Bridge rescans before it reports done), else ErrImportNotIndexed, and // the title's own book (importOwnBook), else ErrImportNotOwn. A refusal is // recorded on the title (fold_refusal_reason, fold_refused_at) in the same @@ -710,7 +710,7 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { } _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET match_library_id = ?, match_path = ?, match_how = ?, rejected = 0, import_pending = 0, import_job_id = ?, planned = '', - contest_library_id = NULL, contest_path = '', updated_at = ? + contest_library_id = NULL, contest_path = '', fold_refusal_reason = '', fold_refused_at = NULL, updated_at = ? WHERE account = ? AND asin = ? AND (import_job_id IS NULL OR import_job_id = ?)`, r.LibraryID, r.Path, AudibleMatchImport, j.ID, c.ts(), p.Account, p.ASIN, j.ID) return err diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 064dcd08..b565dfbc 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -614,6 +614,52 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { } } +// A refusal recorded while the title is already matched (a poll matched it +// mid-backup) stays through writes that leave the match as it was, and goes +// with a newly accepted one. +func TestFoldRefusalKeptByUnchangedMatch(t *testing.T) { + t.Parallel() + f := newAudibleFixture(t, "manual") + f.poll(t, "p1", avail("B000000001", "")) + if err := f.setImport("acct0001", "B000000001", 5); err != nil { + t.Fatal(err) + } + lib := f.lib.ID + for _, b := range []*Book{ + {LibraryID: lib, RelPath: "Author/X", IsFolder: true, Title: "X", + Files: []BookFile{{RelPath: "Author/X/Old.m4b"}, {RelPath: "Author/X/Book.m4b"}}}, + {LibraryID: lib, RelPath: "Author/Y", IsFolder: true, Title: "Y", Files: []BookFile{{RelPath: "Author/Y/Y.m4b"}}}, + } { + if _, err := f.c.UpsertBook(f.ctx, b); err != nil { + t.Fatal(err) + } + } + matchedTo := func(path string) AudibleTitleInput { + x := avail("B000000001", "") + x.Match = &AudibleMatch{LibraryID: lib, Path: path, How: "fuzzy"} + return x + } + f.poll(t, "p2", matchedTo("Author/X")) + params, _ := json.Marshal(bridge.AudibleImportParams{Account: "acct0001", ASIN: "B000000001", LibraryID: lib}) + j := bridge.Job{ID: 5, Kind: bridge.KindAudibleImport, State: bridge.StateDone, LibraryID: &lib, Params: params, + Result: json.RawMessage(fmt.Sprintf(`{"library_id":%d,"path":"Author/X","files":[{"path":"Author/X/Book.m4b","size":1}]}`, lib))} + if err := f.c.FoldAudibleImport(f.ctx, j); !errors.Is(err, ErrImportNotOwn) { + t.Fatalf("joined X: %v, want ErrImportNotOwn", err) + } + f.tick(time.Second) + f.poll(t, "p3", matchedTo("Author/X")) + if _, err := f.c.PatchAudibleTitle(f.ctx, "acct0001", "B000000001", AudibleTitlePatch{Rejected: new(false)}); err != nil { + t.Fatal(err) + } + if x := f.title(t, "B000000001"); x.FoldRefusalReason != AudibleFoldNotOwnBook || x.FoldRefusedAt == nil { + t.Fatalf("after writes that kept the match: %+v", x) + } + f.poll(t, "p4", matchedTo("Author/Y")) + if x := f.title(t, "B000000001"); x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { + t.Fatalf("after a new match: %+v", x) + } +} + // Back up's refusals, and Back up everything's set and estimate. func TestAudibleBackupRequests(t *testing.T) { t.Parallel() diff --git a/internal/store/migrations/0093_audible_fold_refusal.sql b/internal/store/migrations/0093_audible_fold_refusal.sql index 4fcc3f15..a5d0c7e5 100644 --- a/internal/store/migrations/0093_audible_fold_refusal.sql +++ b/internal/store/migrations/0093_audible_fold_refusal.sql @@ -2,11 +2,14 @@ ALTER TABLE audible_titles ADD COLUMN fold_refusal_reason TEXT NOT NULL DEFAULT ''; ALTER TABLE audible_titles ADD COLUMN fold_refused_at TEXT; --- A successful import, a poll's accepted match, or undoing "Not this book" --- resolves the refusal in the same write that accepts the match. +-- A poll's newly accepted match, or undoing "Not this book", resolves the +-- refusal in the same write that accepts the match (a successful import clears +-- it itself: catalog.FoldAudibleImport). A write that leaves the match as it +-- was (a poll naming the same book, "Not this book" undone again) keeps it. CREATE TRIGGER audible_title_match_clears_refusal -AFTER UPDATE OF match_library_id, match_path, match_how, rejected ON audible_titles +AFTER UPDATE OF match_library_id, match_path, rejected ON audible_titles WHEN NEW.fold_refused_at IS NOT NULL AND NEW.match_path IS NOT NULL AND NEW.rejected = 0 + AND (OLD.match_path IS NOT NEW.match_path OR OLD.match_library_id IS NOT NEW.match_library_id OR OLD.rejected <> 0) BEGIN UPDATE audible_titles SET fold_refusal_reason = '', fold_refused_at = NULL WHERE account = NEW.account AND asin = NEW.asin; From 65e71b341f44b89fb48c1e961d9bac160ac4898c Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:41:41 +0000 Subject: [PATCH 5/9] Say what happened when a backup lands in a Not this book book The rejected_match sentence said the backup "found" the book, which left the admin guessing; it now says the backup went into that book and so was not matched, in all six languages. ReasonNote's doc comment is back on ReasonNote. Part of KodeStar/audiosilo-bridge#47. --- admin-ui/src/features/audible/audible-topic.tsx | 10 +++++----- admin-ui/src/features/audible/audible.test.tsx | 2 +- admin-ui/src/i18n/locales/de.json | 2 +- admin-ui/src/i18n/locales/en.json | 2 +- admin-ui/src/i18n/locales/es.json | 2 +- admin-ui/src/i18n/locales/fr.json | 2 +- admin-ui/src/i18n/locales/it.json | 2 +- admin-ui/src/i18n/locales/pt.json | 2 +- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/admin-ui/src/features/audible/audible-topic.tsx b/admin-ui/src/features/audible/audible-topic.tsx index 8f26ca1a..6ff9fa80 100644 --- a/admin-ui/src/features/audible/audible-topic.tsx +++ b/admin-ui/src/features/audible/audible-topic.tsx @@ -364,11 +364,6 @@ function PlannedNote({ title: x, template }: { title: AudibleTitle; template?: s ); } -/** - * Why a title isn't shown as here, in words: contested names the book it tied - * for and the account's other titles on it (or says so plainly without them), - * an unknown code reads as a sentence, and Audible's own words stay. - */ /** Why the server could not match the title's completed backup, when it recorded why. */ function FoldNote({ title: x }: { title: AudibleTitle }) { const { t } = useTranslation(); @@ -381,6 +376,11 @@ function FoldNote({ title: x }: { title: AudibleTitle }) { ); } +/** + * Why a title isn't shown as here, in words: contested names the book it tied + * for and the account's other titles on it (or says so plainly without them), + * an unknown code reads as a sentence, and Audible's own words stay. + */ function ReasonNote({ title: x }: { title: AudibleTitle }) { const { t, i18n } = useTranslation(); if (!x.reason) return null; diff --git a/admin-ui/src/features/audible/audible.test.tsx b/admin-ui/src/features/audible/audible.test.tsx index 2730fc0c..b3fcbc34 100644 --- a/admin-ui/src/features/audible/audible.test.tsx +++ b/admin-ui/src/features/audible/audible.test.tsx @@ -770,7 +770,7 @@ describe('audible backups', () => { "The server couldn't use the backup details to match this title to a book in its library.", "The server couldn't find the backed-up book in the library index.", "The server couldn't confirm that the book at the backup destination belongs to this title.", - 'The backup found the book marked “Not this book” for this title.', + "The backup went into the book marked “Not this book” for this title, so the server didn't match it.", "The server couldn't match the backup to this title.", ]; messages.forEach((message, i) => diff --git a/admin-ui/src/i18n/locales/de.json b/admin-ui/src/i18n/locales/de.json index d163e999..3dea3dc6 100644 --- a/admin-ui/src/i18n/locales/de.json +++ b/admin-ui/src/i18n/locales/de.json @@ -3907,7 +3907,7 @@ "audible.fold.invalid_result": "Der Server konnte diesen Titel anhand der Sicherungsdaten keinem Buch in der Bibliothek zuordnen.", "audible.fold.not_indexed": "Der Server konnte das gesicherte Buch im Bibliotheksindex nicht finden.", "audible.fold.not_own_book": "Der Server konnte nicht bestätigen, dass das Buch am Sicherungsziel zu diesem Titel gehört.", - "audible.fold.rejected_match": "Die Sicherung hat das Buch gefunden, das für diesen Titel mit „Nicht dieses Buch“ markiert ist.", + "audible.fold.rejected_match": "Die Sicherung ist im Buch gelandet, das für diesen Titel mit „Nicht dieses Buch“ markiert ist, daher hat der Server sie nicht zugeordnet.", "audible.fold.other": "Der Server konnte die Sicherung diesem Titel nicht zuordnen.", "audible.import.failed": "Sicherung fehlgeschlagen", "audible.import.cancelled": "Sicherung abgebrochen", diff --git a/admin-ui/src/i18n/locales/en.json b/admin-ui/src/i18n/locales/en.json index 2d616236..417208a2 100644 --- a/admin-ui/src/i18n/locales/en.json +++ b/admin-ui/src/i18n/locales/en.json @@ -3907,7 +3907,7 @@ "audible.fold.invalid_result": "The server couldn't use the backup details to match this title to a book in its library.", "audible.fold.not_indexed": "The server couldn't find the backed-up book in the library index.", "audible.fold.not_own_book": "The server couldn't confirm that the book at the backup destination belongs to this title.", - "audible.fold.rejected_match": "The backup found the book marked “Not this book” for this title.", + "audible.fold.rejected_match": "The backup went into the book marked “Not this book” for this title, so the server didn't match it.", "audible.fold.other": "The server couldn't match the backup to this title.", "audible.import.failed": "Backup failed", "audible.import.cancelled": "Backup cancelled", diff --git a/admin-ui/src/i18n/locales/es.json b/admin-ui/src/i18n/locales/es.json index ae678ace..861c043e 100644 --- a/admin-ui/src/i18n/locales/es.json +++ b/admin-ui/src/i18n/locales/es.json @@ -4120,7 +4120,7 @@ "audible.fold.invalid_result": "El servidor no pudo usar los datos de la copia para asociar este título con un libro de la biblioteca.", "audible.fold.not_indexed": "El servidor no encontró el libro copiado en el índice de la biblioteca.", "audible.fold.not_own_book": "El servidor no pudo confirmar que el libro en el destino de la copia corresponde a este título.", - "audible.fold.rejected_match": "La copia encontró el libro marcado como «No es este libro» para este título.", + "audible.fold.rejected_match": "La copia se guardó en el libro marcado como «No es este libro» para este título, así que el servidor no la asoció.", "audible.fold.other": "El servidor no pudo asociar la copia con este título.", "audible.import.failed": "La copia falló", "audible.import.cancelled": "Copia cancelada", diff --git a/admin-ui/src/i18n/locales/fr.json b/admin-ui/src/i18n/locales/fr.json index 61998df8..856e0dc9 100644 --- a/admin-ui/src/i18n/locales/fr.json +++ b/admin-ui/src/i18n/locales/fr.json @@ -4120,7 +4120,7 @@ "audible.fold.invalid_result": "Le serveur n’a pas pu utiliser les informations de la sauvegarde pour associer ce titre à un livre de la bibliothèque.", "audible.fold.not_indexed": "Le serveur n’a pas trouvé le livre sauvegardé dans l’index de la bibliothèque.", "audible.fold.not_own_book": "Le serveur n’a pas pu confirmer que le livre à l’emplacement de la sauvegarde correspond à ce titre.", - "audible.fold.rejected_match": "La sauvegarde a trouvé le livre marqué « Pas ce livre » pour ce titre.", + "audible.fold.rejected_match": "La sauvegarde a été placée dans le livre marqué « Pas ce livre » pour ce titre, le serveur ne l’a donc pas associée.", "audible.fold.other": "Le serveur n’a pas pu associer la sauvegarde à ce titre.", "audible.import.failed": "Échec de la sauvegarde", "audible.import.cancelled": "Sauvegarde annulée", diff --git a/admin-ui/src/i18n/locales/it.json b/admin-ui/src/i18n/locales/it.json index 202accbd..c601b914 100644 --- a/admin-ui/src/i18n/locales/it.json +++ b/admin-ui/src/i18n/locales/it.json @@ -4120,7 +4120,7 @@ "audible.fold.invalid_result": "Il server non è riuscito a usare i dati del backup per abbinare questo titolo a un libro della libreria.", "audible.fold.not_indexed": "Il server non ha trovato il libro del backup nell’indice della libreria.", "audible.fold.not_own_book": "Il server non ha potuto confermare che il libro nella destinazione del backup corrisponda a questo titolo.", - "audible.fold.rejected_match": "Il backup ha trovato il libro contrassegnato come «Non è questo libro» per questo titolo.", + "audible.fold.rejected_match": "Il backup è finito nel libro contrassegnato come «Non è questo libro» per questo titolo, quindi il server non l’ha abbinato.", "audible.fold.other": "Il server non è riuscito ad abbinare il backup a questo titolo.", "audible.import.failed": "Backup non riuscito", "audible.import.cancelled": "Backup annullato", diff --git a/admin-ui/src/i18n/locales/pt.json b/admin-ui/src/i18n/locales/pt.json index 7e7c9066..3c2cc91f 100644 --- a/admin-ui/src/i18n/locales/pt.json +++ b/admin-ui/src/i18n/locales/pt.json @@ -4120,7 +4120,7 @@ "audible.fold.invalid_result": "O servidor não conseguiu usar os dados da cópia para associar este título a um livro da biblioteca.", "audible.fold.not_indexed": "O servidor não encontrou o livro copiado no índice da biblioteca.", "audible.fold.not_own_book": "O servidor não conseguiu confirmar que o livro no destino da cópia corresponde a este título.", - "audible.fold.rejected_match": "A cópia encontrou o livro marcado como «Não é este livro» para este título.", + "audible.fold.rejected_match": "A cópia foi colocada no livro marcado como «Não é este livro» para este título, por isso o servidor não a associou.", "audible.fold.other": "O servidor não conseguiu associar a cópia a este título.", "audible.import.failed": "A cópia falhou", "audible.import.cancelled": "Cópia cancelada", From b10a36451edb305fa3b409a3435baf6e6ebe6606 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:55:58 +0000 Subject: [PATCH 6/9] Log a recorded backup refusal by its reason, not as a failed write A done Audible backup the server refused to match was logged as "recording a backup failed" although the refusal was stored on the title, sending an operator after a database fault that never happened. AudibleFoldRefusal reads the reason off the fold's error, and the log names it; a fold that could not run keeps the old message. Part of bridge#47. --- CONVENTIONS.md | 6 +++--- internal/api/handlers_bridge.go | 8 ++++++-- internal/catalog/audible_import.go | 10 ++++++++++ internal/catalog/audible_import_test.go | 8 ++++++-- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 02daaedf..7af2efbe 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4480,10 +4480,10 @@ every session. CLAUDE.md keeps a one-line index of these topics. match; and never the book the admin marked Not this book for the title. On refusal, the same transaction records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until a later import clears them, or a newly accepted match does (a poll naming another book, Not this book undone: - the `0093` trigger compares old and new, so a poll repeating the match keeps them). Settings > Audible - explains an unusable report (`invalid_result`), + the `0093` trigger compares old and new, so a poll repeating the match keeps them). Settings > Audible explains an unusable report (`invalid_result`), a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked - Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone. Older rows keep their existing backup status. + Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone; + the log names the reason (`AudibleFoldRefusal`). Older rows keep their existing backup status. A successful import sets the match (`match_how:"import"`), clears rejected and pending, only while `import_job_id` is still this job. A poll keeps an `import` match while its book is indexed and the poll names no other. A failure's code is the diff --git a/internal/api/handlers_bridge.go b/internal/api/handlers_bridge.go index acd11c12..2976d88b 100644 --- a/internal/api/handlers_bridge.go +++ b/internal/api/handlers_bridge.go @@ -54,9 +54,13 @@ func (a *API) SetBridge(b *bridge.Service) { } } if job.Kind == bridge.KindAudibleImport { - // A done backup becomes its title's match. + // A done backup becomes its title's match, or the title records why not. if err := a.cat.FoldAudibleImport(ctx, job); err != nil { - a.log.Warn("audible: recording a backup failed", "job", job.ID, "err", err) + if reason := catalog.AudibleFoldRefusal(err); reason != "" { + a.log.Warn("audible: a backup could not become its title's match", "job", job.ID, "reason", reason, "err", err) + } else { + a.log.Warn("audible: recording a backup failed", "job", job.ID, "err", err) + } } } if job.Kind == bridge.KindLibrivoxFetch { diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index 670eb041..c0bcda74 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -665,6 +665,16 @@ type foldRefusal struct { func (e *foldRefusal) Error() string { return e.err.Error() } func (e *foldRefusal) Unwrap() error { return e.err } +// AudibleFoldRefusal is the reason (one of AudibleFold*) of a +// FoldAudibleImport error that is a refusal, "" for one that is not (the fold +// could not run). +func AudibleFoldRefusal(err error) string { + if r, ok := errors.AsType[*foldRefusal](err); ok { + return r.reason + } + return "" +} + // FoldAudibleImport takes a done backup's place as its title's match (how // "import"), and clears its "Not this book" (the match is now this title's // own), what the last poll said of it unmatched (its planned destination diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index b565dfbc..445a2b4a 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -643,8 +643,12 @@ func TestFoldRefusalKeptByUnchangedMatch(t *testing.T) { params, _ := json.Marshal(bridge.AudibleImportParams{Account: "acct0001", ASIN: "B000000001", LibraryID: lib}) j := bridge.Job{ID: 5, Kind: bridge.KindAudibleImport, State: bridge.StateDone, LibraryID: &lib, Params: params, Result: json.RawMessage(fmt.Sprintf(`{"library_id":%d,"path":"Author/X","files":[{"path":"Author/X/Book.m4b","size":1}]}`, lib))} - if err := f.c.FoldAudibleImport(f.ctx, j); !errors.Is(err, ErrImportNotOwn) { - t.Fatalf("joined X: %v, want ErrImportNotOwn", err) + err := f.c.FoldAudibleImport(f.ctx, j) + if !errors.Is(err, ErrImportNotOwn) || AudibleFoldRefusal(err) != AudibleFoldNotOwnBook { + t.Fatalf("joined X: %v, want ErrImportNotOwn refused %s", err, AudibleFoldNotOwnBook) + } + if AudibleFoldRefusal(nil) != "" || AudibleFoldRefusal(ErrImportNotOwn) != "" { + t.Fatal("a refusal reason for an error that refused nothing") } f.tick(time.Second) f.poll(t, "p3", matchedTo("Author/X")) From b414d609be6121b274196c77206d77e2b15910dc Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:56:03 +0000 Subject: [PATCH 7/9] Keep a backup refusal when the title's book moves A book's move or join rewrites the title's match_path, which the 0093 trigger reads as a newly accepted match, so renaming the folder of a book a backup was refused for (not_own_book) dropped the console's explanation although the title still has the same book and nothing new was accepted. moveAudibleTitles reads the moved titles' refusals first and puts them back in the same transaction. Part of bridge#47. --- CONVENTIONS.md | 3 ++- internal/catalog/audible_import_test.go | 8 ++++++++ internal/catalog/listening.go | 21 +++++++++++++++++++-- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 7af2efbe..dda06b6a 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4480,7 +4480,8 @@ every session. CLAUDE.md keeps a one-line index of these topics. match; and never the book the admin marked Not this book for the title. On refusal, the same transaction records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until a later import clears them, or a newly accepted match does (a poll naming another book, Not this book undone: - the `0093` trigger compares old and new, so a poll repeating the match keeps them). Settings > Audible explains an unusable report (`invalid_result`), + the `0093` trigger compares old and new, so a poll repeating the match keeps them; a book's move or join + keeps the title's book, so `moveAudibleTitles` puts them back). Settings > Audible explains an unusable report (`invalid_result`), a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone; the log names the reason (`AudibleFoldRefusal`). Older rows keep their existing backup status. diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 445a2b4a..2d473676 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -658,6 +658,14 @@ func TestFoldRefusalKeptByUnchangedMatch(t *testing.T) { if x := f.title(t, "B000000001"); x.FoldRefusalReason != AudibleFoldNotOwnBook || x.FoldRefusedAt == nil { t.Fatalf("after writes that kept the match: %+v", x) } + // The book moving keeps the title's book, and so the refusal. + if err := f.c.MoveDurableState(f.ctx, lib, "Author/X", "Author/X2"); err != nil { + t.Fatal(err) + } + if x := f.title(t, "B000000001"); x.Match == nil || x.Match.Path != "Author/X2" || + x.FoldRefusalReason != AudibleFoldNotOwnBook || x.FoldRefusedAt == nil { + t.Fatalf("after the book moved: %+v", x) + } f.poll(t, "p4", matchedTo("Author/Y")) if x := f.title(t, "B000000001"); x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { t.Fatalf("after a new match: %+v", x) diff --git a/internal/catalog/listening.go b/internal/catalog/listening.go index c401ab1f..ede76b74 100644 --- a/internal/catalog/listening.go +++ b/internal/catalog/listening.go @@ -462,14 +462,31 @@ func (c *Catalog) MoveDurableState(ctx context.Context, libraryID int64, oldPath // leaves the titles where they were (the next poll matches them afresh). A // left-behind row a move's carry did not change (its person never played the // moved book, or the row was the newer and won the merge) is another book's -// place: its offer is taken back (keepLeftOffers, server#359). +// place: its offer is taken back (keepLeftOffers, server#359). A moved title +// keeps its book, so it keeps a backup's refusal (fold_refusal_reason, 0093), +// which the 0093 trigger clears on any change of the match: put back after. func moveAudibleTitles(ctx context.Context, tx *sql.Tx, libraryID int64, from, into string) error { + type refusal struct{ account, asin, reason, at string } + kept, err := queryRows(ctx, tx, func(rows *sql.Rows, r *refusal) error { + return rows.Scan(&r.account, &r.asin, &r.reason, &r.at) + }, `SELECT account, asin, fold_refusal_reason, fold_refused_at FROM audible_titles + WHERE match_library_id = ? AND match_path = ? AND fold_refused_at IS NOT NULL`, libraryID, from) + if err != nil { + return err + } if _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET match_path = ? WHERE match_library_id = ? AND match_path = ?`, into, libraryID, from); err != nil { return err } - _, err := tx.ExecContext(ctx, + for _, r := range kept { + if _, err := tx.ExecContext(ctx, + `UPDATE audible_titles SET fold_refusal_reason = ?, fold_refused_at = ? WHERE account = ? AND asin = ?`, + r.reason, r.at, r.account, r.asin); err != nil { + return err + } + } + _, err = tx.ExecContext(ctx, `UPDATE audible_titles SET contest_path = ? WHERE contest_library_id = ? AND contest_path = ?`, into, libraryID, from) return err From 390dc1c7d84dc4fff0e8a198f692c2f8f9b68473 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 17:56:11 +0000 Subject: [PATCH 8/9] Clear a backup refusal with the library the backup went into Deleting a library drops its matches and contests and cascades its jobs away, but a title whose backup into it was refused kept saying the server couldn't find the book in a library that no longer exists. DeleteLibrary clears the refusal on titles whose import job is that library's, in its own transaction, before the jobs go. Part of bridge#47. --- CONVENTIONS.md | 3 +- internal/catalog/audible_import_test.go | 39 +++++++++++++++++++++++++ internal/catalog/library.go | 10 ++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index dda06b6a..45688b4f 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4481,7 +4481,8 @@ every session. CLAUDE.md keeps a one-line index of these topics. records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until a later import clears them, or a newly accepted match does (a poll naming another book, Not this book undone: the `0093` trigger compares old and new, so a poll repeating the match keeps them; a book's move or join - keeps the title's book, so `moveAudibleTitles` puts them back). Settings > Audible explains an unusable report (`invalid_result`), + keeps the title's book, so `moveAudibleTitles` puts them back), or deleting the library the backup went + into does (`DeleteLibrary`). Settings > Audible explains an unusable report (`invalid_result`), a missing book (`not_indexed`), a book the backup could not claim (`not_own_book`), or one marked Not this book (`rejected_match`) (`AudibleFold*`, the console's `FOLD_REASONS`), even after the job is gone; the log names the reason (`AudibleFoldRefusal`). Older rows keep their existing backup status. diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 2d473676..701f588d 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -672,6 +672,45 @@ func TestFoldRefusalKeptByUnchangedMatch(t *testing.T) { } } +// A backup's refusal goes with the library the backup went into, as the job +// does; one into another library stays. +func TestFoldRefusalGoesWithItsLibrary(t *testing.T) { + t.Parallel() + f := newAudibleFixture(t, "manual") + f.poll(t, "p1", avail("B000000001", ""), avail("B000000002", "")) + other, err := f.c.CreateLibrary(f.ctx, Library{Name: "Other", Root: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + for i, lib := range []int64{f.lib.ID, other.ID} { + asin := fmt.Sprintf("B00000000%d", i+1) + res, err := f.c.db.ExecContext(f.ctx, `INSERT INTO bridge_jobs(kind, library_id, rel_path, state, params, dedupe_key, created_at, updated_at) + VALUES(?, ?, '', 'done', '{}', ?, 't', 't')`, bridge.KindAudibleImport, lib, "k"+asin) + if err != nil { + t.Fatal(err) + } + id, _ := res.LastInsertId() + if err := f.setImport("acct0001", asin, id); err != nil { + t.Fatal(err) + } + params, _ := json.Marshal(bridge.AudibleImportParams{Account: "acct0001", ASIN: asin, LibraryID: lib}) + j := bridge.Job{ID: id, Kind: bridge.KindAudibleImport, State: bridge.StateDone, LibraryID: &lib, Params: params, + Result: json.RawMessage(fmt.Sprintf(`{"library_id":%d,"path":"Missing"}`, lib))} + if err := f.c.FoldAudibleImport(f.ctx, j); AudibleFoldRefusal(err) != AudibleFoldNotIndexed { + t.Fatalf("fold %s: %v", asin, err) + } + } + if err := f.c.DeleteLibrary(f.ctx, f.lib.ID); err != nil { + t.Fatal(err) + } + if x := f.title(t, "B000000001"); x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { + t.Fatalf("refused into the deleted library: %+v", x) + } + if x := f.title(t, "B000000002"); x.FoldRefusalReason != AudibleFoldNotIndexed || x.FoldRefusedAt == nil { + t.Fatalf("refused into another library: %+v", x) + } +} + // Back up's refusals, and Back up everything's set and estimate. func TestAudibleBackupRequests(t *testing.T) { t.Parallel() diff --git a/internal/catalog/library.go b/internal/catalog/library.go index 80192860..48f1b727 100644 --- a/internal/catalog/library.go +++ b/internal/catalog/library.go @@ -395,7 +395,8 @@ func (c *Catalog) DeleteLibrary(ctx context.Context, id int64) error { return err } // Audible titles matched to its books lose the match (path-keyed, no FK), those - // contested over one the contest, and + // contested over one the contest, those whose backup into it was refused the + // refusal (0093; the job cascades away with the library), and // the accounts mapped to it pause (library_id SET NULL by the FK), their open // polls cancelled: all with the library's own delete, so no titles call can // match a book of it in between. The delete takes every grant of the library @@ -428,6 +429,13 @@ func (c *Catalog) DeleteLibrary(ctx context.Context, id int64) error { `UPDATE audible_titles SET contest_library_id = NULL, contest_path = '' WHERE contest_library_id = ?`, id); err != nil { return err } + if _, err := tx.ExecContext(ctx, + `UPDATE audible_titles SET fold_refusal_reason = '', fold_refused_at = NULL + WHERE fold_refused_at IS NOT NULL + AND import_job_id IN (SELECT id FROM bridge_jobs WHERE library_id = ? AND kind = ?)`, + id, bridge.KindAudibleImport); err != nil { + return err + } paused, err := queryRows(ctx, tx, func(rows *sql.Rows, account *string) error { return rows.Scan(account) }, `SELECT account FROM audible_accounts WHERE library_id = ?`, id) if err != nil { From 7335767a616618c46ff15784c8e8e76fd46e647e Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 18:07:34 +0000 Subject: [PATCH 9/9] Clear an older backup refusal when the title's next backup is queued A refusal stayed until a later import or match, so a newer backup that failed or was cancelled showed the older refusal beside its own status, and a newer done job whose fold never ran had its "Backed up" hidden by the older job's reason. SetAudibleImportTx now clears the refusal in the transaction that queues the job, so a stored refusal is always the title's current backup's and the console speaks only for the latest backup. Part of bridge#47. --- CONVENTIONS.md | 3 ++- admin-ui/src/features/audible/audible-model.ts | 1 + admin-ui/src/features/audible/audible.test.tsx | 5 ++--- internal/catalog/audible_import.go | 8 ++++++-- internal/catalog/audible_import_test.go | 5 ++++- 5 files changed, 15 insertions(+), 7 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 45688b4f..9fff98eb 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4479,7 +4479,8 @@ every session. CLAUDE.md keeps a one-line index of these topics. book already there (the scan makes it one book) never makes that book, nor another title's, the title's match; and never the book the admin marked Not this book for the title. On refusal, the same transaction records `fold_refusal_reason` and `fold_refused_at` on the title (`0093`). The admin title includes both until - a later import clears them, or a newly accepted match does (a poll naming another book, Not this book undone: + the title's next backup is queued (`SetAudibleImportTx`: the status is that backup's now, so a refusal is + always the title's import job's), or a newly accepted match clears them (a poll naming another book, Not this book undone: the `0093` trigger compares old and new, so a poll repeating the match keeps them; a book's move or join keeps the title's book, so `moveAudibleTitles` puts them back), or deleting the library the backup went into does (`DeleteLibrary`). Settings > Audible explains an unusable report (`invalid_result`), diff --git a/admin-ui/src/features/audible/audible-model.ts b/admin-ui/src/features/audible/audible-model.ts index 4ba302bc..8c72d309 100644 --- a/admin-ui/src/features/audible/audible-model.ts +++ b/admin-ui/src/features/audible/audible-model.ts @@ -217,6 +217,7 @@ export function importStatus( case 'needs_attention': return { key: 'audible.import.parked', tone: 'warn', code }; case 'done': + // A stored refusal is always this job's: queueing a backup clears it. return x.fold_refusal_reason ? null : { key: 'audible.import.done', tone: 'ok' }; case 'failed': return { key: 'audible.import.failed', tone: 'bad', code }; diff --git a/admin-ui/src/features/audible/audible.test.tsx b/admin-ui/src/features/audible/audible.test.tsx index b3fcbc34..72ccdd15 100644 --- a/admin-ui/src/features/audible/audible.test.tsx +++ b/admin-ui/src/features/audible/audible.test.tsx @@ -749,7 +749,7 @@ describe('settings > audible', () => { }); describe('audible backups', () => { - it("shows the title's stored reason even after the job is gone or another backup starts", async () => { + it("shows the title's stored reason in place of Backed up, even after the job is gone", async () => { const done = { job_id: 4, state: 'done', code: '' } as const; const reasons = ['invalid_result', 'not_indexed', 'not_own_book', 'rejected_match', 'new_code']; const titles = reasons.map((reason, i) => @@ -758,7 +758,7 @@ describe('audible backups', () => { match: null, fold_refusal_reason: reason, fold_refused_at: '2026-11-01T09:00:00Z', - import: i === 0 ? null : i === 1 ? { ...done, state: 'queued' } : done, + import: i === 0 ? null : done, }), ); titles.push(title({ asin: 'B000000009', match: null, import: done })); @@ -776,7 +776,6 @@ describe('audible backups', () => { messages.forEach((message, i) => expect(within(rows[i]).getByText(message)).toBeInTheDocument(), ); - expect(within(rows[1]).getByText(en['audible.import.queued'])).toBeInTheDocument(); expect(within(list).getAllByText('Backed up')).toHaveLength(1); expect(within(rows[5]).getByText('Backed up')).toBeInTheDocument(); }); diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index c0bcda74..cc2436bf 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -622,9 +622,13 @@ func (o *seriesOwner) any(ctx context.Context, series []AudibleSeries) (bool, er // SetAudibleImportTx records job as the backup of account's title asin (a // pending request is now queued), in tx: the transaction that queued the job -// (bridge.EnqueueAll), so a job and its title's record commit together. +// (bridge.EnqueueAll), so a job and its title's record commit together. An +// earlier backup's refusal (fold_refusal_reason, 0093) goes: the title's +// status is this backup's now, so a stored refusal is always its import +// job's. func (c *Catalog) SetAudibleImportTx(ctx context.Context, tx *sql.Tx, account, asin string, job int64) error { - _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET import_job_id = ?, import_pending = 0, updated_at = ? + _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET import_job_id = ?, import_pending = 0, + fold_refusal_reason = '', fold_refused_at = NULL, updated_at = ? WHERE account = ? AND asin = ?`, job, c.ts(), account, asin) return err } diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 701f588d..8b9e1cd6 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -492,7 +492,10 @@ func TestFoldAudibleImport(t *testing.T) { if err := f.setImport("acct0001", "B000000001", 7); err != nil { t.Fatal(err) } - checkRefusal(AudibleFoldInvalidResult, f.c.ts()) + // A newer backup takes the title's status: the older refusal goes. + if x := f.title(t, "B000000001"); x.FoldRefusalReason != "" || x.FoldRefusedAt != nil { + t.Fatalf("a newer backup kept the older refusal: %+v", x) + } if err := f.c.FoldAudibleImport(f.ctx, job(7, lib, "Author/Book")); err != nil { t.Fatal(err) }