Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion CONVENTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions admin-ui/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
23 changes: 22 additions & 1 deletion admin-ui/src/features/audible/audible-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down Expand Up @@ -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.<reason>`.
*/
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<AudibleTitle, 'fold_refusal_reason'>): 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
Expand Down
14 changes: 14 additions & 0 deletions admin-ui/src/features/audible/audible-topic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { CardEmpty } from '@/features/settings/card-empty';
import {
accountName,
chosenAccount,
foldReasonKey,
importStatus,
lookList,
onServer,
Expand Down Expand Up @@ -268,6 +269,7 @@ function TitleRow({
<span className="font-mono text-[12px] text-muted-foreground">{details.join(' · ')}</span>
<PlannedNote title={x} template={template} />
<ReasonNote title={x} />
<FoldNote title={x} />
{backup?.code ? (
<span className="text-[12.5px] text-muted-foreground">{t(backup.code)}</span>
) : null}
Expand Down Expand Up @@ -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 (
<StatusText tone="warn" colored className="text-[12.5px]">
{t(key)}
</StatusText>
);
}

/**
* 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),
Expand Down
41 changes: 41 additions & 0 deletions admin-ui/src/features/audible/audible.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {
canSync,
chosenAccount,
cleanDest,
FOLD_REASONS,
foldReasonKey,
importStatus,
lookList,
matchedParam,
Expand Down Expand Up @@ -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<string, string>;
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);
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 5 additions & 0 deletions admin-ui/src/i18n/locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
30 changes: 30 additions & 0 deletions internal/api/audible_import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 6 additions & 2 deletions internal/api/handlers_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 7 additions & 2 deletions internal/catalog/audible.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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`

Expand All @@ -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 {
Expand Down
Loading
Loading