@astrofoundry/trendarr 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,15 +21,19 @@ trendarr add-series <imdbIds...> [--json]
21
21
  trendarr sabnzbd status|pause|resume|unpause [--json]
22
22
  trendarr books search <query> [--max-entries 10] [--json]
23
23
  trendarr books add <bookId> --format audiobook|ebook [--json]
24
- trendarr books releases <bookId> --format audiobook|ebook [--max-entries 10] [--json]
24
+ trendarr books narrators <bookId> [--max-entries 5] [--json]
25
+ trendarr books releases <bookId> --format audiobook|ebook [--edition <id>] [--max-entries 10] [--json]
25
26
  trendarr books grab <chaptarrId> <guid> <indexerId> [--json]
27
+ trendarr books best <bookId> --format audiobook|ebook [--edition <id>] [--json]
26
28
  trendarr books ready <chaptarrId> [--json]
27
29
  trendarr books send <chaptarrId> <device> [--json]
30
+ trendarr books ebooks [--json]
31
+ trendarr books send-item <itemId> <device> [--json]
28
32
  ```
29
33
 
30
34
  `trendarr <command> --help` shows parameters and output shapes. Movies below the IMDb min-rating (default 6.5) are dropped from trending; unrated movies are kept; `--min-rating 0` disables the filter. `recommend` ranks the titles TMDB recommends for your Radarr and Sonarr library by how many library titles lead to them, and keeps released titles not in the library with IMDb 7.0+ and 5,000 votes (movies) or 2,000 (series).
31
35
 
32
- `books` works with Chaptarr, which keeps an audiobook and an ebook entry per work. `add` lets Chaptarr pick the release and waits up to 2 minutes to report whether it grabbed one; `releases` then `grab` let you pick one yourself (narrator, size, format). `ready` tells whether a book has its file and, for an ebook, whether Audiobookshelf has it. `send` emails an ebook to a Kindle through Audiobookshelf's e-reader devices.
36
+ `books` works with Chaptarr, which keeps an audiobook and an ebook entry per work. `add` lets Chaptarr pick the release and waits up to 2 minutes to report whether it grabbed one; `releases` then `grab` let you pick one yourself (narrator, size, format). `narrators` lists an audiobook's narrations, most rated first; `--edition` on `releases` and `best` monitors the one you pick first. Audiobook releases come best first: the narrator's surname in the name, then M4B, then the bitrate estimated from the edition's length. `best` grabs the first of them without a Chaptarr rejection, or leaves the book wanted. `ready` tells whether a book has its file and, for an ebook, whether Audiobookshelf has it. `send` emails an ebook to a Kindle through Audiobookshelf's e-reader devices. `ebooks` lists every ebook in Audiobookshelf, newest first, and `send-item` emails one of them by its item id.
33
37
 
34
38
  ## Development
35
39
 
package/dist/cli.js CHANGED
@@ -2,14 +2,14 @@
2
2
  import { createRequire } from 'node:module';
3
3
  import { Command, InvalidArgumentError } from 'commander';
4
4
  import { addMovies, addSeries, hasFailure } from './commands/add.js';
5
- import { addBook, bookReady, bookReleases, grabRelease, searchBooks, sendBook } from './commands/books.js';
5
+ import { addBook, bestBook, bookNarrators, bookReady, bookReleases, grabRelease, listEbooks, searchBooks, sendBook, sendItem, } from './commands/books.js';
6
6
  import { runInit } from './commands/init.js';
7
7
  import { runSabnzbd } from './commands/sabnzbd.js';
8
8
  import { CANDIDATE_LIMIT, getRecommendations } from './commands/recommend.js';
9
9
  import { getSearch } from './commands/search.js';
10
10
  import { getTrending } from './commands/trending.js';
11
11
  import { ConfigError, loadConfig } from './config.js';
12
- import { renderAddTable, renderBookAdd, renderBookGrab, renderBookReady, renderBookSearchTable, renderBookSend, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
12
+ import { renderAddTable, renderBookAdd, renderBookBest, renderBookGrab, renderBookReady, renderBookSearchTable, renderBookSend, renderEbookList, renderItemSend, renderNarrators, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
13
13
  import { describeError } from './http.js';
14
14
  const pkg = createRequire(import.meta.url)('../package.json');
15
15
  const program = new Command();
@@ -327,10 +327,14 @@ used by add and releases is Chaptarr's foreign book id (e.g. gr:3060926), from b
327
327
  Actions:
328
328
  search <query> Find works, with each format's state and the Kindle devices.
329
329
  add <bookId> --format <f> Monitor one format and let Chaptarr pick and download a release.
330
- releases <bookId> --format <f> List the releases you can pick from (narrator, size, quality).
330
+ narrators <bookId> List the audiobook narrations, most rated first.
331
+ releases <bookId> --format <f> List the releases you can pick from, best first for audiobooks.
331
332
  grab <chaptarrId> <guid> <indexerId> Download one release from that list.
333
+ best <bookId> --format <f> Download the first release of that list Chaptarr accepts.
332
334
  ready <chaptarrId> Whether the book has a file and, for an ebook, is in Audiobookshelf.
333
- send <chaptarrId> <device> Email the ebook to a Kindle through Audiobookshelf.`);
335
+ send <chaptarrId> <device> Email the ebook to a Kindle through Audiobookshelf.
336
+ ebooks List every ebook in Audiobookshelf, newest first, with the Kindles.
337
+ send-item <itemId> <device> Email one Audiobookshelf ebook item to a Kindle.`);
334
338
  books
335
339
  .command('search')
336
340
  .description('search Chaptarr for books by title or author')
@@ -395,29 +399,69 @@ Examples:
395
399
  fail(err);
396
400
  }
397
401
  });
402
+ books
403
+ .command('narrators')
404
+ .description('list the narrations of an audiobook to pick from')
405
+ .argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
406
+ .option('--max-entries <n>', 'narrations', parsePositiveInt)
407
+ .option('--json', 'output JSON')
408
+ .addHelpText('after', `
409
+ Behavior: adds the audiobook unmonitored when Chaptarr does not have it, then groups its editions by
410
+ narrator. Each group shows its most rated edition; groups are ordered by votes. Changes no edition.
411
+
412
+ Parameters:
413
+ --max-entries <n> Narrations (positive integer). Default: 5.
414
+
415
+ Output (--json): { foreign_book_id, book_id, title, narrators: NarratorChoice[] }
416
+ NarratorChoice: { edition_id, narrators, year, duration_seconds, rating, votes, language, chosen }
417
+ edition_id goes to books releases --edition or books best --edition; chosen marks the narration of
418
+ the monitored edition.
419
+
420
+ Examples:
421
+ trendarr books narrators hc:139773 --json`)
422
+ .action(async (bookId, opts) => {
423
+ try {
424
+ const { output, warnings } = await bookNarrators(loadConfig(), bookId, opts);
425
+ printWarnings(warnings);
426
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderNarrators(output)}\n`);
427
+ }
428
+ catch (err) {
429
+ fail(err);
430
+ }
431
+ });
398
432
  books
