forked from vavallee/bindery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
1392 lines (1269 loc) · 45.5 KB
/
Copy pathclient.ts
File metadata and controls
1392 lines (1269 loc) · 45.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Path prefix injected by the backend at serve time (empty for root-mounted
// deploys). Read once at module load so all API calls and redirects use a
// consistent value throughout the session.
const BINDERY_BASE: string = (window as unknown as { __BINDERY_BASE__?: string }).__BINDERY_BASE__ ?? ''
const BASE = `${BINDERY_BASE}/api/v1`
// Pages that render before the user is authenticated — reaching /auth/status
// will 401 in enabled mode before setup, which is expected, and we must not
// try to redirect to /login from the login/setup pages themselves.
const PUBLIC_PATHS = new Set([`${BINDERY_BASE}/login`, `${BINDERY_BASE}/setup`])
// CSRF double-submit token, fetched once on init and refreshed after login.
let csrfToken = ''
// Read from the bindery_csrf cookie (set by GET /auth/csrf).
function readCSRFCookie(): string {
const m = document.cookie.match(/(?:^|;\s*)bindery_csrf=([^;]+)/)
return m ? decodeURIComponent(m[1]) : ''
}
export async function initCSRF(): Promise<void> {
try {
const res = await fetch(`${BASE}/auth/csrf`, {
credentials: 'include',
headers: { 'X-Requested-With': 'bindery-ui' },
})
if (res.ok) {
const data = await res.json()
csrfToken = data.csrfToken || readCSRFCookie()
}
} catch {
// Non-fatal — mutations will fail with 403 if still missing.
}
}
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
async function request<T>(path: string, options?: RequestInit): Promise<T> {
// Merge caller-supplied headers on top of the defaults so we can't lose
// the CSRF header if a caller passes their own `headers`.
const headers = new Headers({
'Content-Type': 'application/json',
'X-Requested-With': 'bindery-ui',
})
const method = (options?.method ?? 'GET').toUpperCase()
if (!SAFE_METHODS.has(method) && csrfToken) {
headers.set('X-CSRF-Token', csrfToken)
}
if (options?.headers) {
new Headers(options.headers).forEach((v, k) => headers.set(k, v))
}
const res = await fetch(`${BASE}${path}`, {
credentials: 'include', // send + accept the session cookie
...options,
headers,
})
if (res.status === 401 && !PUBLIC_PATHS.has(window.location.pathname)) {
// Session expired or missing — punt to login. The router there will
// bounce to /setup if no user exists yet.
window.location.href = `${BINDERY_BASE}/login`
throw new Error('unauthorized')
}
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || res.statusText)
}
if (res.status === 204) return undefined as unknown as T
return res.json()
}
// Upload a file (multipart/form-data). Omits Content-Type so the browser
// sets the boundary automatically, but still injects the CSRF token.
async function uploadFile<T>(path: string, body: FormData): Promise<T> {
const headers = new Headers({
'X-Requested-With': 'bindery-ui',
})
if (csrfToken) {
headers.set('X-CSRF-Token', csrfToken)
}
const res = await fetch(`${BASE}${path}`, {
method: 'POST',
credentials: 'include',
headers,
body,
})
if (res.status === 401 && !PUBLIC_PATHS.has(window.location.pathname)) {
window.location.href = `${BINDERY_BASE}/login`
return Promise.reject(new Error('unauthenticated'))
}
if (!res.ok) {
const data = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(data.error || `HTTP ${res.status}`)
}
return res.json() as Promise<T>
}
export interface AuthStatus {
authenticated: boolean
setupRequired: boolean
username?: string
role?: string
mode: 'enabled' | 'local-only' | 'disabled' | 'proxy'
localAuthEnabled: boolean
}
export interface ManagedUser {
id: number
username: string
role: string
email?: string
displayName?: string
createdAt: string
}
export interface SystemStatus {
version: string
commit: string
buildDate: string
imageCacheBytes?: number
enhancedHardcoverApi: boolean
hardcoverTokenConfigured: boolean
enhancedHardcoverDisabledReason?: 'env_disabled' | 'missing_token' | 'admin_disabled' | string
}
export interface AuthConfig {
mode: 'enabled' | 'local-only' | 'disabled' | 'proxy'
apiKey: string
username: string
}
export interface OidcProviderStatus {
state: 'ok' | 'failed'
last_error?: string
last_attempt?: string
}
export interface OidcProvider {
id: string
name: string
// Optional runtime status. Present on responses from a backend that
// tracks failed-discovery state; absent for older backends.
status?: OidcProviderStatus
}
export interface OidcProviderConfig {
id: string
name: string
issuer: string
client_id: string
client_secret: string
scopes: string[]
}
export const api = {
// System
health: () => request<{ status: string; version: string }>('/health'),
status: () => request<SystemStatus>('/system/status'),
getLogs: (params?: { level?: string; component?: string; from?: string; to?: string; q?: string; limit?: number; offset?: number }) => {
const p: Record<string, string> = {}
if (params?.level) p.level = params.level
if (params?.component) p.component = params.component
if (params?.from) p.from = params.from
if (params?.to) p.to = params.to
if (params?.q) p.q = params.q
if (params?.limit) p.limit = String(params.limit)
if (params?.offset) p.offset = String(params.offset)
const qs = new URLSearchParams(p).toString()
return request<LogEntry[]>(`/system/logs${qs ? '?' + qs : ''}`)
},
getLogLevel: () => request<{ level: string }>('/system/loglevel'),
setLogLevel: (level: string) =>
request<{ level: string }>('/system/loglevel', { method: 'PUT', body: JSON.stringify({ level }) }),
getStorage: () =>
request<{ downloadDir: string; audiobookDownloadDir: string; libraryDir: string; audiobookDir: string }>('/system/storage'),
// Auth
authStatus: () => request<AuthStatus>('/auth/status'),
oidcProviders: () => request<OidcProvider[]>('/auth/oidc/providers'),
oidcSetProviders: (providers: OidcProviderConfig[]) =>
request<void>('/auth/oidc/providers', { method: 'PUT', body: JSON.stringify(providers) }),
// Returns the public base URL Bindery will use as the prefix for OIDC
// callback URLs (resolved from the current request) plus the path template
// with `{id}` placeholder. The settings UI uses these to live-render the
// redirect URI as the admin types the provider id.
oidcRedirectBase: () => request<{ base: string; callback_path: string; configured: boolean }>('/auth/oidc/redirect-base'),
// Probes <issuer>/.well-known/openid-configuration server-side. ok=false
// means the IdP is unreachable / wrong / not OIDC; the error string is
// safe to render directly. issuer_mismatch=true is the silent killer for
// Authentik per-provider mode and Keycloak realms.
oidcTestDiscovery: (issuer: string) =>
request<{
ok: boolean
error?: string
issuer_mismatch?: boolean
discovered?: {
issuer: string
authorization_endpoint: string
token_endpoint: string
userinfo_endpoint?: string
jwks_uri?: string
scopes_supported?: string[]
}
}>('/auth/oidc/test-discovery', { method: 'POST', body: JSON.stringify({ issuer }) }),
authLogin: async (username: string, password: string, rememberMe: boolean) => {
const res = await request<{ ok: boolean; username: string }>('/auth/login', {
method: 'POST',
body: JSON.stringify({ username, password, rememberMe }),
})
await initCSRF()
return res
},
authLogout: async () => {
const res = await request<{ ok: boolean }>('/auth/logout', { method: 'POST' })
csrfToken = ''
return res
},
authSetup: (username: string, password: string) =>
request<{ ok: boolean }>('/auth/setup', {
method: 'POST',
body: JSON.stringify({ username, password }),
}),
authConfig: () => request<AuthConfig>('/auth/config'),
authChangePassword: (currentPassword: string, newPassword: string) =>
request<{ ok: boolean }>('/auth/password', {
method: 'POST',
body: JSON.stringify({ currentPassword, newPassword }),
}),
authRegenerateApiKey: () =>
request<{ apiKey: string }>('/auth/apikey/regenerate', { method: 'POST' }),
authRotateSessionSecret: () =>
request<{ ok: boolean }>('/auth/session-secret/rotate', { method: 'POST' }),
authSetMode: (mode: AuthStatus['mode']) =>
request<{ mode: string }>('/auth/mode', {
method: 'PUT',
body: JSON.stringify({ mode }),
}),
listUsers: () => request<ManagedUser[]>('/auth/users'),
createUser: (username: string, password: string, role: string) =>
request<ManagedUser>('/auth/users', { method: 'POST', body: JSON.stringify({ username, password, role }) }),
deleteUser: (id: number) => request<{ ok: boolean }>(`/auth/users/${id}`, { method: 'DELETE' }),
setUserRole: (id: number, role: string) =>
request<{ ok: boolean }>(`/auth/users/${id}/role`, { method: 'PUT', body: JSON.stringify({ role }) }),
resetUserPassword: (id: number, password: string) =>
request<{ ok: boolean }>(`/auth/users/${id}/reset-password`, { method: 'PUT', body: JSON.stringify({ password }) }),
// Metadata search
searchAuthors: (term: string) => request<Author[]>(`/search/author?term=${encodeURIComponent(term)}`),
searchBooks: (term: string) => request<Book[]>(`/search/book?term=${encodeURIComponent(term)}`),
lookupISBN: (isbn: string) => request<Book>(`/book/lookup?isbn=${encodeURIComponent(isbn)}`),
// Add a single book to wanted (adds author silently if new)
addBook: (data: { foreignBookId: string; foreignAuthorId: string; authorName?: string; searchOnAdd?: boolean }) =>
request<Book>('/author/book', { method: 'POST', body: JSON.stringify(data) }),
// Authors
listAuthors: () => request<Author[]>('/author'),
getAuthor: (id: number) => request<Author>(`/author/${id}`),
addAuthor: (data: AddAuthorRequest) => request<Author>('/author', { method: 'POST', body: JSON.stringify(data) }),
updateAuthor: (id: number, data: UpdateAuthorRequest) => request<Author>(`/author/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteAuthor: (id: number, deleteFiles = false) =>
request<void>(`/author/${id}${deleteFiles ? '?deleteFiles=true' : ''}`, { method: 'DELETE' }),
refreshAuthor: (id: number) => request<void>(`/author/${id}/refresh`, { method: 'POST' }),
relinkAuthorUpstream: (id: number) => request<Author>(`/author/${id}/relink-upstream`, { method: 'POST' }),
listAuthorAliases: (id: number) => request<AuthorAlias[]>(`/author/${id}/aliases`),
mergeAuthors: (targetId: number, sourceId: number, overwriteDefaults = true) =>
request<MergeAuthorsResult>(`/author/${targetId}/merge`, {
method: 'POST',
body: JSON.stringify({ sourceId, overwriteDefaults }),
}),
// Books
listBooks: (params?: { authorId?: number; status?: string; includeExcluded?: boolean }) => {
const q = new URLSearchParams()
if (params?.authorId) q.set('authorId', String(params.authorId))
if (params?.status) q.set('status', params.status)
if (params?.includeExcluded) q.set('includeExcluded', 'true')
const qs = q.toString()
return request<Book[]>(`/book${qs ? '?' + qs : ''}`)
},
getBook: (id: number) => request<Book>(`/book/${id}`),
updateBook: (id: number, data: Partial<Book>) => request<Book>(`/book/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteBook: (id: number, deleteFiles = false) =>
request<void>(`/book/${id}${deleteFiles ? '?deleteFiles=true' : ''}`, { method: 'DELETE' }),
deleteBookFile: (id: number, queryParams = '') => request<Book>(`/book/${id}/file${queryParams}`, { method: 'DELETE' }),
searchBook: (id: number) => request<SearchBookResponse>(`/book/${id}/search`, { method: 'POST' }),
getLastSearchDebug: () => request<SearchDebug>(`/search/last-debug`),
enrichAudiobook: (id: number) => request<Book>(`/book/${id}/enrich-audiobook`, { method: 'POST' }),
toggleExcluded: (id: number) => request<Book>(`/book/${id}/exclude`, { method: 'PUT' }),
rebindBook: (id: number, provider: 'openlibrary' | 'hardcover', foreignId: string, force = false) =>
request<Book>(`/book/${id}/rebind`, { method: 'POST', body: JSON.stringify({ provider, foreign_id: foreignId, force }) }),
// Wanted
listWanted: (opts?: { includeExcluded?: boolean }) => {
const qs = opts?.includeExcluded ? '?includeExcluded=true' : ''
return request<Book[]>(`/wanted/missing${qs}`)
},
// Bulk actions
bulkActionAuthors: (ids: number[], action: AuthorBulkAction, mediaType?: MediaType) =>
request<BulkResult>('/author/bulk', { method: 'POST', body: JSON.stringify({ ids, action, ...(mediaType ? { mediaType } : {}) }) }),
searchAuthorWanted: (id: number) =>
request<BulkResult>('/author/bulk', { method: 'POST', body: JSON.stringify({ ids: [id], action: 'search' }) }),
bulkActionBooks: (ids: number[], action: BookBulkAction, mediaType?: MediaType) =>
request<BulkResult>('/book/bulk', { method: 'POST', body: JSON.stringify({ ids, action, ...(mediaType ? { mediaType } : {}) }) }),
bulkActionWanted: (ids: number[], action: WantedBulkAction) =>
request<BulkResult>('/wanted/bulk', { method: 'POST', body: JSON.stringify({ ids, action }) }),
// Indexers
listIndexers: () => request<Indexer[]>('/indexer'),
addIndexer: (data: Partial<Indexer>) => request<Indexer>('/indexer', { method: 'POST', body: JSON.stringify(data) }),
updateIndexer: (id: number, data: Partial<Indexer>) => request<Indexer>(`/indexer/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteIndexer: (id: number) => request<void>(`/indexer/${id}`, { method: 'DELETE' }),
testIndexer: (id: number) => request<IndexerTestResult>(`/indexer/${id}/test`, { method: 'POST' }),
// Prowlarr indexer sync
listProwlarr: () => request<ProwlarrInstance[]>('/prowlarr'),
addProwlarr: (data: Partial<ProwlarrInstance>) => request<ProwlarrInstance>('/prowlarr', { method: 'POST', body: JSON.stringify(data) }),
updateProwlarr: (id: number, data: Partial<ProwlarrInstance>) => request<ProwlarrInstance>(`/prowlarr/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteProwlarr: (id: number) => request<void>(`/prowlarr/${id}`, { method: 'DELETE' }),
testProwlarr: (id: number) => request<{ ok: string; version?: string; error?: string }>(`/prowlarr/${id}/test`, { method: 'POST' }),
syncProwlarr: (id: number) => request<{ added: number; updated: number; removed: number }>(`/prowlarr/${id}/sync`, { method: 'POST' }),
searchIndexers: (q: string) => request<SearchResult[]>(`/indexer/search?q=${encodeURIComponent(q)}`),
// Download clients
listDownloadClients: () => request<DownloadClient[]>('/downloadclient'),
addDownloadClient: (data: Partial<DownloadClient>) => request<DownloadClient>('/downloadclient', { method: 'POST', body: JSON.stringify(data) }),
updateDownloadClient: (id: number, data: Partial<DownloadClient>) => request<DownloadClient>(`/downloadclient/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteDownloadClient: (id: number) => request<void>(`/downloadclient/${id}`, { method: 'DELETE' }),
testDownloadClient: (id: number) => request<{ message: string; health?: DownloadClientHealth }>(`/downloadclient/${id}/test`, { method: 'POST' }),
// Library
triggerLibraryScan: () => request<{ message: string }>('/library/scan', { method: 'POST' }),
libraryScanStatus: () => request<{
ran_at: string
files_found: number
reconciled: number
unmatched: number
tag_read_failed?: number
unmatched_files?: Array<{ path: string; parsed_title: string; parsed_author: string }>
}>('/library/scan/status'),
// Queue
listQueue: () => request<QueueItem[]>('/queue'),
grab: (data: GrabRequest) => request<Download>('/queue/grab', { method: 'POST', body: JSON.stringify(data) }),
retryImport: (id: number) => request<{ ok: boolean }>(`/queue/${id}/retry-import`, { method: 'POST' }),
deleteFromQueue: (id: number, deleteFiles = false) =>
request<void>(`/queue/${id}${deleteFiles ? '?deleteFiles=true' : ''}`, { method: 'DELETE' }),
// Pending releases
listPending: () => request<PendingRelease[]>('/pending'),
dismissPending: (id: number) => request<void>(`/pending/${id}`, { method: 'DELETE' }),
grabPending: (id: number) => request<Download>(`/pending/${id}/grab`, { method: 'POST' }),
// History
listHistory: (params?: { bookId?: number; eventType?: string }) => {
const q = new URLSearchParams()
if (params?.bookId) q.set('bookId', String(params.bookId))
if (params?.eventType) q.set('eventType', params.eventType)
const qs = q.toString()
return request<HistoryEvent[]>(`/history${qs ? '?' + qs : ''}`)
},
deleteHistory: (id: number) => request<void>(`/history/${id}`, { method: 'DELETE' }),
blocklistFromHistory: (id: number) => request<BlocklistEntry>(`/history/${id}/blocklist`, { method: 'POST' }),
// Blocklist
listBlocklist: () => request<BlocklistEntry[]>('/blocklist'),
deleteBlocklistEntry: (id: number) => request<void>(`/blocklist/${id}`, { method: 'DELETE' }),
bulkDeleteBlocklist: (ids: number[]) => request<void>('/blocklist/bulk', { method: 'DELETE', body: JSON.stringify({ ids }) }),
// Notifications
listNotifications: () => request<NotificationConfig[]>('/notification'),
addNotification: (data: Partial<NotificationConfig>) => request<NotificationConfig>('/notification', { method: 'POST', body: JSON.stringify(data) }),
updateNotification: (id: number, data: Partial<NotificationConfig>) => request<NotificationConfig>(`/notification/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteNotification: (id: number) => request<void>(`/notification/${id}`, { method: 'DELETE' }),
testNotification: (id: number) => request<{ message: string }>(`/notification/${id}/test`, { method: 'POST' }),
// Quality Profiles
listQualityProfiles: () => request<QualityProfile[]>('/qualityprofile'),
// Series
listSeries: () => request<Series[]>('/series'),
createSeries: (data: { title: string }) => request<Series>('/series', { method: 'POST', body: JSON.stringify(data) }),
getSeries: (id: number) => request<Series>(`/series/${id}`),
updateSeries: (id: number, data: { title: string }) => request<Series>(`/series/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
monitorSeries: (id: number, monitored: boolean) => request<{ monitored: boolean }>(`/series/${id}`, { method: 'PATCH', body: JSON.stringify({ monitored }) }),
deleteSeries: (id: number) => request<void>(`/series/${id}`, { method: 'DELETE' }),
linkBookToSeries: (id: number, data: { bookId: number; positionInSeries: string; primarySeries: boolean }) =>
request<Series>(`/series/${id}/books`, { method: 'POST', body: JSON.stringify(data) }),
fillSeries: (id: number, book?: SeriesFillBookRequest) =>
request<{ queued: number }>(`/series/${id}/fill`, {
method: 'POST',
...(book ? { body: JSON.stringify(book) } : {}),
}),
searchHardcoverSeries: (term: string, limit = 10) =>
request<SeriesHardcoverSearchResult[]>(`/series/hardcover/search?term=${encodeURIComponent(term)}&limit=${limit}`),
getSeriesHardcoverLink: (id: number) => request<SeriesHardcoverLink>(`/series/${id}/hardcover-link`),
autoLinkSeriesHardcover: (id: number) =>
request<SeriesHardcoverAutoResponse>(`/series/${id}/hardcover-link/auto`, { method: 'POST' }),
linkSeriesHardcover: (id: number, result: SeriesHardcoverSearchResult) =>
request<SeriesHardcoverLink>(`/series/${id}/hardcover-link`, {
method: 'PUT',
body: JSON.stringify(result),
}),
unlinkSeriesHardcover: (id: number) => request<{ success: boolean }>(`/series/${id}/hardcover-link`, { method: 'DELETE' }),
getSeriesHardcoverDiff: (id: number) => request<SeriesHardcoverDiff>(`/series/${id}/hardcover-diff`),
// Tags
listTags: () => request<Tag[]>('/tag'),
addTag: (name: string) => request<Tag>('/tag', { method: 'POST', body: JSON.stringify({ name }) }),
deleteTag: (id: number) => request<void>(`/tag/${id}`, { method: 'DELETE' }),
// Settings
listSettings: () => request<Array<{ key: string; value: string }>>('/setting'),
getSetting: (key: string) => request<{ key: string; value: string }>(`/setting/${key}`),
setSetting: (key: string, value: string) => request<void>(`/setting/${key}`, { method: 'PUT', body: JSON.stringify({ value }) }),
testHardcover: () => request<HardcoverTestResult>('/hardcover/test', { method: 'POST' }),
// Backup
listBackups: () => request<Array<{ name: string; size: number; modTime: string }>>('/backup'),
createBackup: () => request<{ name: string; size: number; modTime: string }>('/backup', { method: 'POST' }),
deleteBackup: (filename: string) => request<void>(`/backup/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
// Calibre
testCalibre: () => request<CalibreTestResult>('/calibre/test', { method: 'POST' }),
calibreImportStart: () => request<CalibreImportProgress>('/calibre/import', { method: 'POST' }),
calibreImportStatus: () => request<CalibreImportProgress>('/calibre/import/status'),
calibreSyncStart: () => request<CalibreSyncProgress>('/calibre/sync', { method: 'POST' }),
calibreSyncStatus: () => request<CalibreSyncProgress>('/calibre/sync/status'),
// Grimmory
grimmoryConfig: () => request<GrimmoryConfig>('/grimmory/config'),
grimmorySetConfig: (data: { enabled?: boolean; baseUrl?: string; apiKey?: string }) =>
request<GrimmoryConfig>('/grimmory/config', { method: 'PUT', body: JSON.stringify(data) }),
grimmoryTest: (data?: { baseUrl?: string; apiKey?: string }) =>
request<GrimmoryTestResult>('/grimmory/test', { method: 'POST', body: JSON.stringify(data ?? {}) }),
// Audiobookshelf
absConfig: () => request<ABSConfig>('/abs/config'),
absSetConfig: (data: { baseUrl: string; label: string; enabled: boolean; libraryId: string; libraryIds?: string[]; pathRemap: string; apiKey?: string }) =>
request<ABSConfig>('/abs/config', { method: 'PUT', body: JSON.stringify(data) }),
absTest: (data?: { baseUrl?: string; apiKey?: string }) =>
request<ABSTestResult>('/abs/test', { method: 'POST', body: JSON.stringify(data ?? {}) }),
absLibraries: (data?: { baseUrl?: string; apiKey?: string }) =>
request<ABSLibrary[]>('/abs/libraries', { method: 'POST', body: JSON.stringify(data ?? {}) }),
absImportStart: (data?: { dryRun?: boolean }) =>
request<ABSImportProgress>('/abs/import', { method: 'POST', body: JSON.stringify(data ?? {}) }),
absImportStatus: () => request<ABSImportProgress>('/abs/import/status'),
absImportRuns: () => request<ABSImportRun[]>('/abs/import/runs'),
absImportRollbackPreview: (runId: number) => request<ABSRollbackResult>(`/abs/import/runs/${runId}/rollback/preview`, { method: 'POST' }),
absImportRollback: (runId: number) => request<ABSRollbackResult>(`/abs/import/runs/${runId}/rollback`, { method: 'POST' }),
absReviewItems: (params?: { limit?: number; offset?: number }) => {
const q = new URLSearchParams()
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
return request<PaginatedResponse<ABSReviewItem>>(`/abs/review${q.toString() ? `?${q.toString()}` : ''}`)
},
approveAbsReviewItem: (id: number) => request<ABSReviewItem>(`/abs/review/${id}/approve`, { method: 'POST' }),
resolveAbsReviewAuthor: (id: number, data: { foreignAuthorId: string; authorName: string; applyTo?: 'same_author' }) =>
request<{ updated: number }>(`/abs/review/${id}/resolve-author`, { method: 'POST', body: JSON.stringify(data) }),
resolveAbsReviewBook: (id: number, data: { foreignBookId: string; title: string; editedTitle?: string }) =>
request<ABSReviewItem>(`/abs/review/${id}/resolve-book`, { method: 'POST', body: JSON.stringify(data) }),
dismissAbsReviewItem: (id: number) => request<ABSReviewItem>(`/abs/review/${id}/dismiss`, { method: 'POST' }),
dismissAbsReviewRun: (runId: number) =>
request<{ dismissed: number }>(`/abs/review/dismiss-run/${runId}`, { method: 'POST' }),
absConflicts: (params?: { limit?: number; offset?: number }) => {
const q = new URLSearchParams()
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
return request<PaginatedResponse<ABSMetadataConflict>>(`/abs/conflicts${q.toString() ? `?${q.toString()}` : ''}`)
},
resolveAbsConflict: (id: number, source: 'abs' | 'upstream') =>
request<ABSMetadataConflict>(`/abs/conflicts/${id}/resolve`, { method: 'POST', body: JSON.stringify({ source }) }),
// Import lists
listImportLists: () => request<ImportList[]>('/importlist'),
addImportList: (data: Partial<ImportList>) => request<ImportList>('/importlist', { method: 'POST', body: JSON.stringify(data) }),
updateImportList: (id: number, data: ImportListUpdate) => request<ImportList>(`/importlist/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteImportList: (id: number) => request<void>(`/importlist/${id}`, { method: 'DELETE' }),
syncImportList: (id: number) => request<{ status: string }>(`/importlist/${id}/sync`, { method: 'POST' }),
hardcoverLists: (token?: string) =>
request<HardcoverList[]>('/importlist/hardcover/lists', {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
}),
uploadMigrate: <T>(endpoint: 'csv' | 'readarr', body: FormData) =>
uploadFile<T>(`/migrate/${endpoint}`, body),
// Goodreads CSV import — two steps: a dry-run preview that resolves every
// row, then a commit of the resolved books keyed by the preview token.
goodreadsPreview: (body: FormData) =>
uploadFile<GoodreadsPreview>('/migrate/goodreads/preview', body),
goodreadsCommit: (token: string) =>
request<GoodreadsCommitResult>('/migrate/goodreads/commit', {
method: 'POST',
body: JSON.stringify({ token }),
}),
// Metadata Profiles
listMetadataProfiles: () => request<MetadataProfile[]>('/metadataprofile'),
addMetadataProfile: (data: Partial<MetadataProfile>) => request<MetadataProfile>('/metadataprofile', { method: 'POST', body: JSON.stringify(data) }),
updateMetadataProfile: (id: number, data: Partial<MetadataProfile>) => request<MetadataProfile>(`/metadataprofile/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
deleteMetadataProfile: (id: number) => request<void>(`/metadataprofile/${id}`, { method: 'DELETE' }),
// Delay Profiles
listDelayProfiles: () => request<DelayProfile[]>('/delayprofile'),
addDelayProfile: (data: Partial<DelayProfile>) => request<DelayProfile>('/delayprofile', { method: 'POST', body: JSON.stringify(data) }),
deleteDelayProfile: (id: number) => request<void>(`/delayprofile/${id}`, { method: 'DELETE' }),
// Custom Formats
listCustomFormats: () => request<CustomFormat[]>('/customformat'),
addCustomFormat: (data: Partial<CustomFormat>) => request<CustomFormat>('/customformat', { method: 'POST', body: JSON.stringify(data) }),
deleteCustomFormat: (id: number) => request<void>(`/customformat/${id}`, { method: 'DELETE' }),
// Root Folders
listRootFolders: () => request<RootFolder[]>('/rootfolder'),
addRootFolder: (path: string) => request<RootFolder>('/rootfolder', { method: 'POST', body: JSON.stringify({ path }) }),
deleteRootFolder: (id: number) => request<void>(`/rootfolder/${id}`, { method: 'DELETE' }),
// Recommendations
listRecommendations: (params?: { type?: string; limit?: number; offset?: number }) => {
const q = new URLSearchParams()
if (params?.type) q.set('type', params.type)
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
const qs = q.toString()
return request<Recommendation[]>(`/recommendations${qs ? '?' + qs : ''}`)
},
dismissRecommendation: (id: number) => request<void>(`/recommendations/${id}/dismiss`, { method: 'POST' }),
addRecommendation: (id: number) => request<void>(`/recommendations/${id}/add`, { method: 'POST' }),
refreshRecommendations: () => request<void>('/recommendations/refresh', { method: 'POST' }),
clearRecommendationDismissals: () => request<void>('/recommendations/dismissals', { method: 'DELETE' }),
listAuthorExclusions: () => request<string[]>('/recommendations/exclude-author'),
addAuthorExclusion: (authorName: string) => request<void>('/recommendations/exclude-author', { method: 'POST', body: JSON.stringify({ authorName }) }),
removeAuthorExclusion: (authorName: string) => request<void>(`/recommendations/exclude-author/${encodeURIComponent(authorName)}`, { method: 'DELETE' }),
}
// Types
export interface Author {
id: number
foreignAuthorId: string
authorName: string
sortName: string
description: string
imageUrl: string
disambiguation: string
ratingsCount: number
averageRating: number
monitored: boolean
qualityProfileId?: number | null
metadataProfileId?: number | null
rootFolderId?: number | null
audiobookRootFolderId?: number | null
books?: Book[]
statistics?: { bookCount: number; availableBookCount: number; wantedBookCount: number }
aliases?: AuthorAlias[]
}
export interface AuthorAlias {
id: number
authorId: number
name: string
sourceOlId?: string
createdAt: string
}
export interface MergeAuthorsResult {
BooksReparented: number
AliasesMigrated: number
AliasesCreated: number
TargetUpdated: boolean
}
export type MediaType = 'ebook' | 'audiobook' | 'both'
export interface BookFile {
id: number
bookId: number
format: 'ebook' | 'audiobook'
path: string
sizeBytes: number
createdAt: string
}
export interface Book {
id: number
foreignBookId: string
authorId: number
title: string
description: string
imageUrl: string
releaseDate?: string
genres: string[]
monitored: boolean
status: string
filePath: string
mediaType: MediaType
// Per-format file paths for dual-format books (mediaType='both').
ebookFilePath: string
audiobookFilePath: string
// All on-disk files tracked in book_files (populated on single-book GET).
bookFiles?: BookFile[]
excluded: boolean
narrator?: string
durationSeconds?: number
asin?: string
language?: string
calibre_id?: number
author?: Author
}
// CalibreMode selects which integration flow runs after a successful
// Bindery import. 'off' skips Calibre entirely, 'calibredb' shells out to
// the calibredb CLI, 'plugin' posts to the Bindery Bridge Calibre plugin.
export type CalibreMode = 'off' | 'calibredb' | 'plugin'
// CalibreSettings mirrors the `calibre.*` keys stored in the settings table.
export interface CalibreSettings {
calibre_mode: CalibreMode
calibre_library_path: string
calibre_binary_path: string
}
export interface CalibreTestResult {
ok: string
version: string
message: string
}
// CalibreImportStats summarises one completed library import. Present
// only on the final poll (when progress.running flips false).
export interface CalibreImportStats {
authorsAdded: number
authorsLinked: number
booksAdded: number
booksUpdated: number
editionsAdded: number
duplicatesMerged: number
skipped: number
}
// CalibreImportProgress is the polled shape for /calibre/import/status.
// The UI renders a progress bar from total/processed, swaps in the stats
// summary once running=false, and surfaces any error inline.
export interface CalibreImportProgress {
running: boolean
startedAt?: string
finishedAt?: string
total: number
processed: number
message?: string
error?: string
stats?: CalibreImportStats
}
// CalibreSyncError is one failed push entry returned by /calibre/sync/status.
export interface CalibreSyncError {
bookId: number
title: string
path?: string
reason: string
}
// CalibreSyncStats summarises one bulk-push run. Pushed = newly added;
// alreadyInCalibre = 409 Conflict (treated as success for idempotency);
// failed = everything else.
export interface CalibreSyncStats {
total: number
processed: number
pushed: number
alreadyInCalibre: number
failed: number
}
// CalibreSyncProgress is the polled shape for /calibre/sync/status.
export interface CalibreSyncProgress {
running: boolean
startedAt?: string
finishedAt?: string
message?: string
error?: string
stats: CalibreSyncStats
errors: CalibreSyncError[]
}
export interface GrimmoryConfig {
enabled: boolean
baseUrl: string
apiKeyConfigured: boolean
}
export interface GrimmoryTestResult {
ok: boolean
message: string
version?: string
}
export interface ABSConfig {
featureEnabled: boolean
baseUrl: string
label: string
enabled: boolean
libraryId: string
libraryIds?: string[]
pathRemap: string
apiKeyConfigured: boolean
}
export interface ABSLibraryFolder {
id: string
fullPath: string
}
export interface ABSLibrary {
id: string
name: string
mediaType: string
icon: string
provider: string
folders: ABSLibraryFolder[]
}
export interface ABSTestResult {
message: string
username: string
userType: string
defaultLibraryId: string
serverVersion: string
source: string
}
export interface ABSImportStats {
librariesScanned: number
pagesScanned: number
itemsSeen: number
itemsNormalized: number
itemsDetailFetched: number
authorsCreated: number
authorsLinked: number
booksCreated: number
booksLinked: number
booksUpdated: number
seriesCreated: number
seriesLinked: number
editionsAdded: number
ownedMarked: number
pendingManual: number
reviewQueued: number
metadataMatched: number
metadataRelinked: number
metadataConflicts: number
metadataAutoResolved: number
skipped: number
failed: number
}
export interface ABSImportItemResult {
itemId: string
title: string
outcome: string
message?: string
matchedBy?: string
authorId?: number
bookId?: number
seriesCount?: number
}
export interface ABSImportProgress {
running: boolean
runId?: number
dryRun?: boolean
startedAt?: string
finishedAt?: string
processed: number
message?: string
error?: string
resumedFromCheckpoint?: boolean
checkpoint?: {
libraryId: string
page: number
lastItemId?: string
pageSize: number
updatedAt: string
}
stats?: ABSImportStats
results?: ABSImportItemResult[]
}
export interface ABSImportRunSummary {
dryRun: boolean
resumedFromCheckpoint: boolean
checkpoint?: {
libraryId: string
page: number
lastItemId?: string
pageSize: number
updatedAt: string
}
stats: ABSImportStats
error?: string
}
export interface ABSImportRun {
id: number
sourceId: string
sourceLabel: string
baseUrl: string
libraryId: string
status: string
dryRun: boolean
startedAt: string
finishedAt?: string
source: {
sourceId: string
label: string
baseUrl: string
libraryId: string
libraryIds?: string[]
pathRemap?: string
enabled: boolean
dryRun: boolean
}
checkpoint?: {
libraryId: string
page: number
lastItemId?: string
pageSize: number
updatedAt: string
}
summary: ABSImportRunSummary
}
export interface ABSRollbackAction {
entityType: string
externalId: string
displayName?: string
localId: number
outcome: string
action: string
reason?: string
}
export interface ABSRollbackResult {
runId: number
preview: boolean
dryRun: boolean
status: string
stats: {
actionsPlanned: number
entitiesDeleted: number
provenanceUnlinked: number
skipped: number
failed: number
}
actions: ABSRollbackAction[]
finishedAt: string
}
export interface ABSReviewItem {
id: number
sourceId: string
libraryId: string
itemId: string
title: string
primaryAuthor: string
asin: string
mediaType: string
reviewReason: 'unmatched_author' | 'ambiguous_author' | 'unmatched_book' | 'ambiguous_book'
payloadJson: string
resolvedAuthorForeignId?: string
resolvedAuthorName?: string
resolvedBookForeignId?: string
resolvedBookTitle?: string
editedTitle?: string
fileMappingFound: boolean
fileMappingMessage?: string
latestRunId?: number | null
status: 'pending' | 'approved' | 'dismissed'
createdAt: string
updatedAt: string
}
export interface PaginatedResponse<T> {
items: T[]
total: number
limit: number
offset: number
}
export interface ABSMetadataConflict {
id: number
sourceId: string
libraryId: string
itemId: string
entityType: string
localId: number
entityName: string
fieldName: string
fieldLabel: string
absValue: string
upstreamValue: string
appliedSource: 'abs' | 'upstream' | ''
appliedValue: string
preferredSource: 'abs' | 'upstream' | ''
authorRelinkEligible: boolean
resolutionStatus: 'unresolved' | 'resolved'
updatedAt: string
}
export interface Indexer {
id: number
name: string
type: string
url: string
apiKey: string
categories: number[]
enabled: boolean
prowlarrInstanceId?: number
}
export interface IndexerTestResult {
ok: boolean
status: number
categories: number
bookSearch: boolean
latencyMs: number
searchResults: number
searchError?: string
message?: string
error?: string
}
export interface PendingRelease {
id: number
bookId: number
title: string
indexerId?: number
guid: string
protocol: string
size: number
ageMinutes: number
quality?: string
customScore: number
reason: string
firstSeen: string
releaseJson: string
}
export interface ProwlarrInstance {
id: number
name: string
url: string
apiKey: string
syncOnStartup: boolean
enabled: boolean
lastSyncAt?: string
}
export interface DownloadClient {
id: number
name: string
type: string
host: string
port: number
apiKey: string
username: string
password: string
useSsl: boolean
urlBase: string
category: string
pathRemap?: string
enabled: boolean
health?: DownloadClientHealth
}
export interface DownloadClientHealth {
status: 'ok' | 'checking' | 'error'
message: string
}
export interface Download {
id: number
guid: string
title: string
status: string
size: number
protocol: string
errorMessage: string
addedAt: string
grabbedAt?: string
completedAt?: string
importedAt?: string
}
export interface QueueItem extends Download {
percentage?: string
timeLeft?: string
}
export interface SearchResult {
guid: string
indexerName: string