diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 6c3b360a..bafe9df6 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -4411,8 +4411,10 @@ every session. CLAUDE.md keeps a one-line index of these topics. `bridge/audible.go`, `api/handlers_audible.go`)**: the Bridge signs in to Audible and holds every credential; the server only keeps what it reports. `0063`: `audible_accounts` (`account` = the Bridge's id `^[a-z0-9]{8,32}$`, label, marketplace = one of `config.Regions`, `user_id` -> users CASCADE (deleting a - person, or an owner their member, then cancels the gone accounts' open poll, backups and sync, - `catalog.CancelOrphanAudibleJobs`, bridge#46), `library_id` -> + person captures their account ids and those of deleted members before the cascade. After commit, + `catalog.CancelRemovedAudibleJobs` cancels those accounts' open poll, backups and sync by indexed job key. + Each Audible scheduler pass also checks the open-job index for orphan jobs, even while the Bridge is offline. + An empty pass takes no writer (`catalog.CancelOrphanAudibleJobs`, bridge#46)), `library_id` -> libraries SET NULL, policy `all`|`series`|`manual`, sync, `poll_hours` default 6, `last_poll_at`, `last_queued_at`) and `audible_titles` (account CASCADE + asin; title, authors/series JSON, release_date, runtime_s, state `available`|`preorder`|`unavailable`|`gone`, reason, the match `match_library_id` / @@ -4509,7 +4511,9 @@ 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. On refusal, the same transaction + match; and never the book the admin marked Not this book for the title. If the placement joined a disc into + the parent book, its indexed files must all belong to the backup even when the Bridge added its ASIN. + 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: @@ -4551,9 +4555,13 @@ every session. CLAUDE.md keeps a one-line index of these topics. (`{queued, skipped}`, `skipped` the titles left out because their params no longer validate (a stored `dest_path` from before a rule tightened: `CheckAudibleDestPath`; an account template that no longer validates refuses the batch: 400 `invalid_template`, reason `account`), the rest queued; `backupAllSQL`: available, unmatched, not rejected, ignored or contested, nothing open, the latest import not a `done` one whose book is still indexed (a refused fold, `ErrImportNotOwn`, isn't queued again; a done one whose book left the library is), a failed or cancelled one again; a console Back up of one contested or done title, and its pending request, still queue), `PATCH /admin/audible/titles/{account}/{asin}` (`{rejected?, dest_path?}`; 400 - `invalid_dest_path`, also for a disc folder ("CD 3") directly inside an indexed book or a folder with a - `book` override, which the scan would join into it: `checkDestOwnFolder`, `metadata.IsDiscFolder`) and `PATCH /admin/audible/accounts/{account}` (`{policy?, template?}`, 400 - `invalid_policy` / `invalid_template`), audited: a queued Back up `bridge.job` (kind `audible.import`; also + `invalid_dest_path`, also for a disc folder ("CD 3") directly inside an indexed book (reason `indexed_book`) + or a folder set to one book (`book_override`). Setting the `book` override checks saved destinations and open + imports in the same library. Changing an account's library or a placement template checks disc folders + the server can identify before placement (`checkDestOwnFolder`, `audibleDiscParent`; a remap skips the + destinations of titles already on this server, which are never backed up again: `checkAudibleRemap`). An actual joined + placement is checked at fold time too) and `PATCH /admin/audible/accounts/{account}` (`{policy?, template?}`, 400 + `invalid_policy` / `invalid_template` / `invalid_dest_path`), audited: a queued Back up `bridge.job` (kind `audible.import`; also when recording it on the title failed), a pending one `bridge.audible.backup`, then `bridge.audible.backup_all` / `title` / `account` (the audit guard reads `moduleRoutes.Admin` routes too), each with the account's id in its details and its name as the row's target, as `bridge.audible.remove` has it (`audibleAccountName`: diff --git a/admin-ui/src/api/client.ts b/admin-ui/src/api/client.ts index 061c78eb..98fd24c7 100644 --- a/admin-ui/src/api/client.ts +++ b/admin-ui/src/api/client.ts @@ -657,7 +657,7 @@ export const api = { `/admin/audible/titles/${encodeURIComponent(account)}/${encodeURIComponent(asin)}`, patch, ), - /** An account's policy and template; 400 invalid_policy, invalid_template. */ + /** An account's policy and template; 400 invalid_policy, invalid_template, invalid_dest_path. */ patchAudibleAccount: (account: string, patch: AudibleAccountPatch) => request<{ account: AudibleAccount }>( 'PATCH', diff --git a/admin-ui/src/i18n/locales/de.json b/admin-ui/src/i18n/locales/de.json index 737235ba..d8885fea 100644 --- a/admin-ui/src/i18n/locales/de.json +++ b/admin-ui/src/i18n/locales/de.json @@ -4033,6 +4033,8 @@ "errors.invalidDestPath": "Das ist kein Ort in der Bibliothek. Verwende Ordner und einen Dateinamen wie Autor/Reihe/Titel.m4b, ohne versteckte Ordner, Backslashes oder \"..\".", "errors.invalidTemplate": "Diese Vorlage funktioniert nicht. Verwende die Variablen in geschweiften Klammern, etwa {Author}/{Series}/{Title}, und bleib unter 500 Zeichen.", "errors.invalid_template.account": "Die Ablagevorlage dieses Kontos funktioniert nicht mehr. Korrigiere sie in den Kontoeinstellungen und sichere dann erneut.", + "errors.invalid_dest_path.indexed_book": "Dieser Disc-Ordner liegt in einem bereits erfassten Buch. Wähle einen separaten Ordner für die Audible-Sicherung.", + "errors.invalid_dest_path.book_override": "Diese Audible-Sicherung verwendet einen Disc-Ordner, der durch die Ordnereinstellung mit anderen Discs zu einem Buch zusammengefasst würde. Wähle einen separaten Ordner für die Sicherung.", "errors.invalid_dest_path.title": "Das Ziel dieses Titels ist nicht mehr gültig. Lege es mit Ziel neu fest und sichere dann erneut.", "librivox.title": "LibriVox", "librivox.description": "Finde ein freies, gemeinfreies Hörbuch auf LibriVox und füge es einer Bibliothek hinzu. Deine Bridge lädt es herunter, legt es ab und ordnet es seiner Aufnahme zu.", diff --git a/admin-ui/src/i18n/locales/en.json b/admin-ui/src/i18n/locales/en.json index cde3c2be..c626acbe 100644 --- a/admin-ui/src/i18n/locales/en.json +++ b/admin-ui/src/i18n/locales/en.json @@ -4033,6 +4033,8 @@ "errors.invalidDestPath": "That isn't a place inside the library. Use folders and a file name such as Author/Series/Title.m4b, with no hidden folders, backslashes or \"..\".", "errors.invalidTemplate": "That template doesn't work. Use the variables in braces, such as {Author}/{Series}/{Title}, and keep it under 500 characters.", "errors.invalid_template.account": "This account's placement template no longer works. Fix it in Account settings and back up again.", + "errors.invalid_dest_path.indexed_book": "This disc folder is inside an indexed book. Choose a separate folder for the Audible backup.", + "errors.invalid_dest_path.book_override": "This Audible backup uses a disc folder that the folder setting would join into one book. Choose a separate folder for the backup.", "errors.invalid_dest_path.title": "This title's destination is no longer valid. Set it again with Destination and back up again.", "librivox.title": "LibriVox", "librivox.description": "Find a free public-domain audiobook on LibriVox and add it to a library. Your Bridge downloads it, places it and matches it to its recording.", diff --git a/admin-ui/src/i18n/locales/es.json b/admin-ui/src/i18n/locales/es.json index 356cd3b5..c7f94a8f 100644 --- a/admin-ui/src/i18n/locales/es.json +++ b/admin-ui/src/i18n/locales/es.json @@ -4255,6 +4255,8 @@ "errors.invalidDestPath": "Eso no es un lugar dentro de la biblioteca. Usa carpetas y un nombre de archivo como Autor/Serie/Título.m4b, sin carpetas ocultas, barras invertidas ni \"..\".", "errors.invalidTemplate": "Esa plantilla no funciona. Usa las variables entre llaves, como {Author}/{Series}/{Title}, y no pases de 500 caracteres.", "errors.invalid_template.account": "La plantilla de ubicación de esta cuenta ya no funciona. Corrígela en Ajustes de la cuenta y vuelve a hacer la copia.", + "errors.invalid_dest_path.indexed_book": "Esta carpeta de disco está dentro de un libro indexado. Elige otra carpeta para la copia de Audible.", + "errors.invalid_dest_path.book_override": "La copia de Audible usa una carpeta de disco que este ajuste uniría con otros discos en un solo libro. Elige otra carpeta para la copia.", "errors.invalid_dest_path.title": "El destino de este título ya no es válido. Vuelve a definirlo con Destino y vuelve a hacer la copia.", "librivox.title": "LibriVox", "librivox.description": "Busca un audiolibro gratuito de dominio público en LibriVox y añádelo a una biblioteca. Tu Bridge lo descarga, lo coloca y lo asocia a su grabación.", diff --git a/admin-ui/src/i18n/locales/fr.json b/admin-ui/src/i18n/locales/fr.json index de8dcbac..298960dc 100644 --- a/admin-ui/src/i18n/locales/fr.json +++ b/admin-ui/src/i18n/locales/fr.json @@ -4255,6 +4255,8 @@ "errors.invalidDestPath": "Ce n'est pas un emplacement dans la bibliothèque. Utilisez des dossiers et un nom de fichier comme Auteur/Série/Titre.m4b, sans dossiers cachés, barres obliques inverses ni « .. ».", "errors.invalidTemplate": "Ce modèle ne fonctionne pas. Utilisez les variables entre accolades, comme {Author}/{Series}/{Title}, en moins de 500 caractères.", "errors.invalid_template.account": "Le modèle d'emplacement de ce compte ne fonctionne plus. Corrigez-le dans Réglages du compte et relancez la sauvegarde.", + "errors.invalid_dest_path.indexed_book": "Ce dossier de disque se trouve dans un livre déjà indexé. Choisissez un dossier distinct pour la sauvegarde Audible.", + "errors.invalid_dest_path.book_override": "La sauvegarde Audible utilise un dossier de disque que ce réglage regrouperait avec d’autres disques en un seul livre. Choisissez un dossier distinct pour la sauvegarde.", "errors.invalid_dest_path.title": "La destination de ce titre n'est plus valide. Redéfinissez-la avec Destination et relancez la sauvegarde.", "librivox.title": "LibriVox", "librivox.description": "Trouvez un livre audio gratuit du domaine public sur LibriVox et ajoutez-le à une bibliothèque. Votre Bridge le télécharge, le range et l'associe à son enregistrement.", diff --git a/admin-ui/src/i18n/locales/it.json b/admin-ui/src/i18n/locales/it.json index 649f57f8..c8f42b61 100644 --- a/admin-ui/src/i18n/locales/it.json +++ b/admin-ui/src/i18n/locales/it.json @@ -4255,6 +4255,8 @@ "errors.invalidDestPath": "Non è un percorso dentro la libreria. Usa cartelle e un nome di file come Autore/Serie/Titolo.m4b, senza cartelle nascoste, barre rovesciate o \"..\".", "errors.invalidTemplate": "Questo modello non funziona. Usa le variabili tra parentesi graffe, come {Author}/{Series}/{Title}, e non superare i 500 caratteri.", "errors.invalid_template.account": "Il modello di posizione di questo account non funziona più. Correggilo in Impostazioni account e riprova il backup.", + "errors.invalid_dest_path.indexed_book": "Questa cartella del disco si trova all’interno di un libro già indicizzato. Scegli una cartella separata per il backup Audible.", + "errors.invalid_dest_path.book_override": "Il backup Audible usa una cartella del disco che questa impostazione unirebbe ad altri dischi in un unico libro. Scegli una cartella separata per il backup.", "errors.invalid_dest_path.title": "La destinazione di questo titolo non è più valida. Impostala di nuovo con Destinazione e riprova il backup.", "librivox.title": "LibriVox", "librivox.description": "Trova un audiolibro gratuito di pubblico dominio su LibriVox e aggiungilo a una libreria. La tua Bridge lo scarica, lo sistema e lo abbina alla sua registrazione.", diff --git a/admin-ui/src/i18n/locales/pt.json b/admin-ui/src/i18n/locales/pt.json index 9bcdc655..f3078599 100644 --- a/admin-ui/src/i18n/locales/pt.json +++ b/admin-ui/src/i18n/locales/pt.json @@ -4255,6 +4255,8 @@ "errors.invalidDestPath": "Isso não é um local dentro da biblioteca. Use pastas e um nome de ficheiro como Autor/Série/Título.m4b, sem pastas ocultas, barras invertidas nem \"..\".", "errors.invalidTemplate": "Esse modelo não funciona. Use as variáveis entre chavetas, como {Author}/{Series}/{Title}, e não ultrapasse os 500 caracteres.", "errors.invalid_template.account": "O modelo de localização desta conta já não funciona. Corrija-o em Definições da conta e volte a fazer a cópia.", + "errors.invalid_dest_path.indexed_book": "Esta pasta de disco está dentro de um livro já indexado. Escolha uma pasta separada para a cópia de segurança da Audible.", + "errors.invalid_dest_path.book_override": "A cópia de segurança da Audible usa uma pasta de disco que esta definição juntaria a outros discos num só livro. Escolha uma pasta separada para a cópia de segurança.", "errors.invalid_dest_path.title": "O destino deste título já não é válido. Defina-o de novo em Destino e volte a fazer a cópia.", "librivox.title": "LibriVox", "librivox.description": "Encontre um audiolivro gratuito em domínio público no LibriVox e adicione-o a uma biblioteca. A Bridge o baixa, o coloca no lugar e o associa à gravação.", diff --git a/admin-ui/src/lib/errors.test.ts b/admin-ui/src/lib/errors.test.ts index 36a38b81..309b9d8e 100644 --- a/admin-ui/src/lib/errors.test.ts +++ b/admin-ui/src/lib/errors.test.ts @@ -136,6 +136,12 @@ describe('errorMessage', () => { expect(errorMessage(stored('invalid_dest_path', 'title'), t)).toBe( "This title's destination is no longer valid. Set it again with Destination and back up again.", ); + expect(errorMessage(stored('invalid_dest_path', 'indexed_book'), t)).toMatch( + /inside an indexed book/, + ); + expect(errorMessage(stored('invalid_dest_path', 'book_override'), t)).toMatch( + /folder setting would join/, + ); // The value just typed (the account and title PATCHes): no reason. expect(errorMessage(stored('invalid_template'), t)).toMatch(/^That template doesn't work/); }); diff --git a/internal/api/audible_import_test.go b/internal/api/audible_import_test.go index a831bf6d..f8fe9d43 100644 --- a/internal/api/audible_import_test.go +++ b/internal/api/audible_import_test.go @@ -2,15 +2,19 @@ package api import ( "context" + "errors" "fmt" "net/http" "net/url" "strings" "testing" + "time" + "github.com/kodestar/audiosilo-server/internal/audible" "github.com/kodestar/audiosilo-server/internal/auth" "github.com/kodestar/audiosilo-server/internal/bridge" "github.com/kodestar/audiosilo-server/internal/catalog" + "github.com/kodestar/audiosilo-server/internal/modules" ) // Bridge Phase 4b: backing up Audible titles (audible.import). @@ -263,8 +267,13 @@ func TestAudibleDestPathRefusesDiscFolderOfABook(t *testing.T) { t.Fatal(err) } for _, dest := range []string{mistbornBook + "/CD 3", mistbornBook + "/Disc2/One.m4b", cradleBook + "/cd1", "Lone/Saga/CD 2", "Lone/Saga/CD 1/One.m4b"} { - if code, out := patch(dest); code != http.StatusBadRequest || codeOf(out) != "invalid_dest_path" { - t.Errorf("dest %q: %d %s, want 400 invalid_dest_path", dest, code, out) + reason, message := "indexed_book", "inside an indexed book" + if strings.HasPrefix(dest, "Lone/") { + reason, message = "book_override", "one-book folder setting" + } + if code, out := patch(dest); code != http.StatusBadRequest || codeOf(out) != "invalid_dest_path" || + reasonOf(out) != reason || !strings.Contains(out, message) { + t.Errorf("dest %q: %d %s, want 400 invalid_dest_path, %s", dest, code, out, reason) } if x := b.audibleTitle(t, "B000000001"); x.DestPath != "" { t.Fatalf("a refused destination was stored: %q", x.DestPath) @@ -277,6 +286,95 @@ func TestAudibleDestPathRefusesDiscFolderOfABook(t *testing.T) { } } +// F1: CD1 is still its own indexed book when the destination is saved. +func TestAudibleDestinationBeforeBookOverride(t *testing.T) { + t.Parallel() + b := backupEnv(t, title("B000000001", "One", "available", 0, "")) + ctx := t.Context() + const parent = "Other Tapes" + if _, err := b.cat.UpsertBook(ctx, &catalog.Book{LibraryID: b.lib.ID, RelPath: parent + "/CD1", Title: "Unrelated tape", IsFolder: true}); err != nil { + t.Fatal(err) + } + setDest := func(dest string) { + t.Helper() + resp, out := b.do(t, "PATCH", "/api/v1/admin/audible/titles/"+testAccount+"/B000000001", b.adminTok, fmt.Sprintf(`{"dest_path":%q}`, dest)) + if resp.StatusCode != http.StatusOK { + t.Fatalf("set destination %q: %d %s", dest, resp.StatusCode, out) + } + } + override := fmt.Sprintf("/api/v1/admin/libraries/%d/folder-override?path=%s", b.lib.ID, url.QueryEscape(parent)) + refused := func() { + t.Helper() + resp, out := b.do(t, "PUT", override, b.adminTok, `{"mode":"book"}`) + if resp.StatusCode != http.StatusBadRequest || codeOf(out) != "invalid_dest_path" || reasonOf(out) != "book_override" { + t.Fatalf("book override: %d %s", resp.StatusCode, out) + } + if modes, err := b.cat.FolderOverrides(ctx, b.lib.ID); err != nil || modes[parent] == catalog.OverrideBook { + t.Fatalf("override after refusal: %v, %v", modes, err) + } + } + setDest(parent + "/CD2") + refused() + // A job snapshots the old destination. Changing the title while it waits + // still cannot allow a conflicting override for that running backup. + resp, out := b.do(t, "POST", "/api/v1/admin/audible/titles/"+testAccount+"/B000000001/backup", b.adminTok, "") + if resp.StatusCode != http.StatusAccepted { + t.Fatalf("queue backup: %d %s", resp.StatusCode, out) + } + setDest("Own folder") + refused() + var queued struct { + ID int64 `json:"job_id"` + } + decodeInto(t, out, &queued) + if _, err := b.api.bridge.Cancel(ctx, queued.ID); err != nil { + t.Fatal(err) + } + if resp, out := b.do(t, "PUT", override, b.adminTok, `{"mode":"book"}`); resp.StatusCode != http.StatusOK { + t.Fatalf("override after changing destination and cancelling job: %d %s", resp.StatusCode, out) + } +} + +// An account carries its destinations when mapped to a different library. +func TestAudibleDiscDestinationOnRemapAndTemplate(t *testing.T) { + t.Parallel() + b := backupEnv(t, title("B000000001", "One", "available", 0, "")) + lib, err := b.cat.CreateLibrary(t.Context(), catalog.Library{Name: "Second", Root: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + if err := b.cat.SetFolderOverride(t.Context(), lib.ID, "Tapes", catalog.OverrideBook); err != nil { + t.Fatal(err) + } + titleURL := "/api/v1/admin/audible/titles/" + testAccount + "/B000000001" + if resp, out := b.do(t, "PATCH", titleURL, b.adminTok, `{"dest_path":"Tapes/CD2/One.m4b"}`); resp.StatusCode != http.StatusOK { + t.Fatalf("destination in original library: %d %s", resp.StatusCode, out) + } + if code, out := b.putAccount(t, testAccount, b.adminID, lib.ID); code != http.StatusBadRequest || reasonOf(out) != "book_override" { + t.Fatalf("remap: %d %s", code, out) + } + acct, err := b.cat.AudibleAccount(t.Context(), testAccount) + if err != nil || *acct.LibraryID != b.lib.ID { + t.Fatalf("mapping after refusal: %+v, %v", acct, err) + } + if resp, out := b.do(t, "PATCH", titleURL, b.adminTok, `{"dest_path":""}`); resp.StatusCode != http.StatusOK { + t.Fatal(out) + } + if code, out := b.putAccount(t, testAccount, b.adminID, lib.ID); code != http.StatusOK { + t.Fatalf("remap after clearing destination: %d %s", code, out) + } + accountURL := "/api/v1/admin/audible/accounts/" + testAccount + if resp, out := b.do(t, "PATCH", accountURL, b.adminTok, `{"template":"Tapes/CD2/{OriginalFilename}"}`); resp.StatusCode != http.StatusBadRequest || reasonOf(out) != "book_override" { + t.Fatalf("conflicting template: %d %s", resp.StatusCode, out) + } + if resp, out := b.do(t, "PATCH", accountURL, b.adminTok, `{"template":"Backups/CD2/{Title}.m4b"}`); resp.StatusCode != http.StatusOK { + t.Fatalf("separate template: %d %s", resp.StatusCode, out) + } + if err := b.cat.SetFolderOverride(t.Context(), lib.ID, "Backups", catalog.OverrideBook); !errors.Is(err, catalog.ErrAudibleBookOverride) { + t.Fatalf("override after template: %v", err) + } +} + // Deleting a person cancels the open jobs of the Audible accounts the // deletion took with them (bridge#46): a queued backup and a backup the Bridge // is running (asked to stop), with the account's reason. Denied: another @@ -303,7 +401,13 @@ func TestAudibleDeletePersonCancelsTheirJobs(t *testing.T) { } return queued.JobID } - for account, user := range map[string]int64{"acct0002": alex, "acct0003": alex, "acct0004": blair} { + member, _ := newUserWithSession(t, b.testEnv, "member", false) + for _, id := range []int64{member, blair} { + if _, err := b.db.ExecContext(ctx, `UPDATE users SET managed_by=?, member_kind='grownup', member_access='all' WHERE id=?`, alex, id); err != nil { + t.Fatal(err) + } + } + for account, user := range map[string]int64{"acct0002": alex, "acct0003": alex, "acct0004": blair, "acct0005": member, "acct0006": blair} { if code, out := b.putAccount(t, account, user, b.lib.ID); code != http.StatusOK { t.Fatalf("put %s: %d %s", account, code, out) } @@ -313,7 +417,19 @@ func TestAudibleDeletePersonCancelsTheirJobs(t *testing.T) { t.Fatalf("claimed %d, want %d", j.ID, running) } queued, others, admins := backup("acct0003"), backup("acct0004"), backup(testAccount) - if resp, out := b.do(t, "DELETE", fmt.Sprintf("/api/v1/admin/users/%d", alex), b.adminTok, ""); resp.StatusCode != http.StatusNoContent { + // The queued backup still belongs to Alex after an account changes libraries. + remap, err := b.cat.CreateLibrary(ctx, catalog.Library{Name: "Remapped", Root: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + if code, out := b.putAccount(t, "acct0003", alex, remap.ID); code != http.StatusOK { + t.Fatalf("remap queued backup: %d %s", code, out) + } + members, orphan := backup("acct0005"), backup("acct0006") + if _, err := b.db.ExecContext(ctx, `DELETE FROM audible_accounts WHERE account = 'acct0006'`); err != nil { + t.Fatal(err) + } + if resp, out := b.do(t, "DELETE", fmt.Sprintf("/api/v1/admin/users/%d?keep_members=%d", alex, blair), b.adminTok, ""); resp.StatusCode != http.StatusNoContent { t.Fatalf("delete alex: %d %s", resp.StatusCode, out) } job := func(id int64) *bridge.Job { @@ -330,11 +446,27 @@ func TestAudibleDeletePersonCancelsTheirJobs(t *testing.T) { if j := job(running); j.State != bridge.StateClaimed || !j.CancelRequested || j.Error != bridge.CancelAudibleRemoved { t.Errorf("alex's running backup: %s cancel %t %q, want asked to stop", j.State, j.CancelRequested, j.Error) } - for name, id := range map[string]int64{"blair's": others, "the admin's": admins} { + if j := job(members); j.State != bridge.StateCancelled { + t.Errorf("deleted member's job stayed %s", j.State) + } + for name, id := range map[string]int64{"kept member's": others, "the admin's": admins, "unrelated orphan's": orphan} { if j := job(id); j.State != bridge.StateQueued || j.CancelRequested { t.Errorf("%s backup: %s cancel %t, want queued", name, j.State, j.CancelRequested) } } + // The scheduler recovers the unrelated orphan even with the Bridge offline. + if _, err := b.db.ExecContext(ctx, `UPDATE bridge_status SET heartbeat_at = NULL`); err != nil { + t.Fatal(err) + } + if err := audible.SchedulerTick(ctx, modules.Deps{Catalog: b.cat, Bridge: b.api.bridge}, time.Now()); err != nil { + t.Fatal(err) + } + if j := job(orphan); j.State != bridge.StateCancelled || j.Error != bridge.CancelAudibleRemoved { + t.Fatalf("orphan after scheduler pass: %+v", j) + } + if j := job(others); j.State != bridge.StateQueued { + t.Fatalf("kept member's backup after scheduler pass: %s", j.State) + } // Again: nothing left to cancel. if n, err := b.cat.CancelOrphanAudibleJobs(ctx); n != 0 || err != nil { t.Fatalf("a second sweep found %d accounts, %v", n, err) diff --git a/internal/api/handlers_admin.go b/internal/api/handlers_admin.go index 0e9d188a..64c15f5c 100644 --- a/internal/api/handlers_admin.go +++ b/internal/api/handlers_admin.go @@ -442,13 +442,7 @@ func (a *API) handleDeleteUser(w http.ResponseWriter, r *http.Request) { a.writeUserError(w, err, "could not delete user") return } - // Their Audible accounts went with them (and their deleted members'): end - // those accounts' open jobs too (bridge#46). The person is deleted - // whatever this says; a failure leaves the jobs to fail at the Bridge - // (unknown_account). Committed, it runs even if the console hung up. - if _, err := a.cat.CancelOrphanAudibleJobs(context.WithoutCancel(r.Context())); err != nil { - a.log.Warn("cancel a deleted person's audible jobs failed", "user", id, "err", err) - } + a.cancelRemovedAudibleJobs(r, done.AudibleAccounts) // The household facts only for someone who had members (no "0 deleted, // none kept" on every other deletion). var details map[string]any diff --git a/internal/api/handlers_audible.go b/internal/api/handlers_audible.go index 312044c5..6e65e53a 100644 --- a/internal/api/handlers_audible.go +++ b/internal/api/handlers_audible.go @@ -71,6 +71,15 @@ func positiveLimit(w http.ResponseWriter, r *http.Request) (int, bool) { return n, true } +// The deletion already committed. A later scheduler pass retries a failed +// cancellation, including one interrupted by a server restart (while the +// Audible module is on; off, its jobs are held, and its first pass sweeps). +func (a *API) cancelRemovedAudibleJobs(r *http.Request, accounts []string) { + if _, err := a.cat.CancelRemovedAudibleJobs(context.WithoutCancel(r.Context()), accounts); err != nil { + a.log.Warn("cancel a deleted person's audible jobs failed", "accounts", accounts, "err", err) + } +} + // writeAudibleError answers an Audible catalog error. func (a *API) writeAudibleError(w http.ResponseWriter, err error, op string) { switch { @@ -90,8 +99,6 @@ func (a *API) writeAudibleError(w http.ResponseWriter, err error, op string) { writeErrorCode(w, http.StatusNotFound, "unknown_account", "no such Audible account") case errors.Is(err, catalog.ErrUnknownTitle): writeErrorCode(w, http.StatusNotFound, "unknown_title", "no such Audible title") - case errors.Is(err, bridge.ErrAudibleDestPath): - writeErrorCode(w, http.StatusBadRequest, "invalid_dest_path", err.Error()) case errors.Is(err, bridge.ErrAudibleTemplate): writeErrorCode(w, http.StatusBadRequest, "invalid_template", err.Error()) case errors.Is(err, catalog.ErrASINSet): @@ -103,7 +110,9 @@ func (a *API) writeAudibleError(w http.ResponseWriter, err error, op string) { // handleBridgeAudibleAccount serves PUT /bridge/audible/accounts/{account}: // the Bridge's mapping of an account it signed in to (a user, a books library, -// a policy). 200 {"account": {...}}. +// a policy). 200 {"account": {...}}; 400 invalid_dest_path (reason +// indexed_book or book_override) when a new library would put a saved title +// destination or the template's disc folder into another book there. func (a *API) handleBridgeAudibleAccount(w http.ResponseWriter, r *http.Request) { id, ok := audibleAccountID(w, r) if !ok { @@ -704,7 +713,9 @@ func (a *API) handleAdminAudibleTitle(w http.ResponseWriter, r *http.Request) { // {"policy"?, "template"?, "sync"?}: what the account backs up by itself and // where, and whether its places sync with Audible (Phase 4c; off cancels its // open sync). 200 -// the account; 400 invalid_policy, invalid_template; 404 unknown_account. +// the account; 400 invalid_policy, invalid_template, invalid_dest_path (a +// template placing in a disc folder of an indexed book, reason indexed_book, +// or of a one-book folder, book_override); 404 unknown_account. func (a *API) handleAdminAudibleAccount(w http.ResponseWriter, r *http.Request) { id, ok := audibleAccountID(w, r) if !ok { diff --git a/internal/api/handlers_members.go b/internal/api/handlers_members.go index 7c7c00d5..c12d4af8 100644 --- a/internal/api/handlers_members.go +++ b/internal/api/handlers_members.go @@ -498,11 +498,7 @@ func (a *API) handleDeleteMember(w http.ResponseWriter, r *http.Request) { a.writeMemberError(w, err, "delete member failed", "could not delete the member", "member", id) return } - // The member is deleted whatever this says; a failure leaves the jobs to - // fail at the Bridge (unknown_account), as on handleDeleteUser. - if _, err := a.cat.CancelOrphanAudibleJobs(context.WithoutCancel(r.Context())); err != nil { - a.log.Warn("cancel a deleted member's audible jobs failed", "member", id, "err", err) - } + a.cancelRemovedAudibleJobs(r, m.AudibleAccounts) a.audit(r, "member.delete", m.Username, map[string]any{"member": m.Username}) w.WriteHeader(http.StatusNoContent) } diff --git a/internal/api/respond.go b/internal/api/respond.go index 3449df70..befe4f45 100644 --- a/internal/api/respond.go +++ b/internal/api/respond.go @@ -13,6 +13,7 @@ import ( "time" "github.com/kodestar/audiosilo-server/internal/auth" + "github.com/kodestar/audiosilo-server/internal/bridge" "github.com/kodestar/audiosilo-server/internal/catalog" "github.com/kodestar/audiosilo-server/internal/config" "github.com/kodestar/audiosilo-server/internal/library" @@ -287,6 +288,12 @@ func (a *API) writeCatalogError(w http.ResponseWriter, err error, op, genericMsg // Its own code (bridge#50), so a client reads again from the start for // this alone: the Bridge's progress feed, books and titles cursors. writeErrorCode(w, http.StatusBadRequest, codeInvalidCursor, "invalid cursor") + case errors.Is(err, catalog.ErrAudibleIndexedBook): + writeErrorReason(w, http.StatusBadRequest, "invalid_dest_path", "indexed_book", err.Error()) + case errors.Is(err, catalog.ErrAudibleBookOverride): + writeErrorReason(w, http.StatusBadRequest, "invalid_dest_path", "book_override", err.Error()) + case errors.Is(err, bridge.ErrAudibleDestPath): + writeErrorCode(w, http.StatusBadRequest, "invalid_dest_path", err.Error()) case errors.Is(err, catalog.ErrInvalidOverrideMode): writeError(w, http.StatusBadRequest, `mode must be "book" or "collection"`) case errors.Is(err, catalog.ErrInvalidSetupStep): diff --git a/internal/audible/scheduler.go b/internal/audible/scheduler.go index f709bd49..1709fe31 100644 --- a/internal/audible/scheduler.go +++ b/internal/audible/scheduler.go @@ -44,7 +44,8 @@ func RunScheduler(ctx context.Context, d modules.Deps) { } } -// SchedulerTick is one pass at now: when an online Bridge runs audible.poll, +// SchedulerTick first cancels orphan jobs, even with the Bridge offline. +// When an online Bridge runs audible.poll, // each due account's poll is queued (and when it runs audible.sync, each due // account's sync: queueSyncs) (catalog.DueAudiblePolls: mapped to a // library and not queued within its poll_hours), deduped per account by the @@ -52,14 +53,12 @@ func RunScheduler(ctx context.Context, d modules.Deps) { // recorded. With no Bridge online, or one without Audible, nothing is queued: // the polls fall due again once it is back. func SchedulerTick(ctx context.Context, d modules.Deps, now time.Time) error { + _, sweepErr := d.Catalog.CancelOrphanAudibleJobs(ctx) h, err := d.Bridge.Online(ctx) - if err != nil { - return err + if err != nil || h == nil { + return errors.Join(sweepErr, err) } - if h == nil { - return nil - } - var errs []error + errs := []error{sweepErr} if h.Offers(bridge.KindAudiblePoll) { errs = append(errs, queuePolls(ctx, d, now)) } diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 4161f788..9888934b 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -1681,6 +1681,10 @@ func (s *Service) deleteUser(ctx context.Context, id int64, keep, del []int64, l return err } } + out.AudibleAccounts, err = deletedAudibleAccounts(ctx, tx, id) + if err != nil { + return err + } res, err := tx.ExecContext(ctx, `DELETE FROM users WHERE managed_by = ?`, id) if err != nil { return err @@ -1756,11 +1760,33 @@ func (s *Service) keepMembers(ctx context.Context, tx *sql.Tx, owner int64, list return kept, rows.Err() } -// DeletedUser is what DeleteUser did with the person's household members: how -// many it deleted and the usernames of those it kept ([] for none). +// deletedAudibleAccounts captures the account ids before their owners' rows +// cascade. Kept members have already been detached. The job queue uses these +// ids after commit, even when the account was mapped to another library. +func deletedAudibleAccounts(ctx context.Context, tx *sql.Tx, id int64) ([]string, error) { + rows, err := tx.QueryContext(ctx, `SELECT account FROM audible_accounts + WHERE user_id IN (SELECT ?1 UNION ALL SELECT id FROM users WHERE managed_by = ?1)`, id) + if err != nil { + return nil, err + } + defer rows.Close() + var accounts []string + for rows.Next() { + var account string + if err := rows.Scan(&account); err != nil { + return nil, err + } + accounts = append(accounts, account) + } + return accounts, rows.Err() +} + +// DeletedUser lists the Audible accounts that cascaded, the number of members +// deleted and the usernames of those kept ([] for none). type DeletedUser struct { - MembersDeleted int - MembersKept []string + AudibleAccounts []string + MembersDeleted int + MembersKept []string } // SetPassword sets (or clears) an account's password. A non-empty password is diff --git a/internal/auth/members.go b/internal/auth/members.go index 327c1e8f..38d2e085 100644 --- a/internal/auth/members.go +++ b/internal/auth/members.go @@ -837,13 +837,23 @@ func leaveOwners(ctx context.Context, tx *sql.Tx, id, newOwner int64) error { return err } +// DeletedMember identifies the member removed and the Audible accounts that +// went with them. +type DeletedMember struct { + Member + AudibleAccounts []string +} + // DeleteMember deletes owner's member id and all of its state (the schema's // cascade, as DeleteUser), returning the member as it was. -func (s *Service) DeleteMember(ctx context.Context, owner, id int64) (Member, error) { - var m Member +func (s *Service) DeleteMember(ctx context.Context, owner, id int64) (DeletedMember, error) { + var m DeletedMember err := s.db.WithDurableTx(ctx, "DeleteMember", func(tx *sql.Tx) error { var err error - if m, err = s.memberOf(ctx, tx, owner, id); err != nil { + if m.Member, err = s.memberOf(ctx, tx, owner, id); err != nil { + return err + } + if m.AudibleAccounts, err = deletedAudibleAccounts(ctx, tx, id); err != nil { return err } _, err = tx.ExecContext(ctx, `DELETE FROM users WHERE id = ?`, id) diff --git a/internal/bridge/audible.go b/internal/bridge/audible.go index 33140084..6d498e90 100644 --- a/internal/bridge/audible.go +++ b/internal/bridge/audible.go @@ -79,16 +79,16 @@ func AudiblePoll(account, template string, priority int) NewJob { return NewJob{Kind: KindAudiblePoll, Params: raw, Priority: priority} } -// pruneAudibleEnded keeps only the newest ended poll (or sync, kind) of the -// account a new one is queued for (its dedupe key), inside Enqueue's +// pruneAudibleEnded keeps only the newest ended job of j's kind (a poll or a +// sync) for the account a new one is queued for (its dedupe key), inside Enqueue's // transaction: a poll every few hours, or a sync every 15 minutes, would // otherwise pile up in the job list. -func pruneAudibleEnded(ctx context.Context, tx *sql.Tx, kind, key string) error { +func pruneAudibleEnded(ctx context.Context, tx *sql.Tx, j NewJob, key string) error { // The kind lets idx_bridge_jobs_kind_finished serve both scans (the // dedupe_key index holds only open jobs). _, err := tx.ExecContext(ctx, `DELETE FROM bridge_jobs WHERE kind = ?2 AND dedupe_key = ?1 AND state IN `+EndedStatesSQL+` AND id <> (SELECT MAX(id) FROM bridge_jobs WHERE kind = ?2 AND dedupe_key = ?1 AND state IN `+EndedStatesSQL+`)`, - key, kind) + key, j.Kind) return err } @@ -115,8 +115,13 @@ func CancelAudiblePolls(ctx context.Context, tx *sql.Tx, account, reason string, // account was removed: CancelAudibleRemoved), as CancelAudiblePolls does its // poll: at once when queued or parked, else at the Bridge's next report. func CancelAudibleImports(ctx context.Context, tx *sql.Tx, account, reason string, now time.Time) error { - keys, err := queryColumn[string](ctx, tx, `SELECT dedupe_key FROM bridge_jobs WHERE kind = ? AND state IN `+OpenStatesSQL+` - AND `+ParamSQL("params", "$.account")+` = ?`, KindAudibleImport, account) + // A backup keeps the library it was queued in even if the account is + // remapped. Seek its open key prefix in each library: the kind, the + // library, the empty path, then the account. '}' immediately follows the + // '|' between the account id and the ASIN in the key. + part := "|" + audibleImportAccountKey(account) + keys, err := queryColumn[string](ctx, tx, openAudibleImportsSQL, + KindAudibleImport+"|", part, strings.TrimSuffix(part, "|")+"}", account) if err != nil { return err } @@ -128,6 +133,10 @@ func CancelAudibleImports(ctx context.Context, tx *sql.Tx, account, reason strin return nil } +var openAudibleImportsSQL = `SELECT j.dedupe_key FROM libraries l CROSS JOIN bridge_jobs j INDEXED BY idx_bridge_jobs_open + WHERE j.state IN ` + OpenStatesSQL + ` AND j.dedupe_key >= (?1 || l.id || ?2) AND j.dedupe_key < (?1 || l.id || ?3) + AND ` + ParamSQL("j.params", "$.account") + ` = ?4` + // CleanText is v as printable bounded text on one line (cleanText): what the // Bridge reports from the outside world (an Audible title, its authors) is // cleaned rather than refused, so one odd title never fails a whole poll. @@ -370,7 +379,17 @@ func audibleImportParams(raw json.RawMessage) (json.RawMessage, error) { func audibleImportSuffix(j NewJob) string { var p AudibleImportParams _ = json.Unmarshal(j.Params, &p) - return "|" + p.Account + "|" + p.ASIN + return audibleImportAccountKey(p.Account) + p.ASIN +} + +// audibleImportAccountKey is the account's part of an audible.import key. +func audibleImportAccountKey(account string) string { return "|" + account + "|" } + +// AudibleImportKeyRange bounds the dedupe keys of library's audible.import +// jobs, for a seek on idx_bridge_jobs_open: lo <= key < hi. +func AudibleImportKeyRange(library int64) (lo, hi string) { + lo = DedupeKey(KindAudibleImport, &library, nil) + return lo, strings.TrimSuffix(lo, "|") + "}" } // AudibleImport is the NewJob that backs up p's title into p's library. diff --git a/internal/bridge/audible_import_test.go b/internal/bridge/audible_import_test.go index 200f7620..36501279 100644 --- a/internal/bridge/audible_import_test.go +++ b/internal/bridge/audible_import_test.go @@ -137,6 +137,35 @@ func TestAudibleImportJobs(t *testing.T) { } } +// Each library, including an account's previous mapping, gets a range seek +// for that account's open backups. A scan of the open index would visit other +// people's jobs on every delete. +func TestCancelAudibleImportsPlan(t *testing.T) { + t.Parallel() + q := newTestQueue(t) + rows, err := q.db.QueryContext(t.Context(), "EXPLAIN QUERY PLAN "+openAudibleImportsSQL, + KindAudibleImport+"|", "||acct0001|", "||acct0001}", "acct0001") + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var plan []string + for rows.Next() { + var id, parent, unused int + var detail string + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { + t.Fatal(err) + } + plan = append(plan, detail) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + if !strings.Contains(strings.Join(plan, "\n"), "idx_bridge_jobs_open (dedupe_key>? AND dedupe_key 0 || len(s.refusedWhileOpen) > 0 { + t.Errorf("batch kind %s prunes, promotes, cancels or refuses", kind) + } + } +} + func ptr[T any](v T) *T { return &v } // damageParams stores params that are not JSON on job id, as a damaged row has. diff --git a/internal/bridge/podcasts.go b/internal/bridge/podcasts.go index e9c94355..634bf5d3 100644 --- a/internal/bridge/podcasts.go +++ b/internal/bridge/podcasts.go @@ -55,7 +55,7 @@ func Internal(kind string) bool { return kinds[kind].internal } // podcastWork reports whether kind is one of a followed show's bound jobs // (poll, fetch, retain): params naming the show's identity, which an open job -// for a replaced identity must not absorb, and terminal rows pruned per target. +// for a replaced identity must not absorb. func podcastWork(kind string) bool { return kind == KindPodcastPoll || kind == KindPodcastFetch || kind == KindPodcastRetain } @@ -802,9 +802,9 @@ func (s *Service) checkLibraryKind(ctx context.Context, j NewJob) error { } } -// prunePolls keeps only the newest ended poll of a show (the dedupe key's -// kind, library and path, which idx_bridge_jobs_book serves). -func (s *Service) prunePolls(ctx context.Context, tx *sql.Tx, j NewJob) error { +// prunePolls keeps the newest ended job at this kind, library and path. For +// fetch and retain it also keeps older results until the server folds them. +func prunePolls(ctx context.Context, tx *sql.Tx, j NewJob, _ string) error { _, err := tx.ExecContext(ctx, `DELETE FROM bridge_jobs WHERE library_id=?1 AND rel_path=?2 AND kind=?3 AND state IN `+EndedStatesSQL+` AND (kind='podcast.poll' OR EXISTS(SELECT 1 FROM podcast_folded f WHERE f.job_id=bridge_jobs.id)) AND id<>(SELECT MAX(id) FROM bridge_jobs WHERE library_id=?1 AND rel_path=?2 AND kind=?3 AND state IN `+EndedStatesSQL+`)`, j.LibraryID, j.Path, j.Kind) return err diff --git a/internal/catalog/audible.go b/internal/catalog/audible.go index e14c02ef..d6ff532d 100644 --- a/internal/catalog/audible.go +++ b/internal/catalog/audible.go @@ -309,10 +309,17 @@ func (c *Catalog) PutAudibleAccount(ctx context.Context, id string, in AudibleAc return ErrNotBookLibrary } var was int64 - err = tx.QueryRowContext(ctx, `SELECT user_id FROM audible_accounts WHERE account = ?`, id).Scan(&was) + var oldLibrary sql.NullInt64 + var template string + err = tx.QueryRowContext(ctx, `SELECT user_id, library_id, template FROM audible_accounts WHERE account = ?`, id).Scan(&was, &oldLibrary, &template) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } + if err == nil && in.LibraryID != oldLibrary.Int64 { + if err := checkAudibleRemap(ctx, tx, id, in.LibraryID, template); err != nil { + return err + } + } remapped := err == nil && was != in.UserID now := c.ts() if _, err := tx.ExecContext(ctx, @@ -379,36 +386,46 @@ func cancelAudibleJobs(ctx context.Context, tx *sql.Tx, account string, now time return bridge.CancelAudibleSyncs(ctx, tx, account, bridge.CancelAudibleRemoved, now) } -// CancelOrphanAudibleJobs cancels the open Audible jobs (poll, backups, sync) -// of every account that is no longer there: deleting a person drops their -// accounts by the schema's cascade (auth.DeleteUser, which can't reach the job -// queue), and their jobs would otherwise stay open, a backup downloading for -// nobody. It returns how many accounts it found with a job not yet asked to -// stop; none is no change, so it is safe to call again. +// CancelOrphanAudibleJobs recovers open jobs left after their account went. +// Only the open-job index's audible.* key range is walked. The common empty pass needs no writer. func (c *Catalog) CancelOrphanAudibleJobs(ctx context.Context) (int, error) { - var gone []string - // A job whose params name no account (a damaged row reads as NULL) is - // passed by: NULL NOT IN an empty audible_accounts is true, and a NULL - // account would fail the scan, the whole sweep with it. accountSQL := bridge.ParamSQL("params", "$.account") - err := c.db.WithTx(ctx, "CancelOrphanAudibleJobs", func(tx *sql.Tx) error { - var err error - gone, err = queryRows(ctx, tx, func(rows *sql.Rows, account *string) error { return rows.Scan(account) }, - `SELECT DISTINCT `+accountSQL+` FROM bridge_jobs - WHERE kind IN (?, ?, ?) AND state IN `+bridge.OpenStatesSQL+` AND cancel_requested = 0 - AND `+accountSQL+` IS NOT NULL AND `+accountSQL+` NOT IN (SELECT account FROM audible_accounts)`, - bridge.KindAudiblePoll, bridge.KindAudibleImport, bridge.KindAudibleSync) - if err != nil { - return err - } + gone, err := queryRows(ctx, c.db, func(rows *sql.Rows, account *string) error { return rows.Scan(account) }, + `SELECT DISTINCT `+accountSQL+` FROM bridge_jobs INDEXED BY idx_bridge_jobs_open + WHERE dedupe_key >= 'audible.' AND dedupe_key < 'audible/' AND kind IN (?, ?, ?) AND state IN `+bridge.OpenStatesSQL+` AND cancel_requested = 0 + AND `+accountSQL+` IS NOT NULL AND `+accountSQL+` NOT IN (SELECT account FROM audible_accounts)`, + bridge.KindAudiblePoll, bridge.KindAudibleImport, bridge.KindAudibleSync) + if err != nil { + return 0, err + } + return c.CancelRemovedAudibleJobs(ctx, gone) +} + +// CancelRemovedAudibleJobs cancels jobs for the listed accounts that are still +// absent. A fresh mapping between a delete (or the scheduler read) and this +// transaction keeps its jobs. +func (c *Catalog) CancelRemovedAudibleJobs(ctx context.Context, gone []string) (int, error) { + if len(gone) == 0 { + return 0, nil + } + n := 0 + err := c.db.WithTx(ctx, "CancelRemovedAudibleJobs", func(tx *sql.Tx) error { for _, account := range gone { - if err := cancelAudibleJobs(ctx, tx, account, c.now()); err != nil { + // The Bridge may have mapped the account again since the read. + var exists bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM audible_accounts WHERE account = ?)`, account).Scan(&exists); err != nil { return err } + if !exists { + if err := cancelAudibleJobs(ctx, tx, account, c.now()); err != nil { + return err + } + n++ + } } return nil }) - return len(gone), err + return n, err } // AudibleAccount returns account id, ErrUnknownAccount when there is none. diff --git a/internal/catalog/audible_import.go b/internal/catalog/audible_import.go index cc2436bf..7b919aa1 100644 --- a/internal/catalog/audible_import.go +++ b/internal/catalog/audible_import.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "path" + "regexp" "slices" "strings" "time" @@ -197,8 +198,9 @@ type AudibleTitlePatch struct { // PatchAudibleTitle applies the console's change to a title and returns it: // ErrUnknownTitle for none, a bridge.ErrAudibleDestPath for a destination -// bridge.CheckAudibleDestPath refuses or one into a disc folder of an indexed -// book (checkDestOwnFolder). "Not this book" drops a pending +// bridge.CheckAudibleDestPath refuses, ErrAudibleIndexedBook or +// ErrAudibleBookOverride for one (or, cleared, the account's template) into a +// disc folder another book would absorb (checkDestOwnFolder). "Not this book" drops a pending // request: such a title is never backed up by a policy or "Back up // everything", and its match is not this title's (a backup may still be asked // for one by one). A user-state write. @@ -209,14 +211,16 @@ func (c *Catalog) PatchAudibleTitle(ctx context.Context, account, asin string, p } } err := c.db.WithUserStateTx(ctx, "PatchAudibleTitle", func(tx *sql.Tx) error { - var ok bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM audible_titles WHERE account = ? AND asin = ?)`, - account, asin).Scan(&ok); err != nil { - return err - } - if !ok { + var library int64 + var template string + err := tx.QueryRowContext(ctx, `SELECT COALESCE(a.library_id, 0), a.template FROM audible_titles t + JOIN audible_accounts a ON a.account = t.account WHERE t.account = ? AND t.asin = ?`, account, asin).Scan(&library, &template) + if errors.Is(err, sql.ErrNoRows) { return ErrUnknownTitle } + if err != nil { + return err + } now := c.ts() if p.Rejected != nil { if _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET rejected = ?1, @@ -226,7 +230,7 @@ func (c *Catalog) PatchAudibleTitle(ctx context.Context, account, asin string, p } } if p.DestPath != nil { - if err := checkDestOwnFolder(ctx, tx, account, *p.DestPath); err != nil { + if err := checkDestOwnFolder(ctx, tx, library, *p.DestPath, template); err != nil { return err } if _, err := tx.ExecContext(ctx, `UPDATE audible_titles SET dest_path = ?, updated_at = ? WHERE account = ? AND asin = ?`, @@ -248,39 +252,141 @@ func (c *Catalog) PatchAudibleTitle(ctx context.Context, account, asin string, p return c.AudibleTitle(ctx, account, asin) } -// checkDestOwnFolder refuses (a bridge.ErrAudibleDestPath) a destination whose -// folder is a disc folder (metadata.IsDiscFolder: "CD 3") directly inside a -// folder of account's library that is an indexed book, or that holds a `book` -// folder override (one disc there on its own, "Book/CD 1", is its own book -// until a second makes the disc set the override joins): the scan joins the -// disc into that book, so the backup's fold would refuse it (ErrImportNotOwn) -// only after the whole download and its placement in the other book's folder -// (bridge#46). Without an override, discs stay books of their own and the -// destination is allowed. The destination's folder is its last segment, or the -// one above a file name with an audio extension, as the Bridge reads it. A -// paused account (no library) has no book to check. -func checkDestOwnFolder(ctx context.Context, tx *sql.Tx, account, dest string) error { - folder := dest - if metadata.IsAudio(dest) { - folder = path.Dir(dest) - } - book := path.Dir(folder) - if dest == "" || book == "." || !metadata.IsDiscFolder(path.Base(folder)) { +// The parent of the disc destination is already indexed as a book, or the +// admin explicitly set it to join its discs. The former alone does not prove +// the next scan would join the backup. +var ( + ErrAudibleIndexedBook = fmt.Errorf("%w: the disc folder is inside an indexed book", bridge.ErrAudibleDestPath) + ErrAudibleBookOverride = fmt.Errorf("%w: the Audible disc destination conflicts with the one-book folder setting", bridge.ErrAudibleDestPath) +) + +// audibleDiscParent is the folder that could absorb the backup's disc, or "" +// when there is none. The Bridge renders templates. We can check a literal +// disc folder even if the file name uses a title variable. For a folder that +// depends on a variable, importOwnBook checks the actual placement. +func audibleDiscParent(dest, template string) string { + folder := strings.TrimSpace(dest) + fromTemplate := folder == "" + var templateFile bool + if fromTemplate { + folder = templateFolders(template) + m := templateFileEnd.FindStringSubmatchIndex(path.Base(folder)) + templateFile = m != nil && (m[0] > 0 || path.Base(folder)[m[2]:m[3]] == "OriginalFilename") + } + if templateFile || metadata.IsAudio(folder) { + folder = path.Dir(folder) + } + if !metadata.IsDiscFolder(path.Base(folder)) { + return "" + } + parent := path.Dir(folder) + // A brace or escape is a variable, a group or an escaped character, so + // the folder the Bridge renders can't be read from the template. + if parent == "." || (fromTemplate && strings.ContainsAny(parent, "{}\\")) { + return "" + } + return parent +} + +// templateFileEnd is a template's last segment the Bridge renders as the +// file's name: one ending in {OriginalFilename} or {Ext} (modifiers allowed), +// whose extension is the backup's. {Ext} alone is a folder (".m4b" sanitized +// to "m4b"). +var templateFileEnd = regexp.MustCompile(`\{(OriginalFilename|Ext)(?::[^{}]*)?\}$`) + +// templateFolders is template's segments as the Bridge's placement.Render +// leaves its literal ones (its sanitize: white space trimmed, a colon made +// " -", leading and trailing spaces and dots trimmed) with the empty ones +// dropped, so "Audible/CD 1/" places in Audible/CD 1, a disc of Audible. A +// segment with a token keeps its colons (a modifier's). +func templateFolders(template string) string { + var segs []string + for seg := range strings.SplitSeq(template, "/") { + if seg = strings.TrimSpace(seg); !strings.ContainsAny(seg, "{}\\") { + seg = strings.ReplaceAll(seg, ":", " -") + } + if seg = strings.Trim(seg, " ."); seg != "" { + segs = append(segs, seg) + } + } + return strings.Join(segs, "/") +} + +// checkDestOwnFolder refuses, through tx, a destination (or, dest empty, the +// template) whose disc folder library already joins into another book: its +// parent holds a `book` override (ErrAudibleBookOverride) or is an indexed +// book (ErrAudibleIndexedBook). A paused account (library 0) has none. +func checkDestOwnFolder(ctx context.Context, tx *sql.Tx, library int64, dest, template string) error { + book := audibleDiscParent(dest, template) + if book == "" || library == 0 { return nil } - var joins bool - err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM audible_accounts a JOIN books b ON b.library_id = a.library_id - WHERE a.account = ?1 AND b.rel_path = ?2) OR EXISTS(SELECT 1 FROM audible_accounts a JOIN folder_overrides o ON o.library_id = a.library_id - WHERE a.account = ?1 AND o.path = ?2 AND o.mode = ?3)`, account, book, OverrideBook).Scan(&joins) - if err != nil { + var override, indexed bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM folder_overrides WHERE library_id = ?1 AND path = ?2 AND mode = ?3), + EXISTS(SELECT 1 FROM books WHERE library_id = ?1 AND rel_path = ?2)`, library, book, OverrideBook).Scan(&override, &indexed) + switch { + case err != nil: return err - } - if joins { - return fmt.Errorf("%w: %s is a disc folder of the book %s, which the backup would join; pick a folder of its own", bridge.ErrAudibleDestPath, folder, book) + case override: + return discConflict(ErrAudibleBookOverride, book) + case indexed: + return discConflict(ErrAudibleIndexedBook, book) } return nil } +// discConflict is the refusal naming the folder that would absorb the disc. +func discConflict(sentinel error, book string) error { + return fmt.Errorf("%w (%s). Choose a separate folder for the backup", sentinel, book) +} + +// checkAudibleRemap checks the saved destinations in the library the Bridge +// proposes for this account, including when a paused account resumes. A title +// already on this server (matched, not marked "Not this book") is never backed +// up again, so its destination, where an earlier backup may sit in the old +// library, refuses nothing in the new one. +func checkAudibleRemap(ctx context.Context, tx *sql.Tx, account string, library int64, template string) error { + if err := checkDestOwnFolder(ctx, tx, library, "", template); err != nil { + return err + } + // checkDestOwnFolder's rule over every saved destination in one statement. + var book string + var override bool + err := tx.QueryRowContext(ctx, `SELECT p, EXISTS(SELECT 1 FROM folder_overrides WHERE library_id = ?2 AND path = p AND mode = ?3) AS o + FROM (SELECT DISTINCT audible_disc_parent(dest_path, '') AS p FROM audible_titles + WHERE account = ?1 AND dest_path <> '' AND (match_path IS NULL OR rejected = 1)) + WHERE p <> '' AND (o OR EXISTS(SELECT 1 FROM books WHERE library_id = ?2 AND rel_path = p)) + ORDER BY o DESC LIMIT 1`, account, library, OverrideBook).Scan(&book, &override) + switch { + case errors.Is(err, sql.ErrNoRows): + return nil + case err != nil: + return err + case override: + return discConflict(ErrAudibleBookOverride, book) + } + return discConflict(ErrAudibleIndexedBook, book) +} + +// checkAudibleOverride checks the other order of edits. Open backups keep +// their original placement if the account is remapped or the title is edited. +func checkAudibleOverride(ctx context.Context, tx *sql.Tx, library int64, book string) error { + lo, hi := bridge.AudibleImportKeyRange(library) + var conflict bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM audible_accounts WHERE library_id = ?1 AND template <> '' AND audible_disc_parent('', template) = ?2 + UNION ALL SELECT 1 FROM audible_accounts a JOIN audible_titles t ON t.account = a.account + WHERE a.library_id = ?1 AND t.dest_path <> '' AND audible_disc_parent(t.dest_path, '') = ?2 + UNION ALL SELECT 1 FROM bridge_jobs j INDEXED BY idx_bridge_jobs_open WHERE j.dedupe_key >= ?3 AND j.dedupe_key < ?4 + AND j.state IN `+bridge.OpenStatesSQL+` + AND audible_disc_parent(`+bridge.ParamSQL("j.params", "$.dest_path")+`, `+bridge.ParamSQL("j.params", "$.template")+`) = ?2)`, + library, book, lo, hi).Scan(&conflict) + if err == nil && conflict { + return discConflict(ErrAudibleBookOverride, book) + } + return err +} + // AudibleAccountPatch is the console's change to an account: its policy, its // placement template and whether its places sync with Audible (Phase 4c). A // nil field is left as it is. @@ -292,7 +398,9 @@ type AudibleAccountPatch struct { // PatchAudibleAccount applies the console's change to account id and returns // it: ErrUnknownAccount for none, ErrAudiblePolicy for an unknown policy, a -// bridge.ErrAudibleTemplate for a template bridge.CheckAudibleTemplate refuses. +// bridge.ErrAudibleTemplate for a template bridge.CheckAudibleTemplate refuses, +// ErrAudibleIndexedBook or ErrAudibleBookOverride for one placing in a disc +// folder another book would absorb (checkDestOwnFolder). // A policy changed to an automatic one (all, series) starts acting now // (policy_since): only titles first seen after it are backed up by it. func (c *Catalog) PatchAudibleAccount(ctx context.Context, id string, p AudibleAccountPatch) (*AudibleAccount, error) { @@ -306,7 +414,8 @@ func (c *Catalog) PatchAudibleAccount(ctx context.Context, id string, p AudibleA } err := c.db.WithTx(ctx, "PatchAudibleAccount", func(tx *sql.Tx) error { var policy string - err := tx.QueryRowContext(ctx, `SELECT policy FROM audible_accounts WHERE account = ?`, id).Scan(&policy) + var library int64 + err := tx.QueryRowContext(ctx, `SELECT policy, COALESCE(library_id, 0) FROM audible_accounts WHERE account = ?`, id).Scan(&policy, &library) if errors.Is(err, sql.ErrNoRows) { return ErrUnknownAccount } @@ -322,6 +431,9 @@ func (c *Catalog) PatchAudibleAccount(ctx context.Context, id string, p AudibleA } } if p.Template != nil { + if err := checkDestOwnFolder(ctx, tx, library, "", *p.Template); err != nil { + return err + } if _, err := tx.ExecContext(ctx, `UPDATE audible_accounts SET template = ?, updated_at = ? WHERE account = ?`, *p.Template, now, id); err != nil { return err @@ -739,7 +851,7 @@ func (c *Catalog) FoldAudibleImport(ctx context.Context, j bridge.Job) error { // is indexed in a books library (else ErrImportNotIndexed) and is the title's // own (else ErrImportNotOwn): it carries the title's ASIN (the Bridge's // enrichment set it, or the book had it), or it holds only the files the -// backup placed (a book the backup made). A file the Bridge placed into a +// backup placed. A joined disc set must pass the file check even with the ASIN. 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. A refusal is a *foldRefusal. @@ -763,12 +875,19 @@ func importOwnBook(ctx context.Context, tx *sql.Tx, p bridge.AudibleImportParams return err case rejected: return &foldRefusal{AudibleFoldRejectedMatch, ErrImportNotOwn} - case strings.EqualFold(asin, p.ASIN): - return nil } + // A newly joined disc set can carry the ASIN the Bridge just wrote. + // In that case require the indexed files to belong to this backup. + joinedDisc := folder && audibleDiscParent(p.DestPath, p.Template) == r.Path placed := make(map[string]bool, len(r.Files)) for _, f := range r.Files { placed[f.Path] = true + if folder && audibleDiscParent(f.Path, "") == r.Path { + joinedDisc = true + } + } + if strings.EqualFold(asin, p.ASIN) && !joinedDisc { + return nil } files := []string{r.Path} // a single-file book is its file if folder { diff --git a/internal/catalog/audible_import_test.go b/internal/catalog/audible_import_test.go index 8b9e1cd6..1912e331 100644 --- a/internal/catalog/audible_import_test.go +++ b/internal/catalog/audible_import_test.go @@ -573,6 +573,26 @@ func TestFoldAudibleImportOwnBook(t *testing.T) { } return tt } + // A reclassified disc set may have just received the title's ASIN from the + // Bridge. Its other tape proves that the placed disc isn't the whole book. + const tapes = "Other Tapes" + const placed = tapes + "/CD2/One.m4b" + joined := &Book{LibraryID: lib, RelPath: tapes, Title: tapes, IsFolder: true, ASIN: "B000000004", + Files: []BookFile{{RelPath: tapes + "/CD1/Tape.m4b"}, {RelPath: placed, Seq: 1}}} + if _, err := f.c.UpsertBook(f.ctx, joined); err != nil { + t.Fatal(err) + } + discJob := done(4, "B000000004", tapes, placed) + if err := f.c.FoldAudibleImport(f.ctx, discJob); !errors.Is(err, ErrImportNotOwn) || match("B000000004").Match != nil { + t.Fatalf("disc joined another tape carrying the backup's ASIN: %v", err) + } + joined.Files = []BookFile{{RelPath: placed}} + if _, err := f.c.UpsertBook(f.ctx, joined); err != nil { + t.Fatal(err) + } + if err := f.c.FoldAudibleImport(f.ctx, discJob); err != nil { + t.Fatalf("disc set holds only the backup's own file: %v", err) + } // One's file joined Other's folder book: not One's. 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) @@ -967,15 +987,97 @@ func TestAudibleIgnoredAndNoSyncBackups(t *testing.T) { func TestCancelOrphanAudibleJobsPassesDamagedParams(t *testing.T) { t.Parallel() c, ctx := newTestCatalog(t) - for i, params := range []string{`{`, `{"account":"acct0009"}`} { + for key, params := range map[string]string{"audible.sync|||damaged1": `{`, "audible.sync|||acct0009": `{"account":"acct0009"}`} { if _, err := c.db.ExecContext(ctx, `INSERT INTO bridge_jobs(kind, params, dedupe_key, created_at, updated_at) - VALUES(?, ?, ?, 't', 't')`, bridge.KindAudibleSync, params, fmt.Sprintf("orphan%d", i)); err != nil { + VALUES(?, ?, ?, 't', 't')`, bridge.KindAudibleSync, params, key); err != nil { t.Fatal(err) } } if n, err := c.CancelOrphanAudibleJobs(ctx); err != nil || n != 1 { t.Fatalf("sweep = %d, %v; want the one orphaned account, no error", n, err) } + before, _ := c.ContentGeneration() + if n, err := c.CancelOrphanAudibleJobs(ctx); err != nil || n != 0 { + t.Fatalf("idle sweep = %d, %v", n, err) + } + if after, _ := c.ContentGeneration(); after != before { + t.Fatalf("idle sweep took the writer: generation %d became %d", before, after) + } +} + +// The folder a disc destination would join: a template's segments as the +// Bridge renders its literal ones (empty dropped, spaces and dots trimmed, a +// colon made " -"), and no guess where a variable or escape makes the parent. +func TestAudibleDiscParent(t *testing.T) { + t.Parallel() + for _, c := range []struct{ dest, template, want string }{ + {"Author/Book/CD 1", "", "Author/Book"}, + {"Author/Book/CD 1/One.m4b", "", "Author/Book"}, + {"Author/Book/One.m4b", "", ""}, + {"CD 1", "", ""}, + {"", "Audible/CD 1", "Audible"}, + {"", "Audible/CD 1/", "Audible"}, + {"", "Audible//CD 1/{Title}.m4b", "Audible"}, + {"", " Audible / CD 1 /{OriginalFilename}", "Audible"}, + {"", "Audible/CD 1/{Title}{Ext}", "Audible"}, + {"", "Audible/CD 1/{OriginalFilename:lower}", "Audible"}, + {"", "Audible/CD 1/{Title}{Ext:upper}", "Audible"}, + {"", "Audible/CD 1/{Ext}", ""}, + {"", "{Author}/CD 1", ""}, + {"", "Books: Audible/CD 1", "Books - Audible"}, + {"", "My Audible/CD 1", "My Audible"}, + {"", "Audible?/CD 1", "Audible?"}, + {"", "Audible/{Title}", ""}, + } { + if got := audibleDiscParent(c.dest, c.template); got != c.want { + t.Errorf("audibleDiscParent(%q, %q) = %q, want %q", c.dest, c.template, got, c.want) + } + } +} + +// A remap checks the destinations of the titles that may still be backed up: +// one already on this server isn't backed up again, so its saved disc folder +// (where its backup sits, in the old library) refuses nothing in the new one; +// marked "Not this book", it may be, and refuses. +func TestAudibleRemapSkipsMatchedTitles(t *testing.T) { + t.Parallel() + f := newAudibleFixture(t, "manual") + f.poll(t, "p1", avail("B000000001", "")) + dest := "Tapes/CD2" + if _, err := f.c.PatchAudibleTitle(f.ctx, "acct0001", "B000000001", AudibleTitlePatch{DestPath: &dest}); err != nil { + t.Fatal(err) + } + other, err := f.c.CreateLibrary(f.ctx, Library{Name: "Other", Root: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + if err := f.c.SetFolderOverride(f.ctx, other.ID, "Tapes", OverrideBook); err != nil { + t.Fatal(err) + } + mapTo := func(lib int64) error { + _, err := f.c.PutAudibleAccount(f.ctx, "acct0001", AudibleAccountInput{Label: "x", Marketplace: "us", + UserID: f.user, LibraryID: lib, Policy: "manual", Sync: true}) + return err + } + if err := mapTo(other.ID); !errors.Is(err, ErrAudibleBookOverride) { + t.Fatalf("unmatched title's disc destination: %v, want ErrAudibleBookOverride", err) + } + if _, err := f.c.db.ExecContext(f.ctx, `UPDATE audible_titles SET match_library_id = ?, match_path = ? WHERE asin = 'B000000001'`, + f.lib.ID, dest); err != nil { + t.Fatal(err) + } + if err := mapTo(other.ID); err != nil { + t.Fatalf("matched title's destination refused the remap: %v", err) + } + if err := mapTo(f.lib.ID); err != nil { + t.Fatal(err) + } + if _, err := f.c.db.ExecContext(f.ctx, `UPDATE audible_titles SET rejected = 1 WHERE asin = 'B000000001'`); err != nil { + t.Fatal(err) + } + if err := mapTo(other.ID); !errors.Is(err, ErrAudibleBookOverride) { + t.Fatalf("title marked Not this book: %v, want ErrAudibleBookOverride", err) + } } // can_backup is the console's Back up allowed: exactly the titles diff --git a/internal/catalog/folder_overrides.go b/internal/catalog/folder_overrides.go index 56f24380..258c0f90 100644 --- a/internal/catalog/folder_overrides.go +++ b/internal/catalog/folder_overrides.go @@ -2,6 +2,7 @@ package catalog import ( "context" + "database/sql" "errors" ) @@ -53,11 +54,19 @@ func (c *Catalog) SetFolderOverride(ctx context.Context, libraryID int64, path, if mode != OverrideBook && mode != OverrideCollection { return ErrInvalidOverrideMode } - _, err := c.db.ExecContext(ctx, - `INSERT INTO folder_overrides(library_id, path, mode, updated_at) VALUES(?,?,?,?) - ON CONFLICT(library_id, path) DO UPDATE SET mode = excluded.mode, updated_at = excluded.updated_at`, - libraryID, CleanRelPath(path), mode, c.ts()) - return err + path = CleanRelPath(path) + return c.db.WithTx(ctx, "SetFolderOverride", func(tx *sql.Tx) error { + if mode == OverrideBook && path != "" { + if err := checkAudibleOverride(ctx, tx, libraryID, path); err != nil { + return err + } + } + _, err := tx.ExecContext(ctx, + `INSERT INTO folder_overrides(library_id, path, mode, updated_at) VALUES(?,?,?,?) + ON CONFLICT(library_id, path) DO UPDATE SET mode = excluded.mode, updated_at = excluded.updated_at`, + libraryID, path, mode, c.ts()) + return err + }) } // DeleteFolderOverride removes a folder's override, reverting it to auto-detection. diff --git a/internal/catalog/sqlfuncs.go b/internal/catalog/sqlfuncs.go index a651bcb6..9e6821bd 100644 --- a/internal/catalog/sqlfuncs.go +++ b/internal/catalog/sqlfuncs.go @@ -45,6 +45,12 @@ func init() { } return int64(0), nil }) + // audible_disc_parent(dest_path, template): the folder an Audible backup's + // disc folder would join (audibleDiscParent), "" for none: the disc-folder + // checks over saved destinations, templates and open backups. + store.RegisterFunction("audible_disc_parent", 2, func(args []driver.Value) (driver.Value, error) { + return audibleDiscParent(sqlText(args[0]), sqlText(args[1])), nil + }) // audible_dest_ok(dest_path): whether an Audible title's stored destination // still validates (bridge.CheckAudibleDestPath, "" the automatic one), which // "Back up everything" skips a title for (backupAllQueuedSQL).