diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 3f7777db..9fff98eb 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4477,7 +4477,17 @@ 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 + 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`), + 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. + 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..8c72d309 100644 --- a/admin-ui/src/features/audible/audible-model.ts +++ b/admin-ui/src/features/audible/audible-model.ts @@ -217,7 +217,8 @@ export function importStatus( case 'needs_attention': return { key: 'audible.import.parked', tone: 'warn', code }; case 'done': - return { key: 'audible.import.done', tone: 'ok' }; + // 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 }; case 'cancelled': @@ -337,6 +338,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 b199c2b7..6ff9fa80 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,6 +269,7 @@ function TitleRow({ {details.join(' · ')} + {backup?.code ? ( {t(backup.code)} ) : null} @@ -362,6 +364,18 @@ function PlannedNote({ title: x, template }: { title: AudibleTitle; template?: s ); } +/** 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)} + + ); +} + /** * 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), diff --git a/admin-ui/src/features/audible/audible.test.tsx b/admin-ui/src/features/audible/audible.test.tsx index 9fd15e4f..72ccdd15 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, @@ -747,6 +749,45 @@ describe('settings > audible', () => { }); describe('audible backups', () => { + 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) => + title({ + asin: `B00000000${i}`, + match: null, + fold_refusal_reason: reason, + fold_refused_at: '2026-11-01T09:00:00Z', + import: i === 0 ? null : 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 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) => + expect(within(rows[i]).getByText(message)).toBeInTheDocument(), + ); + expect(within(list).getAllByText('Backed up')).toHaveLength(1); + 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); diff --git a/admin-ui/src/i18n/locales/de.json b/admin-ui/src/i18n/locales/de.json index ab0fd9f8..3dea3dc6 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 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", "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..417208a2 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 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", "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..861c043e 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 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", "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..856e0dc9 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 é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", "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..c601b914 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 è 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", "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..3c2cc91f 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 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", "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..a831bf6d 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 != 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 { + 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/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.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..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 } @@ -641,36 +645,94 @@ 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 } + +// 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) 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 job that isn't -// a done audible.import, or whose title has another backup since, changes -// nothing. A user-state write. +// the title's own book (importOwnBook), else ErrImportNotOwn. A refusal is +// 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, err := bridge.AudibleImportOf(j) - if err != nil { + 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 r.LibraryID != *j.LibraryID || r.LibraryID != p.LibraryID || !bridgeBookPath(r.Path) { - return ErrImportNotIndexed + 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)} + } } - return c.db.WithUserStateTx(ctx, "FoldAudibleImport", func(tx *sql.Tx) error { - if err := importOwnBook(ctx, tx, p, r); err != nil { + 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 { + if refused == nil { + if err := importOwnBook(ctx, tx, p, r); !errors.As(err, &refused) && err != nil { + return err + } + } + 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)`, + refused.reason, c.ts(), j.ID, p.Account, p.ASIN) return err } _, 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 }) + if err != nil || refused == nil { + return err + } + return refused } // importOwnBook checks, through tx, that the book a done backup's result names @@ -680,7 +742,7 @@ 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. +// 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 @@ -696,11 +758,11 @@ 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 &foldRefusal{AudibleFoldNotIndexed, ErrImportNotIndexed} case err != nil: return err case rejected: - return ErrImportNotOwn + return &foldRefusal{AudibleFoldRejectedMatch, ErrImportNotOwn} case strings.EqualFold(asin, p.ASIN): return nil } @@ -716,11 +778,11 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams } } if len(files) == 0 { - return ErrImportNotOwn + return &foldRefusal{AudibleFoldNotOwnBook, ErrImportNotOwn} } for _, f := range files { if !placed[f] { - return ErrImportNotOwn + return &foldRefusal{AudibleFoldNotOwnBook, ErrImportNotOwn} } } return nil diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index de251f59..8b9e1cd6 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,33 @@ 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() + 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) + } + } + 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(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. + 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(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(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 { @@ -457,6 +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(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) @@ -464,11 +489,23 @@ 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) + } + // 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) + } + // 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 +577,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 != 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" { t.Fatalf("Other's match = %+v", x.Match) @@ -561,8 +598,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 != 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 || + 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 { @@ -573,6 +617,103 @@ 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))} + 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")) + 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) + } + // 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) + } +} + +// 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 { 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 diff --git a/internal/store/migration_0093_test.go b/internal/store/migration_0093_test.go new file mode 100644 index 00000000..38a30d8d --- /dev/null +++ b/internal/store/migration_0093_test.go @@ -0,0 +1,28 @@ +package store + +import ( + "context" + "slices" + "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() }) + 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 new file mode 100644 index 00000000..a5d0c7e5 --- /dev/null +++ b/internal/store/migrations/0093_audible_fold_refusal.sql @@ -0,0 +1,16 @@ +-- 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 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, 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; +END;