399
433
  .command('releases')
400
434
  .description('list the releases of one format to pick from')
401
435
  .argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
402
436
  .requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
437
+ .option('--edition <id>', 'edition_id from books narrators to monitor first', parsePositiveInt)
403
438
  .option('--max-entries <n>', 'releases', parsePositiveInt)
404
439
  .option('--json', 'output JSON')
405
440
  .addHelpText('after', `
406
- Behavior: adds the book unmonitored when Chaptarr does not have it, switches a suffixed edition title
407
- to the plain one as books add does, then runs Chaptarr's interactive
408
- search (can take a minute). Releases in a format the profile does not want, and torrents without
409
- enough seeders, are left out. Order is Chaptarr's. Grab one within 30 minutes, while Chaptarr
410
- still caches the search.
441
+ Behavior: adds the book unmonitored when Chaptarr does not have it, monitors --edition when given,
442
+ switches a suffixed edition title to the plain one as books add does, then runs Chaptarr's
443
+ interactive search (can take a minute). Releases in a format the profile does not want, and
444
+ torrents without enough seeders, are left out. Ebook releases keep Chaptarr's order. Audiobook
445
+ releases come best first: the monitored narrator's surname in the name, then M4B over MP3 and FLAC
446
+ over other formats, then the higher estimated bitrate, then Chaptarr's order. Grab one within
447
+ 30 minutes, while Chaptarr still caches the search.
411
448
 
412
- Output (--json): { foreign_book_id, format, book_id, title, releases: BookRelease[] }
449
+ Output (--json): { foreign_book_id, format, book_id, title, narrators, duration_seconds,
450
+ releases: BookRelease[] }
413
451
  BookRelease: { rank, title, size, quality, protocol, indexer, seeders, age_days, guid, indexer_id,
414
- rejections } — size in bytes; rejections are Chaptarr's reasons it would not pick it by itself.
452
+ rejections, narrator_match, kbps } — size in bytes; rejections are Chaptarr's reasons it would not
453
+ pick it by itself; kbps is size divided by the edition's length (null without a length or for
454
+ ebooks), so a release holding several books shows too high a value.
415
455
 
416
456
  Examples:
417
- trendarr books releases gr:3060926 --format audiobook --max-entries 5`)
457
+ trendarr books releases gr:3060926 --format audiobook --max-entries 5
458
+ trendarr books releases hc:139773 --format audiobook --edition 203`)
418
459
  .action(async (bookId, opts) => {
419
460
  try {
420
- const { output, warnings } = await bookReleases(loadConfig(), bookId, opts.format, opts);
461
+ const { output, warnings } = await bookReleases(loadConfig(), bookId, opts.format, {
462
+ maxEntries: opts.maxEntries,
463
+ editionId: opts.edition,
464
+ });
421
465
  printWarnings(warnings);
422
466
  process.stdout.write(`${opts.json === true ? toJson(output) : renderReleasesTable(output)}\n`);
423
467
  }
@@ -452,6 +496,38 @@ Examples:
452
496
  fail(err);
453
497
  }
454
498
  });
499
+ books
500
+ .command('best')
501
+ .description('download the best release Chaptarr accepts')
502
+ .argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
503
+ .requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
504
+ .option('--edition <id>', 'edition_id from books narrators to monitor first', parsePositiveInt)
505
+ .option('--json', 'output JSON')
506
+ .addHelpText('after', `
507
+ Behavior: does what books releases does, then monitors the book and grabs the first release in that
508
+ order without rejections. When every release has one, the book stays monitored and Chaptarr keeps
509
+ looking. A format that already has a file reports already_exists; one in the download queue
510
+ reports downloading without a grab.
511
+
512
+ Output (--json): { foreign_book_id, format, book_id, title, status, detail, release, sabnzbd_paused }
513
+ status is one of: downloading | nothing_found | already_exists | not_found | error.
514
+ release: { title, quality, kbps, narrator_match } of the grabbed release, else null.
515
+ Exit code 1 on not_found or error.
516
+
517
+ Examples:
518
+ trendarr books best hc:139773 --format audiobook --edition 203`)
519
+ .action(async (bookId, opts) => {
520
+ try {
521
+ const { output, warnings } = await bestBook(loadConfig(), bookId, opts.format, { editionId: opts.edition });
522
+ printWarnings(warnings);
523
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderBookBest(output)}\n`);
524
+ if (output.status === 'not_found' || output.status === 'error')
525
+ process.exitCode = 1;
526
+ }
527
+ catch (err) {
528
+ fail(err);
529
+ }
530
+ });
455
531
  books
456
532
  .command('ready')
457
533
  .description('report whether a book has its file and, for an ebook, whether Audiobookshelf has it')
@@ -505,6 +581,57 @@ Examples:
505
581
  fail(err);
506
582
  }
507
583
  });
584
+ books
585
+ .command('ebooks')
586
+ .description('list every ebook in Audiobookshelf, newest first, with the Kindle devices')
587
+ .option('--json', 'output JSON')
588
+ .addHelpText('after', `
589
+ Behavior: reads every book library of Audiobookshelf and keeps the items with an ebook file,
590
+ including ebooks Chaptarr does not manage. Changes nothing.
591
+
592
+ Output (--json): { "ebooks": EbookItem[], "kindles": string[] }
593
+ EbookItem: { item_id, title, author, added_at } — item_id is Audiobookshelf's library item id,
594
+ for send-item; added_at is ISO 8601 or null.
595
+
596
+ Examples:
597
+ trendarr books ebooks --json`)
598
+ .action(async (opts) => {
599
+ try {
600
+ const { output, warnings } = await listEbooks(loadConfig());
601
+ printWarnings(warnings);
602
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderEbookList(output)}\n`);
603
+ }
604
+ catch (err) {
605
+ fail(err);
606
+ }
607
+ });
608
+ books
609
+ .command('send-item')
610
+ .description('email one Audiobookshelf ebook item to a Kindle')
611
+ .argument('<itemId>', 'item_id from books ebooks')
612
+ .argument('<device>', 'Audiobookshelf e-reader device name, from books ebooks "kindles"')
613
+ .option('--json', 'output JSON')
614
+ .addHelpText('after', `
615
+ Behavior: asks Audiobookshelf to email that item's ebook to the device. The sender must be approved
616
+ on the Amazon account.
617
+
618
+ Output (--json): { item_id, device, status, detail }
619
+ status is one of: sent | unknown_device | error. Exit code 1 unless sent.
620
+
621
+ Examples:
622
+ trendarr books send-item ed3cbf09-3303-4714-ae11-f190d8279af5 "Kindle Astro"`)
623
+ .action(async (itemId, device, opts) => {
624
+ try {
625
+ const { output, warnings } = await sendItem(loadConfig(), itemId, device);
626
+ printWarnings(warnings);
627
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderItemSend(output)}\n`);
628
+ if (output.status !== 'sent')
629
+ process.exitCode = 1;
630
+ }
631
+ catch (err) {
632
+ fail(err);
633
+ }
634
+ });
508
635
  if (process.argv.slice(2).length === 0) {
509
636
  program.outputHelp();
510
637
  process.exit(0);
@@ -8,7 +8,13 @@ const itemsSchema = z.object({
8
8
  results: z.array(z.object({
9
9
  id: z.string(),
10
10
  path: z.string(),
11
- media: z.object({ ebookFormat: z.string().nullish() }).nullish(),
11
+ addedAt: z.number().nullish(),
12
+ media: z
13
+ .object({
14
+ ebookFormat: z.string().nullish(),
15
+ metadata: z.object({ title: z.string().nullish(), authorName: z.string().nullish() }).nullish(),
16
+ })
17
+ .nullish(),
12
18
  })),
13
19
  });
14
20
  export class AudiobookshelfClient {
@@ -30,7 +36,14 @@ export class AudiobookshelfClient {
30
36
  }
31
37
  async items(libraryId) {
32
38
  const parsed = itemsSchema.parse(await this.request(`/api/libraries/${encodeURIComponent(libraryId)}/items?limit=0`));
33
- return parsed.results.map((i) => ({ id: i.id, path: i.path, ebookFormat: i.media?.ebookFormat ?? null }));
39
+ return parsed.results.map((i) => ({
40
+ id: i.id,
41
+ path: i.path,
42
+ ebookFormat: i.media?.ebookFormat ?? null,
43
+ title: i.media?.metadata?.title ?? null,
44
+ author: i.media?.metadata?.authorName ?? null,
45
+ addedAt: i.addedAt ?? null,
46
+ }));
34
47
  }
35
48
  async sendEbook(libraryItemId, deviceName) {
36
49
  await this.request('/api/emails/send-ebook-to-device', {
@@ -50,6 +50,9 @@ const editionSchema = z.object({
50
50
  language: z.string().nullish(),
51
51
  monitored: z.boolean(),
52
52
  narrators: z.array(z.object({ name: z.string() })).nullish(),
53
+ ratings: z.object({ value: z.number().nullish(), votes: z.number().nullish() }).nullish(),
54
+ durationSeconds: z.number().nullish(),
55
+ releaseDate: z.string().nullish(),
53
56
  });
54
57
  const rawSchema = z.record(z.string(), z.unknown());
55
58
  const commandSchema = z.object({ id: z.number(), status: z.string(), queued: z.string() });
@@ -208,6 +211,10 @@ export class ChaptarrClient {
208
211
  language: e.language ?? null,
209
212
  monitored: e.monitored,
210
213
  narrators: (e.narrators ?? []).map((n) => n.name),
214
+ rating: e.ratings?.value ?? null,
215
+ votes: e.ratings?.votes ?? null,
216
+ durationSeconds: e.durationSeconds != null && e.durationSeconds > 0 ? e.durationSeconds : null,
217
+ releaseDate: e.releaseDate ?? null,
211
218
  }));
212
219
  }
213
220
  async monitorEdition(bookId, editionId) {
@@ -9,6 +9,8 @@ const DAY_MS = 86_400_000;
9
9
  const UNWANTED_REJECTION = /not wanted in profile|not enough seeders/i;
10
10
  const SAB_FORCE_PRIORITY = 2;
11
11
  const RUNNING_COMMAND = new Set(['queued', 'started']);
12
+ const NARRATOR_CHOICES = 5;
13
+ const AUDIO_FORMAT_RANK = { M4B: 3, FLAC: 2, MP3: 2 };
12
14
  const SEARCH_TIMING = { waitMs: 120_000, pollMs: 3_000 };
13
15
  function chaptarr(config) {
14
16
  if (config.chaptarr === undefined)
@@ -95,13 +97,84 @@ export function plainEdition(editions) {
95
97
  current.title.startsWith(`${e.title} (`));
96
98
  return plain.sort((a, b) => a.title.length - b.title.length)[0] ?? null;
97
99
  }
100
+ function monitoring(editions, editionId) {
101
+ return editions.map((e) => ({ ...e, monitored: e.id === editionId }));
102
+ }
98
103
  async function ensureBook(client, lookup, format, opts) {
99
104
  const local = preferred(lookup[format]);
100
105
  const id = local?.id ?? (await client.addBook(lookup, format, await client.formatDefaults(), opts));
101
- const plain = plainEdition(await client.editions(id));
102
- if (plain !== null)
106
+ let editions = await client.editions(id);
107
+ const chosen = opts.editionId === undefined ? undefined : editions.find((e) => e.id === opts.editionId);
108
+ if (opts.editionId !== undefined && chosen === undefined) {
109
+ throw new Error(`edition ${opts.editionId} is not an edition of ${lookup.title}`);
110
+ }
111
+ if (chosen !== undefined && !chosen.monitored) {
112
+ await client.monitorEdition(id, chosen.id);
113
+ editions = monitoring(editions, chosen.id);
114
+ }
115
+ const plain = plainEdition(editions);
116
+ if (plain !== null) {
103
117
  await client.monitorEdition(id, plain.id);
104
- return id;
118
+ editions = monitoring(editions, plain.id);
119
+ }
120
+ return { id, editions };
121
+ }
122
+ function narratorKey(narrators) {
123
+ return narrators
124
+ .map((n) => n.toLowerCase())
125
+ .sort()
126
+ .join('|');
127
+ }
128
+ function releaseYear(date) {
129
+ if (date === null)
130
+ return null;
131
+ const time = Date.parse(date);
132
+ return Number.isNaN(time) ? null : new Date(time).getUTCFullYear();
133
+ }
134
+ function editionOrder(a, b) {
135
+ return ((b.votes ?? 0) - (a.votes ?? 0) ||
136
+ Number(b.durationSeconds !== null) - Number(a.durationSeconds !== null) ||
137
+ (b.releaseDate ?? '').localeCompare(a.releaseDate ?? ''));
138
+ }
139
+ export function narratorChoices(editions, limit = NARRATOR_CHOICES) {
140
+ const current = editions.find((e) => e.monitored);
141
+ const currentKey = current === undefined ? null : narratorKey(current.narrators);
142
+ const groups = new Map();
143
+ for (const e of editions) {
144
+ if (e.narrators.length === 0)
145
+ continue;
146
+ const key = narratorKey(e.narrators);
147
+ groups.set(key, [...(groups.get(key) ?? []), e]);
148
+ }
149
+ return [...groups.entries()]
150
+ .flatMap(([key, group]) => {
151
+ const best = [...group].sort(editionOrder)[0];
152
+ const duration = group.find((e) => e.durationSeconds !== null)?.durationSeconds ?? null;
153
+ return best === undefined ? [] : [{ key, best, duration }];
154
+ })
155
+ .sort((a, b) => editionOrder(a.best, b.best))
156
+ .slice(0, limit)
157
+ .map(({ key, best, duration }) => ({
158
+ edition_id: best.id,
159
+ narrators: best.narrators,
160
+ year: releaseYear(best.releaseDate),
161
+ duration_seconds: best.durationSeconds ?? duration,
162
+ rating: best.rating,
163
+ votes: best.votes,
164
+ language: best.language,
165
+ chosen: key === currentKey,
166
+ }));
167
+ }
168
+ function narrationOf(editions) {
169
+ const current = editions.find((e) => e.monitored);
170
+ if (current === undefined)
171
+ return { narrators: [], seconds: null };
172
+ const key = narratorKey(current.narrators);
173
+ const seconds = current.durationSeconds ??
174
+ editions.find((e) => e.durationSeconds !== null && current.narrators.length > 0 && narratorKey(e.narrators) === key)
175
+ ?.durationSeconds ??
176
+ null;
177
+ return { narrators: current.narrators, seconds };
105
178
  }
106
179
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
107
180
  async function searchOutcome(client, bookId, timing) {
@@ -153,7 +226,7 @@ export async function addBook(config, foreignBookId, format, timing = SEARCH_TIM
153
226
  result = { book_id: local.id, title: lookup.title, status: 'downloading', detail: null };
154
227
  }
155
228
  else {
156
- const id = await ensureBook(client, lookup, format, { monitored: true, search: false });
229
+ const { id } = await ensureBook(client, lookup, format, { monitored: true, search: false });
157
230
  await client.setMonitored([id], true);
158
231
  const title = (await client.book(id)).title;
159
232
  result = { book_id: id, title, ...(await searchOutcome(client, id, timing)) };
@@ -171,11 +244,43 @@ function ageDays(publishDate, now) {
171
244
  const time = Date.parse(publishDate);
172
245
  return Number.isNaN(time) ? null : Math.max(0, Math.floor((now - time) / DAY_MS));
173
246
  }
174
- export function selectReleases(releases, limit, now = Date.now()) {
175
- return releases
247
+ function words(text) {
248
+ return text
249
+ .normalize('NFKD')
250
+ .replace(/\p{M}/gu, '')
251
+ .toLowerCase()
252
+ .split(/[^a-z0-9]+/)
253
+ .filter((w) => w.length > 0);
254
+ }
255
+ export function narratorMatch(title, narrators) {
256
+ const inTitle = new Set(words(title));
257
+ return narrators.some((name) => {
258
+ const surname = words(name).at(-1);
259
+ return surname !== undefined && surname.length >= 3 && inTitle.has(surname);
260
+ });
261
+ }
262
+ export function estimateKbps(size, seconds) {
263
+ if (size === null || seconds === null || seconds <= 0)
264
+ return null;
265
+ return Math.round((size * 8) / seconds / 1000);
266
+ }
267
+ export function selectReleases(releases, limit, now = Date.now(), narration = null) {
268
+ const wanted = releases
176
269
  .filter((r) => !r.rejections.some((reason) => UNWANTED_REJECTION.test(reason)))
177
- .slice(0, limit)
178
- .map((r, i) => ({
270
+ .map((r, order) => ({
271
+ r,
272
+ order,
273
+ narrator_match: narration !== null && narratorMatch(r.title, narration.narrators),
274
+ kbps: narration === null ? null : estimateKbps(r.size, narration.seconds),
275
+ format: r.quality === null ? 0 : (AUDIO_FORMAT_RANK[r.quality] ?? 1),
276
+ }));
277
+ const ranked = narration === null
278
+ ? wanted
279
+ : [...wanted].sort((a, b) => Number(b.narrator_match) - Number(a.narrator_match) ||
280
+ b.format - a.format ||
281
+ (b.kbps ?? -1) - (a.kbps ?? -1) ||
282
+ a.order - b.order);
283
+ return ranked.slice(0, limit).map(({ r, narrator_match, kbps }, i) => ({
179
284
  rank: i + 1,
180
285
  title: r.title,
181
286
  size: r.size,
@@ -187,6 +292,8 @@ export function selectReleases(releases, limit, now = Date.now()) {
187
292
  guid: r.guid,
188
293
  indexer_id: r.indexerId,
189
294
  rejections: r.rejections,
295
+ narrator_match,
296
+ kbps,
190
297
  }));
191
298
  }
192
299
  export async function bookReleases(config, foreignBookId, format, opts) {
@@ -194,14 +301,94 @@ export async function bookReleases(config, foreignBookId, format, opts) {
194
301
  const lookup = await findFormat(client, foreignBookId, format);
195
302
  if (lookup === null)
196
303
  throw new Error(`no book ${foreignBookId} in Chaptarr's lookup`);
197
- const id = await ensureBook(client, lookup, format, { monitored: false, search: false });
304
+ const { id, editions } = await ensureBook(client, lookup, format, {
305
+ monitored: false,
306
+ search: false,
307
+ editionId: opts.editionId,
308
+ });
198
309
  const title = (await client.book(id)).title;
199
- const releases = selectReleases(await client.releases(id), opts.maxEntries ?? config.defaults.maxEntries);
310
+ const narration = format === 'audiobook' ? narrationOf(editions) : null;
311
+ const limit = opts.maxEntries ?? config.defaults.maxEntries;
312
+ const releases = selectReleases(await client.releases(id), limit, Date.now(), narration);
200
313
  return {
201
- output: { foreign_book_id: foreignBookId, format, book_id: id, title, releases },
314
+ output: {
315
+ foreign_book_id: foreignBookId,
316
+ format,
317
+ book_id: id,
318
+ title,
319
+ narrators: narration?.narrators ?? [],
320
+ duration_seconds: narration?.seconds ?? null,
321
+ releases,
322
+ },
202
323
  warnings: [],
203
324
  };
204
325
  }
326
+ export async function bookNarrators(config, foreignBookId, opts) {
327
+ const client = chaptarr(config);
328
+ const lookup = await findFormat(client, foreignBookId, 'audiobook');
329
+ if (lookup === null)
330
+ throw new Error(`no book ${foreignBookId} in Chaptarr's lookup`);
331
+ const { id, editions } = await ensureBook(client, lookup, 'audiobook', { monitored: false, search: false });
332
+ const title = (await client.book(id)).title;
333
+ return {
334
+ output: {
335
+ foreign_book_id: foreignBookId,
336
+ book_id: id,
337
+ title,
338
+ narrators: narratorChoices(editions, opts.maxEntries ?? NARRATOR_CHOICES),
339
+ },
340
+ warnings: [],
341
+ };
342
+ }
343
+ export async function bestBook(config, foreignBookId, format, opts) {
344
+ const client = chaptarr(config);
345
+ const warnings = [];
346
+ const base = { foreign_book_id: foreignBookId, format };
347
+ let result;
348
+ try {
349
+ const lookup = await findFormat(client, foreignBookId, format);
350
+ const local = lookup === null ? null : preferred(lookup[format]);
351
+ if (lookup === null) {
352
+ result = { book_id: null, title: null, status: 'not_found', detail: null, release: null };
353
+ }
354
+ else if (local?.hasFiles === true) {
355
+ result = { book_id: local.id, title: lookup.title, status: 'already_exists', detail: null, release: null };
356
+ }
357
+ else if (local !== null && (await client.queuedBookIds()).has(local.id)) {
358
+ result = { book_id: local.id, title: lookup.title, status: 'downloading', detail: null, release: null };
359
+ }
360
+ else {
361
+ const { id, editions } = await ensureBook(client, lookup, format, {
362
+ monitored: false,
363
+ search: false,
364
+ editionId: opts.editionId,
365
+ });
366
+ const title = (await client.book(id)).title;
367
+ const narration = format === 'audiobook' ? narrationOf(editions) : null;
368
+ const found = await client.releases(id);
369
+ const pick = selectReleases(found, found.length, Date.now(), narration).find((r) => r.rejections.length === 0);
370
+ await client.setMonitored([id], true);
371
+ if (pick === undefined) {
372
+ result = { book_id: id, title, status: 'nothing_found', detail: null, release: null };
373
+ }
374
+ else {
375
+ await client.grab(pick.guid, pick.indexer_id);
376
+ const release = {
377
+ title: pick.title,
378
+ quality: pick.quality,
379
+ kbps: pick.kbps,
380
+ narrator_match: pick.narrator_match,
381
+ };
382
+ result = { book_id: id, title, status: 'downloading', detail: null, release };
383
+ }
384
+ }
385
+ }
386
+ catch (err) {
387
+ result = { book_id: null, title: null, status: 'error', detail: httpDetail(err), release: null };
388
+ }
389
+ const sabnzbd_paused = await sabPausedFor(config, client, format, warnings);
390
+ return { output: { ...base, ...result, sabnzbd_paused }, warnings };
391
+ }
205
392
  export async function grabRelease(config, bookId, guid, indexerId) {
206
393
  const client = chaptarr(config);
207
394
  const warnings = [];
@@ -266,3 +453,31 @@ export async function sendBook(config, bookId, device) {
266
453
  return { output: { ...base, title, status: 'error', detail: httpDetail(err) }, warnings: [] };
267
454
  }
268
455
  }
456
+ export async function listEbooks(config) {
457
+ const abs = audiobookshelf(config);
458
+ const found = [];
459
+ for (const library of (await abs.libraries()).filter((l) => l.mediaType === 'book')) {
460
+ for (const i of await abs.items(library.id)) {
461
+ if (i.ebookFormat === null)
462
+ continue;
463
+ const added_at = i.addedAt === null ? null : new Date(i.addedAt).toISOString();
464
+ found.push({ item: { item_id: i.id, title: i.title ?? i.path, author: i.author, added_at }, addedAt: i.addedAt ?? 0 });
465
+ }
466
+ }
467
+ const ebooks = found.sort((a, b) => b.addedAt - a.addedAt).map((f) => f.item);
468
+ return { output: { ebooks, kindles: await abs.ereaderDevices() }, warnings: [] };
469
+ }
470
+ export async function sendItem(config, itemId, device) {
471
+ const abs = audiobookshelf(config);
472
+ const base = { item_id: itemId, device };
473
+ try {
474
+ if (!(await abs.ereaderDevices()).includes(device)) {
475
+ return { output: { ...base, status: 'unknown_device', detail: null }, warnings: [] };
476
+ }
477
+ await abs.sendEbook(itemId, device);
478
+ return { output: { ...base, status: 'sent', detail: null }, warnings: [] };
479
+ }
480
+ catch (err) {
481
+ return { output: { ...base, status: 'error', detail: httpDetail(err) }, warnings: [] };
482
+ }
483
+ }
package/dist/format.js CHANGED
@@ -126,13 +126,37 @@ export function renderBookAdd(output) {
126
126
  function megabytes(size) {
127
127
  return size === null ? '-' : `${Math.round(size / 1_048_576)} MB`;
128
128
  }
129
+ function hours(seconds) {
130
+ if (seconds === null)
131
+ return '-';
132
+ const minutes = Math.round(seconds / 60);
133
+ return `${Math.floor(minutes / 60)} h ${String(minutes % 60).padStart(2, '0')}`;
134
+ }
129
135
  export function renderReleasesTable(output) {
130
- const title = `${output.title} [${output.format}] book ${output.book_id}`;
136
+ const narration = output.narrators.length > 0 ? ` · ${output.narrators.join(', ')} · ${hours(output.duration_seconds)}` : '';
137
+ const title = `${output.title} [${output.format}] book ${output.book_id}${narration}`;
131
138
  if (output.releases.length === 0)
132
139
  return `${title}\nNo releases.`;
133
- const header = `${cell('#', 3)} ${cell('RELEASE', 60)} ${cell('SIZE', 9)} ${cell('QUALITY', 13)} ${cell('SEEDS', 5)} AGE`;
134
- const rows = output.releases.map((r) => `${cell(String(r.rank), 3)} ${cell(r.title, 60)} ${cell(megabytes(r.size), 9)} ${cell(dash(r.quality), 13)} ${cell(r.protocol === 'usenet' ? 'nzb' : dash(r.seeders), 5)} ${r.age_days === null ? '-' : `${r.age_days}d`}`);
135
- return [title, pc.bold(header), ...rows].join('\n');
140
+ const header = `${cell('#', 3)} ${cell('RELEASE', 60)} ${cell('SIZE', 9)} ${cell('QUALITY', 13)} ${cell('KBPS', 5)} ${cell('SEEDS', 5)} AGE`;
141
+ const rows = output.releases.map((r) => `${cell(String(r.rank), 3)} ${cell(`${r.narrator_match ? '* ' : ''}${r.title}`, 60)} ${cell(megabytes(r.size), 9)} ${cell(dash(r.quality), 13)} ${cell(dash(r.kbps), 5)} ${cell(r.protocol === 'usenet' ? 'nzb' : dash(r.seeders), 5)} ${r.age_days === null ? '-' : `${r.age_days}d`}`);
142
+ const note = output.releases.some((r) => r.narrator_match) ? ['* names the narrator'] : [];
143
+ return [title, pc.bold(header), ...rows, ...note].join('\n');
144
+ }
145
+ export function renderNarrators(output) {
146
+ const title = `${output.title} [audiobook] book ${output.book_id}`;
147
+ if (output.narrators.length === 0)
148
+ return `${title}\nNo narrator known.`;
149
+ const header = `${cell('EDITION', 8)} ${cell('NARRATORS', 40)} ${cell('YEAR', 4)} ${cell('LENGTH', 8)} ${cell('RATING', 6)} VOTES`;
150
+ const rows = output.narrators.map((n) => `${cell(String(n.edition_id), 8)} ${cell(`${n.chosen ? '* ' : ''}${n.narrators.join(', ')}`, 40)} ${cell(dash(n.year), 4)} ${cell(hours(n.duration_seconds), 8)} ${cell(n.rating === null ? '-' : n.rating.toFixed(2), 6)} ${dash(n.votes)}`);
151
+ return [title, pc.bold(header), ...rows, '* monitored now'].join('\n');
152
+ }
153
+ export function renderBookBest(output) {
154
+ const detail = output.detail === null ? '' : ` (${output.detail})`;
155
+ const line = `${output.title ?? output.foreign_book_id} [${output.format}] ${statusColor(output.status, ['downloading'])}${detail}`;
156
+ const release = output.release === null
157
+ ? []
158
+ : [`Release: ${output.release.title} (${dash(output.release.quality)}, ${dash(output.release.kbps)} kbps)`];
159
+ return [line, ...release, '', sabLine(output.sabnzbd_paused)].join('\n');
136
160
  }
137
161
  export function renderBookGrab(output) {
138
162
  const detail = output.detail === null ? '' : ` (${output.detail})`;
@@ -148,3 +172,15 @@ export function renderBookReady(output) {
148
172
  const kindles = output.kindles.length === 0 ? '' : `\nKindles: ${output.kindles.join(', ')}`;
149
173
  return `${output.title} [${output.format}] ${file}${abs}${kindles}`;
150
174
  }
175
+ export function renderEbookList(output) {
176
+ if (output.ebooks.length === 0)
177
+ return 'No ebooks.';
178
+ const header = `${cell('TITLE', 44)} ${cell('AUTHOR', 24)} ${cell('ADDED', 10)} ITEM`;
179
+ const rows = output.ebooks.map((e) => `${cell(e.title, 44)} ${cell(dash(e.author), 24)} ${cell(e.added_at?.slice(0, 10) ?? '-', 10)} ${e.item_id}`);
180
+ const kindles = output.kindles.length === 0 ? 'Kindles: none' : `Kindles: ${output.kindles.join(', ')}`;
181
+ return [pc.bold(header), ...rows, '', kindles].join('\n');
182
+ }
183
+ export function renderItemSend(output) {
184
+ const detail = output.detail === null ? '' : ` (${output.detail})`;
185
+ return `${output.item_id} → ${output.device}: ${statusColor(output.status, ['sent'])}${detail}`;
186
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/trendarr",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "TMDB trending → OMDb ratings → Radarr/Sonarr adds → SABnzbd control, from the terminal",
5
5
  "scripts": {
6
6
  "build": "tsc -p tsconfig.build.json && chmod +x dist/cli.js",