@astrofoundry/trendarr 0.6.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 ADDED
@@ -0,0 +1,31 @@
1
+ # trendarr
2
+
3
+ TMDB weekly trending in the terminal โ€” IMDb ratings via OMDb, Radarr/Sonarr library flags and adds, SABnzbd queue control.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add -g @astrofoundry/trendarr
9
+ ```
10
+
11
+ Node 24+. Run `trendarr init` once โ€” prompts for TMDB API Read Access Token (themoviedb.org/settings/api), OMDb, Radarr, Sonarr, and SABnzbd credentials, validates each live, and saves to `~/.trendarr/config.json` (mode 600). No environment variables.
12
+
13
+ ## Commands
14
+
15
+ ```bash
16
+ trendarr trending [--max-entries 10] [--type movies|series] [--min-rating 6.5] [--json|--discord]
17
+ trendarr search <query> [--max-entries 10] [--type movies|series] [--json|--discord]
18
+ trendarr add-movies <imdbIds...> [--json]
19
+ trendarr add-series <imdbIds...> [--json]
20
+ trendarr sabnzbd status|pause|resume|unpause [--json]
21
+ ```
22
+
23
+ `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.
24
+
25
+ ## Development
26
+
27
+ ```bash
28
+ pnpm check # typecheck, lint, tests
29
+ pnpm build
30
+ pnpm release:patch # or release:minor / release:major
31
+ ```
package/dist/cli.js ADDED
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { Command, InvalidArgumentError } from 'commander';
4
+ import { addMovies, addSeries, hasFailure } from './commands/add.js';
5
+ import { runInit } from './commands/init.js';
6
+ import { runSabnzbd } from './commands/sabnzbd.js';
7
+ import { getSearch } from './commands/search.js';
8
+ import { getTrending } from './commands/trending.js';
9
+ import { ConfigError, loadConfig } from './config.js';
10
+ import { renderAddTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
11
+ import { describeError } from './http.js';
12
+ const pkg = createRequire(import.meta.url)('../package.json');
13
+ const program = new Command();
14
+ function parsePositiveInt(value) {
15
+ const n = Number(value);
16
+ if (!Number.isInteger(n) || n <= 0)
17
+ throw new InvalidArgumentError('must be a positive integer');
18
+ return n;
19
+ }
20
+ function parseType(value) {
21
+ if (value === 'movies' || value === 'series')
22
+ return value;
23
+ throw new InvalidArgumentError("must be 'movies' or 'series'");
24
+ }
25
+ function parseRating(value) {
26
+ const n = Number(value);
27
+ if (!Number.isFinite(n) || n < 0 || n > 10)
28
+ throw new InvalidArgumentError('must be a number between 0 and 10');
29
+ return n;
30
+ }
31
+ function fail(err) {
32
+ process.stderr.write(`${err instanceof ConfigError ? err.message : describeError(err)}\n`);
33
+ process.exit(1);
34
+ }
35
+ function printWarnings(warnings) {
36
+ for (const warning of warnings)
37
+ process.stderr.write(`warning: ${warning}\n`);
38
+ }
39
+ program
40
+ .name('trendarr')
41
+ .description('TMDB trending, IMDb ratings via OMDb, Radarr/Sonarr adds, and SABnzbd control from the terminal.')
42
+ .version(pkg.version)
43
+ .showHelpAfterError('(run "trendarr --help" for usage)')
44
+ .addHelpText('after', `
45
+ Setup:
46
+ Run "trendarr init" once. Credentials are saved to ~/.trendarr/config.json (chmod 600).
47
+ The tool never reads environment variables.
48
+
49
+ Output and exit codes:
50
+ Every command prints a human-readable table by default, or machine JSON with --json.
51
+ JSON is written to stdout; warnings and errors go to stderr. Exit code is 1 on failure.
52
+
53
+ Commands:
54
+ init Interactive setup with live credential validation.
55
+ trending Trending movies and series (TMDB, weekly) with IMDb ratings and a library flag.
56
+ search <query> Search movies and series by name (full or partial).
57
+ add-movies <imdbIds...> Add movies to Radarr by IMDb id and start a search.
58
+ add-series <imdbIds...> Add series to Sonarr by IMDb id and start a search.
59
+ sabnzbd <action> Read or toggle the SABnzbd queue pause state.
60
+
61
+ Run "trendarr <command> --help" for that command's parameters and output shape.`);
62
+ program
63
+ .command('init')
64
+ .description('guided setup: credentials, validation, defaults')
65
+ .addHelpText('after', `
66
+ Prompts for TMDB, OMDb, Radarr, Sonarr, and SABnzbd credentials and validates each live.
67
+ Lets you pick the default Radarr/Sonarr quality profile and root folder, and the Sonarr
68
+ monitor mode. Writes ~/.trendarr/config.json (chmod 600). Re-run to update; existing values
69
+ are prefilled. Takes no parameters.`)
70
+ .action(async () => {
71
+ await runInit().catch(fail);
72
+ });
73
+ program
74
+ .command('trending')
75
+ .description('trending movies and series (TMDB weekly) with IMDb ratings and in-library flag')
76
+ .option('--max-entries <n>', 'results per media type', parsePositiveInt)
77
+ .option('--type <type>', "'movies' or 'series'", parseType)
78
+ .option('--min-rating <n>', 'drop movies below this IMDb rating (0-10)', parseRating)
79
+ .option('--json', 'output JSON')
80
+ .option('--discord', 'output Discord markdown (masked IMDb links, โœ…/โŒ library flags)')
81
+ .addHelpText('after', `
82
+ Parameters:
83
+ --max-entries <n> Results per media type (positive integer). Default: 10 (config defaults.maxEntries).
84
+ --type <type> Restrict to "movies" or "series". Default: both.
85
+ --min-rating <n> Drop movies with an IMDb rating below <n> (0-10). Movies with no IMDb rating
86
+ are kept; series are not filtered. Default: 6.5. Use 0 to disable.
87
+ --json Output JSON instead of the table.
88
+ --discord Output Discord markdown: "{rank}. [Title (year)](<imdb url>) โ€” {rating} ยท ๐Ÿ”ฅ{popularity}"
89
+ with masked links whose URL is wrapped in <> so it never unfurls a preview,
90
+ โœ… in library / โŒ not / โ“ arr unreachable. If both --json and --discord are given, --json wins.
91
+
92
+ Output (table): a MOVIES block then a SERIES block, each ordered by TMDB weekly trending rank.
93
+ Columns: # rank, TITLE, YEAR, POP (TMDB popularity, rounded), IMDB (rating), LIB (library: check /
94
+ blank / ? when Radarr or Sonarr is unreachable), LINK (IMDb URL).
95
+ Output (--json): { "movies": TrendingItem[], "series": TrendingItem[] }
96
+ TrendingItem: { rank, title, year, popularity, imdb_rating, imdb_votes,
97
+ rotten_tomatoes, metascore, genres, imdb_id, tmdb_id, tvdb_id, in_library }
98
+ Ratings are strings or null. popularity is the raw TMDB float. in_library is true/false, or null
99
+ when the arr server is unreachable.
100
+
101
+ Examples:
102
+ trendarr trending
103
+ trendarr trending --type movies --min-rating 7 --max-entries 20
104
+ trendarr trending --json
105
+ trendarr trending --discord`)
106
+ .action(async (opts) => {
107
+ try {
108
+ const config = loadConfig();
109
+ const { output, warnings } = await getTrending(config, opts);
110
+ printWarnings(warnings);
111
+ const rendered = opts.json === true
112
+ ? toJson(output)
113
+ : opts.discord === true
114
+ ? renderTrendingDiscord(output)
115
+ : renderTrendingTable(output);
116
+ process.stdout.write(`${rendered}\n`);
117
+ }
118
+ catch (err) {
119
+ fail(err);
120
+ }
121
+ });
122
+ program
123
+ .command('search')
124
+ .description('search TMDB for movies and series by name (full or partial)')
125
+ .argument('<query>', 'title to search for, e.g. "breaking bad"')
126
+ .option('--max-entries <n>', 'results per media type', parsePositiveInt)
127
+ .option('--type <type>', "'movies' or 'series'", parseType)
128
+ .option('--json', 'output JSON')
129
+ .option('--discord', 'output Discord markdown')
130
+ .addHelpText('after', `
131
+ Parameters:
132
+ <query> Title to search, full or partial (e.g. "dune", "breaking"). Quote multi-word queries.
133
+ --max-entries <n> Results per media type (positive integer). Default: 10 (config defaults.maxEntries).
134
+ --type <type> Restrict to "movies" or "series". Default: both.
135
+ --json Output JSON instead of the table.
136
+ --discord Output Discord markdown (same format as trending, without popularity).
137
+ If both --json and --discord are given, --json wins.
138
+
139
+ Output (table): a MOVIES block then a SERIES block, ordered by TMDB search relevance.
140
+ Columns: # rank, TITLE, YEAR, IMDB (rating), LIB (library: check / blank / ? if arr unreachable), LINK.
141
+ Output (--json): { "movies": MediaItem[], "series": MediaItem[] }
142
+ MediaItem: { rank, title, year, imdb_rating, imdb_votes, rotten_tomatoes,
143
+ metascore, genres, imdb_id, tmdb_id, tvdb_id, in_library }
144
+ Same shape as trending items minus "popularity". Use the imdb_id with add-movies/add-series.
145
+
146
+ Examples:
147
+ trendarr search dune
148
+ trendarr search "breaking bad" --type series
149
+ trendarr search weapons --json`)
150
+ .action(async (query, opts) => {
151
+ try {
152
+ const config = loadConfig();
153
+ const { output, warnings } = await getSearch(config, query, opts);
154
+ printWarnings(warnings);
155
+ const rendered = opts.json === true
156
+ ? toJson(output)
157
+ : opts.discord === true
158
+ ? renderSearchDiscord(output)
159
+ : renderSearchTable(output);
160
+ process.stdout.write(`${rendered}\n`);
161
+ }
162
+ catch (err) {
163
+ fail(err);
164
+ }
165
+ });
166
+ function addAction(kind) {
167
+ return async (ids, opts) => {
168
+ try {
169
+ const config = loadConfig();
170
+ const run = kind === 'movies' ? addMovies : addSeries;
171
+ const { output, warnings } = await run(config, ids);
172
+ printWarnings(warnings);
173
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderAddTable(output)}\n`);
174
+ if (hasFailure(output))
175
+ process.exitCode = 1;
176
+ }
177
+ catch (err) {
178
+ fail(err);
179
+ }
180
+ };
181
+ }
182
+ program
183
+ .command('add-movies')
184
+ .description('add movies to Radarr by IMDb id and search')
185
+ .argument('<imdbIds...>', 'IMDb ids, e.g. tt1160419')
186
+ .option('--json', 'output JSON')
187
+ .addHelpText('after', `
188
+ Parameters:
189
+ <imdbIds...> One or more IMDb ids (e.g. tt1160419). Commas and surrounding spaces are tolerated.
190
+ --json Output JSON instead of the table.
191
+
192
+ Behavior: each id is looked up in Radarr and added monitored with a search triggered, using the
193
+ quality profile and root folder chosen during init. Ids already in the library report
194
+ already_exists. The batch continues past per-item failures.
195
+
196
+ Output (--json): { "results": AddResult[], "sabnzbd_paused": boolean | null }
197
+ AddResult: { imdb_id, title, status, detail }
198
+ status is one of: added | already_exists | not_found | error.
199
+ Exit code is 1 if any id is not_found or error.
200
+
201
+ Examples:
202
+ trendarr add-movies tt1160419
203
+ trendarr add-movies tt1160419 tt0468569 --json`)
204
+ .action(addAction('movies'));
205
+ program
206
+ .command('add-series')
207
+ .description('add series to Sonarr by IMDb id and search')
208
+ .argument('<imdbIds...>', 'IMDb ids, e.g. tt0903747')
209
+ .option('--json', 'output JSON')
210
+ .addHelpText('after', `
211
+ Parameters:
212
+ <imdbIds...> One or more IMDb ids (e.g. tt0903747). Commas and surrounding spaces are tolerated.
213
+ --json Output JSON instead of the table.
214
+
215
+ Behavior: each IMDb id is resolved to a TVDB id via TMDB, then added to Sonarr monitored with a
216
+ search triggered, using the quality profile, root folder, and monitor mode chosen during init.
217
+ Ids already in the library report already_exists. The batch continues past per-item failures.
218
+
219
+ Output: same shape as add-movies. Exit code is 1 if any id is not_found or error.
220
+
221
+ Examples:
222
+ trendarr add-series tt0903747
223
+ trendarr add-series tt0903747 tt0944947 --json`)
224
+ .action(addAction('series'));
225
+ program
226
+ .command('sabnzbd')
227
+ .description('SABnzbd queue pause control')
228
+ .argument('<action>', 'status | pause | resume | unpause')
229
+ .option('--json', 'output JSON')
230
+ .addHelpText('after', `
231
+ Parameters:
232
+ <action> status (read only), pause, resume, or unpause (alias of resume).
233
+ --json Output JSON instead of a line.
234
+
235
+ Output (table): "SABnzbd paused: yes" or "SABnzbd paused: no".
236
+ Output (--json): { "sabnzbd_paused": boolean }
237
+ pause, resume, and unpause perform the action then report the resulting state.
238
+
239
+ Examples:
240
+ trendarr sabnzbd status
241
+ trendarr sabnzbd pause --json`)
242
+ .action(async (action, opts) => {
243
+ if (!['status', 'pause', 'resume', 'unpause'].includes(action)) {
244
+ process.stderr.write('action must be one of: status, pause, resume, unpause\n');
245
+ process.exit(1);
246
+ }
247
+ try {
248
+ const config = loadConfig();
249
+ const result = await runSabnzbd(config, action);
250
+ process.stdout.write(`${opts.json === true ? toJson(result) : renderSabStatus(result.sabnzbd_paused)}\n`);
251
+ }
252
+ catch (err) {
253
+ fail(err);
254
+ }
255
+ });
256
+ if (process.argv.slice(2).length === 0) {
257
+ program.outputHelp();
258
+ process.exit(0);
259
+ }
260
+ await program.parseAsync();
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+ import { HttpError, fetchJson } from '../http.js';
3
+ const statusSchema = z.object({ appName: z.string(), version: z.string() });
4
+ const profilesSchema = z.array(z.object({ id: z.number(), name: z.string() }));
5
+ const rootFoldersSchema = z.array(z.object({ path: z.string() }));
6
+ const lookupSchema = z.object({ id: z.number().default(0), title: z.string() });
7
+ const validationErrorsSchema = z.array(z.object({ errorMessage: z.string().nullish() }));
8
+ export class ArrClient {
9
+ baseUrl;
10
+ apiKey;
11
+ constructor(baseUrl, apiKey) {
12
+ this.baseUrl = baseUrl;
13
+ this.apiKey = apiKey;
14
+ }
15
+ getJson(path) {
16
+ return fetchJson(`${this.baseUrl}${path}`, { headers: { 'X-Api-Key': this.apiKey } });
17
+ }
18
+ postJson(path, body) {
19
+ return fetchJson(`${this.baseUrl}${path}`, {
20
+ method: 'POST',
21
+ headers: { 'X-Api-Key': this.apiKey },
22
+ body,
23
+ });
24
+ }
25
+ async systemStatus() {
26
+ return statusSchema.parse(await this.getJson('/api/v3/system/status'));
27
+ }
28
+ async qualityProfiles() {
29
+ return profilesSchema.parse(await this.getJson('/api/v3/qualityprofile'));
30
+ }
31
+ async rootFolders() {
32
+ return rootFoldersSchema.parse(await this.getJson('/api/v3/rootfolder'));
33
+ }
34
+ toLookup(value) {
35
+ const first = Array.isArray(value) ? value[0] : value;
36
+ if (first === undefined || first === null || typeof first !== 'object')
37
+ return null;
38
+ const parsed = lookupSchema.safeParse(first);
39
+ if (!parsed.success)
40
+ return null;
41
+ return { id: parsed.data.id, title: parsed.data.title, raw: first };
42
+ }
43
+ mapAddError(err) {
44
+ if (err instanceof HttpError && err.status === 400) {
45
+ const parsed = validationErrorsSchema.safeParse(err.body);
46
+ const detail = parsed.success
47
+ ? parsed.data.map((e) => e.errorMessage ?? '').filter((m) => m.length > 0).join('; ')
48
+ : '';
49
+ if (detail.toLowerCase().includes('already'))
50
+ return { status: 'already_exists', detail };
51
+ return { status: 'error', detail: detail.length > 0 ? detail : 'validation failed' };
52
+ }
53
+ throw err;
54
+ }
55
+ }
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { fetchJson } from '../http.js';
3
+ const responseSchema = z.object({
4
+ Response: z.string(),
5
+ imdbRating: z.string().nullish(),
6
+ imdbVotes: z.string().nullish(),
7
+ Metascore: z.string().nullish(),
8
+ Ratings: z.array(z.object({ Source: z.string(), Value: z.string() })).nullish(),
9
+ });
10
+ function clean(value) {
11
+ return value === undefined || value === null || value === 'N/A' ? null : value;
12
+ }
13
+ export class OmdbClient {
14
+ apiKey;
15
+ constructor(apiKey) {
16
+ this.apiKey = apiKey;
17
+ }
18
+ async byImdbId(imdbId) {
19
+ try {
20
+ const raw = await fetchJson(`https://www.omdbapi.com/?apikey=${encodeURIComponent(this.apiKey)}&i=${encodeURIComponent(imdbId)}`);
21
+ const parsed = responseSchema.safeParse(raw);
22
+ if (!parsed.success || parsed.data.Response !== 'True')
23
+ return null;
24
+ const rt = parsed.data.Ratings?.find((r) => r.Source === 'Rotten Tomatoes')?.Value ?? null;
25
+ return {
26
+ imdbRating: clean(parsed.data.imdbRating),
27
+ imdbVotes: clean(parsed.data.imdbVotes),
28
+ rottenTomatoes: clean(rt),
29
+ metascore: clean(parsed.data.Metascore),
30
+ };
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,29 @@
1
+ import { z } from 'zod';
2
+ import { ArrClient } from './arr.js';
3
+ const librarySchema = z.array(z.object({ tmdbId: z.number().nullish() }));
4
+ export class RadarrClient extends ArrClient {
5
+ async lookupByImdb(imdbId) {
6
+ const raw = await this.getJson(`/api/v3/movie/lookup/imdb?imdbId=${encodeURIComponent(imdbId)}`);
7
+ return this.toLookup(raw);
8
+ }
9
+ async addMovie(lookup, opts) {
10
+ const body = {
11
+ ...lookup.raw,
12
+ qualityProfileId: opts.qualityProfileId,
13
+ rootFolderPath: opts.rootFolderPath,
14
+ monitored: true,
15
+ addOptions: { searchForMovie: true },
16
+ };
17
+ try {
18
+ await this.postJson('/api/v3/movie', body);
19
+ return { status: 'added', detail: null };
20
+ }
21
+ catch (err) {
22
+ return this.mapAddError(err);
23
+ }
24
+ }
25
+ async libraryTmdbIds() {
26
+ const items = librarySchema.parse(await this.getJson('/api/v3/movie'));
27
+ return new Set(items.flatMap((m) => (typeof m.tmdbId === 'number' ? [m.tmdbId] : [])));
28
+ }
29
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ import { fetchJson } from '../http.js';
3
+ const queueSchema = z.object({ queue: z.object({ paused: z.boolean() }) });
4
+ export class SabnzbdClient {
5
+ url;
6
+ apiKey;
7
+ constructor(url, apiKey) {
8
+ this.url = url;
9
+ this.apiKey = apiKey;
10
+ }
11
+ call(mode) {
12
+ return fetchJson(`${this.url}/api?mode=${mode}&apikey=${encodeURIComponent(this.apiKey)}&output=json`);
13
+ }
14
+ async isPaused() {
15
+ return queueSchema.parse(await this.call('queue')).queue.paused;
16
+ }
17
+ async pause() {
18
+ await this.call('pause');
19
+ }
20
+ async resume() {
21
+ await this.call('resume');
22
+ }
23
+ }
@@ -0,0 +1,31 @@
1
+ import { z } from 'zod';
2
+ import { ArrClient } from './arr.js';
3
+ const librarySchema = z.array(z.object({ tvdbId: z.number().nullish() }));
4
+ export class SonarrClient extends ArrClient {
5
+ async lookupByTvdb(tvdbId) {
6
+ const raw = await this.getJson(`/api/v3/series/lookup?term=${encodeURIComponent(`tvdb:${tvdbId}`)}`);
7
+ return this.toLookup(raw);
8
+ }
9
+ async addSeries(lookup, opts) {
10
+ const { languageProfileId: _dropped, ...raw } = lookup.raw;
11
+ const body = {
12
+ ...raw,
13
+ qualityProfileId: opts.qualityProfileId,
14
+ rootFolderPath: opts.rootFolderPath,
15
+ monitored: true,
16
+ seasonFolder: true,
17
+ addOptions: { searchForMissingEpisodes: true, monitor: opts.monitor },
18
+ };
19
+ try {
20
+ await this.postJson('/api/v3/series', body);
21
+ return { status: 'added', detail: null };
22
+ }
23
+ catch (err) {
24
+ return this.mapAddError(err);
25
+ }
26
+ }
27
+ async libraryTvdbIds() {
28
+ const items = librarySchema.parse(await this.getJson('/api/v3/series'));
29
+ return new Set(items.flatMap((s) => (typeof s.tvdbId === 'number' ? [s.tvdbId] : [])));
30
+ }
31
+ }
@@ -0,0 +1,146 @@
1
+ import { z } from 'zod';
2
+ import { mapConcurrent } from '../concurrency.js';
3
+ import { HttpError, fetchJson } from '../http.js';
4
+ const BASE = 'https://api.themoviedb.org/3';
5
+ export const EXTERNAL_IDS_CONCURRENCY = 5;
6
+ const movieResultSchema = z.object({
7
+ id: z.number(),
8
+ title: z.string(),
9
+ release_date: z.string().nullish(),
10
+ genre_ids: z.array(z.number()).nullish(),
11
+ popularity: z.number(),
12
+ });
13
+ const showResultSchema = z.object({
14
+ id: z.number(),
15
+ name: z.string(),
16
+ first_air_date: z.string().nullish(),
17
+ genre_ids: z.array(z.number()).nullish(),
18
+ popularity: z.number(),
19
+ });
20
+ const moviePageSchema = z.object({ total_pages: z.number(), results: z.array(movieResultSchema) });
21
+ const showPageSchema = z.object({ total_pages: z.number(), results: z.array(showResultSchema) });
22
+ const genreListSchema = z.object({ genres: z.array(z.object({ id: z.number(), name: z.string() })) });
23
+ const movieExternalIdsSchema = z.object({ imdb_id: z.string().nullish() });
24
+ const showExternalIdsSchema = z.object({ imdb_id: z.string().nullish(), tvdb_id: z.number().nullish() });
25
+ const findSchema = z.object({ tv_results: z.array(z.object({ id: z.number() })) });
26
+ function yearOf(date) {
27
+ if (date === undefined || date === null || date.length < 4)
28
+ return null;
29
+ const year = Number(date.slice(0, 4));
30
+ return Number.isInteger(year) ? year : null;
31
+ }
32
+ function genreNames(ids, map) {
33
+ return (ids ?? []).flatMap((id) => {
34
+ const name = map.get(id);
35
+ return name === undefined ? [] : [name];
36
+ });
37
+ }
38
+ export class TmdbClient {
39
+ accessToken;
40
+ genreMaps = {};
41
+ constructor(accessToken) {
42
+ this.accessToken = accessToken;
43
+ }
44
+ headers() {
45
+ return {
46
+ Authorization: `Bearer ${this.accessToken}`,
47
+ 'User-Agent': 'trendarr',
48
+ };
49
+ }
50
+ async get(path) {
51
+ const url = `${BASE}${path}`;
52
+ try {
53
+ return await fetchJson(url, { headers: this.headers() });
54
+ }
55
+ catch (err) {
56
+ if (err instanceof HttpError && err.status === 429 && err.retryAfterSeconds !== undefined) {
57
+ const retryAfterSeconds = err.retryAfterSeconds;
58
+ await new Promise((r) => setTimeout(r, retryAfterSeconds * 1000));
59
+ return fetchJson(url, { headers: this.headers() });
60
+ }
61
+ throw err;
62
+ }
63
+ }
64
+ async collectPages(schema, urlFor, limit) {
65
+ const collected = [];
66
+ for (let page = 1; collected.length < limit; page += 1) {
67
+ const parsed = schema.parse(await this.get(urlFor(page)));
68
+ collected.push(...parsed.results);
69
+ if (page >= parsed.total_pages || parsed.results.length === 0)
70
+ break;
71
+ }
72
+ return collected.slice(0, limit);
73
+ }
74
+ async genreMap(kind) {
75
+ const cached = this.genreMaps[kind];
76
+ if (cached !== undefined)
77
+ return cached;
78
+ const raw = await this.get(`/genre/${kind}/list`);
79
+ const map = new Map(genreListSchema.parse(raw).genres.map((g) => [g.id, g.name]));
80
+ this.genreMaps[kind] = map;
81
+ return map;
82
+ }
83
+ async movieImdbId(tmdbId) {
84
+ const raw = await this.get(`/movie/${tmdbId}/external_ids`);
85
+ const imdbId = movieExternalIdsSchema.parse(raw).imdb_id;
86
+ return imdbId ? imdbId : null;
87
+ }
88
+ async showExternalIds(tmdbId) {
89
+ const raw = await this.get(`/tv/${tmdbId}/external_ids`);
90
+ const parsed = showExternalIdsSchema.parse(raw);
91
+ return { imdbId: parsed.imdb_id ? parsed.imdb_id : null, tvdbId: parsed.tvdb_id ?? null };
92
+ }
93
+ async findShowTvdbIdByImdb(imdbId) {
94
+ const raw = await this.get(`/find/${encodeURIComponent(imdbId)}?external_source=imdb_id`);
95
+ const first = findSchema.parse(raw).tv_results[0];
96
+ if (first === undefined)
97
+ return null;
98
+ return (await this.showExternalIds(first.id)).tvdbId;
99
+ }
100
+ async moviesToMedia(results) {
101
+ if (results.length === 0)
102
+ return [];
103
+ const genres = await this.genreMap('movie');
104
+ const imdbIds = await mapConcurrent(results, EXTERNAL_IDS_CONCURRENCY, (r) => this.movieImdbId(r.id));
105
+ return results.map((r, i) => ({
106
+ title: r.title,
107
+ year: yearOf(r.release_date),
108
+ imdbId: imdbIds[i] ?? null,
109
+ tmdbId: r.id,
110
+ tvdbId: null,
111
+ genres: genreNames(r.genre_ids, genres),
112
+ }));
113
+ }
114
+ async showsToMedia(results) {
115
+ if (results.length === 0)
116
+ return [];
117
+ const genres = await this.genreMap('tv');
118
+ const externals = await mapConcurrent(results, EXTERNAL_IDS_CONCURRENCY, (r) => this.showExternalIds(r.id));
119
+ return results.map((r, i) => ({
120
+ title: r.name,
121
+ year: yearOf(r.first_air_date),
122
+ imdbId: externals[i]?.imdbId ?? null,
123
+ tmdbId: r.id,
124
+ tvdbId: externals[i]?.tvdbId ?? null,
125
+ genres: genreNames(r.genre_ids, genres),
126
+ }));
127
+ }
128
+ async trendingMovies(limit) {
129
+ const results = await this.collectPages(moviePageSchema, (p) => `/trending/movie/week?page=${p}`, limit);
130
+ const media = await this.moviesToMedia(results);
131
+ return media.map((m, i) => ({ ...m, popularity: results[i]?.popularity ?? 0 }));
132
+ }
133
+ async trendingShows(limit) {
134
+ const results = await this.collectPages(showPageSchema, (p) => `/trending/tv/week?page=${p}`, limit);
135
+ const media = await this.showsToMedia(results);
136
+ return media.map((m, i) => ({ ...m, popularity: results[i]?.popularity ?? 0 }));
137
+ }
138
+ async searchMovies(query, limit) {
139
+ const results = await this.collectPages(moviePageSchema, (p) => `/search/movie?query=${encodeURIComponent(query)}&page=${p}`, limit);
140
+ return this.moviesToMedia(results);
141
+ }
142
+ async searchShows(query, limit) {
143
+ const results = await this.collectPages(showPageSchema, (p) => `/search/tv?query=${encodeURIComponent(query)}&page=${p}`, limit);
144
+ return this.showsToMedia(results);
145
+ }
146
+ }
@@ -0,0 +1,91 @@
1
+ import { z } from 'zod';
2
+ import { HttpError, fetchJson } from '../http.js';
3
+ const BASE = 'https://api.trakt.tv';
4
+ const idsSchema = z.object({
5
+ imdb: z.string().nullish(),
6
+ tmdb: z.number().nullish(),
7
+ tvdb: z.number().nullish(),
8
+ });
9
+ const mediaSchema = z.object({
10
+ title: z.string(),
11
+ year: z.number().nullish(),
12
+ ids: idsSchema,
13
+ rating: z.number().nullish(),
14
+ votes: z.number().nullish(),
15
+ genres: z.array(z.string()).nullish(),
16
+ });
17
+ const trendingMoviesSchema = z.array(z.object({ watchers: z.number(), movie: mediaSchema }));
18
+ const trendingShowsSchema = z.array(z.object({ watchers: z.number(), show: mediaSchema }));
19
+ const showSearchSchema = z.array(z.object({ type: z.string(), show: mediaSchema.optional() }));
20
+ const movieResultsSchema = z.array(z.object({ type: z.string(), movie: mediaSchema.optional() }));
21
+ const showResultsSchema = z.array(z.object({ type: z.string(), show: mediaSchema.optional() }));
22
+ function toMedia(media) {
23
+ return {
24
+ title: media.title,
25
+ year: media.year ?? null,
26
+ imdbId: media.ids.imdb ?? null,
27
+ tmdbId: media.ids.tmdb ?? null,
28
+ tvdbId: media.ids.tvdb ?? null,
29
+ rating: media.rating ?? null,
30
+ votes: media.votes ?? null,
31
+ genres: media.genres ?? [],
32
+ };
33
+ }
34
+ function toTrending(watchers, media) {
35
+ return { ...toMedia(media), watchers };
36
+ }
37
+ export class TraktClient {
38
+ clientId;
39
+ constructor(clientId) {
40
+ this.clientId = clientId;
41
+ }
42
+ headers() {
43
+ return {
44
+ 'trakt-api-version': '2',
45
+ 'trakt-api-key': this.clientId,
46
+ 'User-Agent': 'traktarr',
47
+ };
48
+ }
49
+ async get(path) {
50
+ const url = `${BASE}${path}`;
51
+ try {
52
+ return await fetchJson(url, { headers: this.headers() });
53
+ }
54
+ catch (err) {
55
+ if (err instanceof HttpError && err.status === 429 && err.retryAfterSeconds !== undefined) {
56
+ const retryAfterSeconds = err.retryAfterSeconds;
57
+ await new Promise((r) => setTimeout(r, retryAfterSeconds * 1000));
58
+ return fetchJson(url, { headers: this.headers() });
59
+ }
60
+ throw err;
61
+ }
62
+ }
63
+ async trendingMovies(limit) {
64
+ const raw = await this.get(`/movies/trending?extended=full&limit=${limit}`);
65
+ return trendingMoviesSchema.parse(raw).map((e) => toTrending(e.watchers, e.movie));
66
+ }
67
+ async trendingShows(limit) {
68
+ const raw = await this.get(`/shows/trending?extended=full&limit=${limit}`);
69
+ return trendingShowsSchema.parse(raw).map((e) => toTrending(e.watchers, e.show));
70
+ }
71
+ async searchMovies(query, limit) {
72
+ const raw = await this.get(`/search/movie?query=${encodeURIComponent(query)}&extended=full&limit=${limit}`);
73
+ return movieResultsSchema
74
+ .parse(raw)
75
+ .flatMap((r) => (r.movie === undefined ? [] : [toMedia(r.movie)]));
76
+ }
77
+ async searchShows(query, limit) {
78
+ const raw = await this.get(`/search/show?query=${encodeURIComponent(query)}&extended=full&limit=${limit}`);
79
+ return showResultsSchema.parse(raw).flatMap((r) => (r.show === undefined ? [] : [toMedia(r.show)]));
80
+ }
81
+ async findShowTvdbIdByImdb(imdbId) {
82
+ const raw = await this.get(`/search/imdb/${imdbId}?type=show`);
83
+ const results = showSearchSchema.parse(raw);
84
+ for (const result of results) {
85
+ const tvdb = result.show?.ids.tvdb;
86
+ if (typeof tvdb === 'number')
87
+ return tvdb;
88
+ }
89
+ return null;
90
+ }
91
+ }
@@ -0,0 +1,86 @@
1
+ import { RadarrClient } from '../clients/radarr.js';
2
+ import { SabnzbdClient } from '../clients/sabnzbd.js';
3
+ import { SonarrClient } from '../clients/sonarr.js';
4
+ import { TmdbClient } from '../clients/tmdb.js';
5
+ import { describeError } from '../http.js';
6
+ export function parseImdbIds(raw) {
7
+ const valid = [];
8
+ const invalid = [];
9
+ for (const entry of raw) {
10
+ const cleaned = entry.replaceAll(',', '').trim();
11
+ if (cleaned.length === 0)
12
+ continue;
13
+ if (/^tt\d+$/.test(cleaned))
14
+ valid.push(cleaned);
15
+ else
16
+ invalid.push(cleaned);
17
+ }
18
+ return { valid, invalid };
19
+ }
20
+ export function hasFailure(output) {
21
+ return output.results.some((r) => r.status === 'not_found' || r.status === 'error');
22
+ }
23
+ async function sabPaused(config, warnings) {
24
+ try {
25
+ return await new SabnzbdClient(config.sabnzbd.url, config.sabnzbd.apiKey).isPaused();
26
+ }
27
+ catch (err) {
28
+ warnings.push(`SABnzbd unreachable โ€” paused state unknown (${describeError(err)})`);
29
+ return null;
30
+ }
31
+ }
32
+ async function runBatch(config, rawIds, handler) {
33
+ const { valid, invalid } = parseImdbIds(rawIds);
34
+ const warnings = [];
35
+ const results = invalid.map((id) => ({
36
+ imdb_id: id,
37
+ title: null,
38
+ status: 'error',
39
+ detail: 'invalid IMDb id',
40
+ }));
41
+ for (const id of valid) {
42
+ try {
43
+ results.push(await handler(id));
44
+ }
45
+ catch (err) {
46
+ results.push({ imdb_id: id, title: null, status: 'error', detail: describeError(err) });
47
+ }
48
+ }
49
+ const sabnzbd_paused = await sabPaused(config, warnings);
50
+ return { output: { results, sabnzbd_paused }, warnings };
51
+ }
52
+ export function addMovies(config, rawIds) {
53
+ const radarr = new RadarrClient(config.radarr.url, config.radarr.apiKey);
54
+ return runBatch(config, rawIds, async (imdbId) => {
55
+ const lookup = await radarr.lookupByImdb(imdbId);
56
+ if (lookup === null)
57
+ return { imdb_id: imdbId, title: null, status: 'not_found', detail: null };
58
+ if (lookup.id > 0)
59
+ return { imdb_id: imdbId, title: lookup.title, status: 'already_exists', detail: null };
60
+ const outcome = await radarr.addMovie(lookup, {
61
+ qualityProfileId: config.radarr.qualityProfileId,
62
+ rootFolderPath: config.radarr.rootFolderPath,
63
+ });
64
+ return { imdb_id: imdbId, title: lookup.title, status: outcome.status, detail: outcome.detail };
65
+ });
66
+ }
67
+ export function addSeries(config, rawIds) {
68
+ const tmdb = new TmdbClient(config.tmdb.accessToken);
69
+ const sonarr = new SonarrClient(config.sonarr.url, config.sonarr.apiKey);
70
+ return runBatch(config, rawIds, async (imdbId) => {
71
+ const tvdbId = await tmdb.findShowTvdbIdByImdb(imdbId);
72
+ if (tvdbId === null)
73
+ return { imdb_id: imdbId, title: null, status: 'not_found', detail: null };
74
+ const lookup = await sonarr.lookupByTvdb(tvdbId);
75
+ if (lookup === null)
76
+ return { imdb_id: imdbId, title: null, status: 'not_found', detail: null };
77
+ if (lookup.id > 0)
78
+ return { imdb_id: imdbId, title: lookup.title, status: 'already_exists', detail: null };
79
+ const outcome = await sonarr.addSeries(lookup, {
80
+ qualityProfileId: config.sonarr.qualityProfileId,
81
+ rootFolderPath: config.sonarr.rootFolderPath,
82
+ monitor: config.sonarr.monitor,
83
+ });
84
+ return { imdb_id: imdbId, title: lookup.title, status: outcome.status, detail: outcome.detail };
85
+ });
86
+ }
@@ -0,0 +1,154 @@
1
+ import { cancel, intro, isCancel, log, outro, select, spinner, text } from '@clack/prompts';
2
+ import { OmdbClient } from '../clients/omdb.js';
3
+ import { RadarrClient } from '../clients/radarr.js';
4
+ import { SonarrClient } from '../clients/sonarr.js';
5
+ import { TmdbClient } from '../clients/tmdb.js';
6
+ import { SabnzbdClient } from '../clients/sabnzbd.js';
7
+ import { configPath, loadConfig, saveConfig } from '../config.js';
8
+ import { describeError } from '../http.js';
9
+ function bail() {
10
+ cancel('init aborted');
11
+ process.exit(1);
12
+ }
13
+ async function ask(message, initial) {
14
+ const value = await text({
15
+ message,
16
+ initialValue: initial ?? '',
17
+ validate: (v) => ((v ?? '').trim().length === 0 ? 'required' : undefined),
18
+ });
19
+ if (isCancel(value))
20
+ bail();
21
+ return value.trim();
22
+ }
23
+ async function validated(label, run) {
24
+ const s = spinner();
25
+ s.start(`Checking ${label}โ€ฆ`);
26
+ try {
27
+ const result = await run();
28
+ s.stop(`${label} OK`);
29
+ return result;
30
+ }
31
+ catch (err) {
32
+ s.stop(`${label} failed: ${describeError(err)}`);
33
+ return null;
34
+ }
35
+ }
36
+ async function askUntilValid(prompt) {
37
+ for (;;) {
38
+ const result = await prompt();
39
+ if (result !== null)
40
+ return result;
41
+ log.warn('Validation failed โ€” try again.');
42
+ }
43
+ }
44
+ async function pickArrDefaults(client, prior) {
45
+ const profiles = await client.qualityProfiles();
46
+ const folders = await client.rootFolders();
47
+ if (profiles.length === 0 || folders.length === 0) {
48
+ throw new Error('no quality profiles or root folders configured on the server');
49
+ }
50
+ const qualityProfileId = await select({
51
+ message: 'Default quality profile',
52
+ initialValue: prior.qualityProfileId,
53
+ options: profiles.map((p) => ({ value: p.id, label: p.name })),
54
+ });
55
+ if (isCancel(qualityProfileId))
56
+ bail();
57
+ const rootFolderPath = await select({
58
+ message: 'Default root folder',
59
+ initialValue: prior.rootFolderPath,
60
+ options: folders.map((f) => ({ value: f.path, label: f.path })),
61
+ });
62
+ if (isCancel(rootFolderPath))
63
+ bail();
64
+ return { qualityProfileId, rootFolderPath };
65
+ }
66
+ export async function runInit() {
67
+ intro('trendarr init');
68
+ let prior = {};
69
+ try {
70
+ prior = loadConfig();
71
+ log.info('Existing config found โ€” values prefilled.');
72
+ }
73
+ catch {
74
+ // fresh setup
75
+ }
76
+ const tmdb = await askUntilValid(async () => {
77
+ const accessToken = await ask('TMDB API Read Access Token (themoviedb.org/settings/api)', prior.tmdb?.accessToken);
78
+ const ok = await validated('TMDB', () => new TmdbClient(accessToken).trendingMovies(1));
79
+ return ok === null ? null : { accessToken };
80
+ });
81
+ const omdb = await askUntilValid(async () => {
82
+ const apiKey = await ask('OMDb API key (omdbapi.com/apikey.aspx)', prior.omdb?.apiKey);
83
+ const result = await validated('OMDb', async () => {
84
+ const enrich = await new OmdbClient(apiKey).byImdbId('tt0111161');
85
+ if (enrich === null)
86
+ throw new Error('key rejected');
87
+ return enrich;
88
+ });
89
+ return result === null ? null : { apiKey };
90
+ });
91
+ const radarr = await askUntilValid(async () => {
92
+ const url = (await ask('Radarr URL (e.g. http://localhost:7878)', prior.radarr?.url)).replace(/\/+$/, '');
93
+ const apiKey = await ask('Radarr API key (Settings > General > Security)', prior.radarr?.apiKey);
94
+ const client = new RadarrClient(url, apiKey);
95
+ const ok = await validated('Radarr', () => client.systemStatus());
96
+ if (ok === null)
97
+ return null;
98
+ let defaults;
99
+ try {
100
+ defaults = await pickArrDefaults(client, prior.radarr ?? {});
101
+ }
102
+ catch (err) {
103
+ log.error(`Radarr failed: ${describeError(err)}`);
104
+ return null;
105
+ }
106
+ return { url, apiKey, ...defaults };
107
+ });
108
+ const sonarr = await askUntilValid(async () => {
109
+ const url = (await ask('Sonarr URL (e.g. http://localhost:8989)', prior.sonarr?.url)).replace(/\/+$/, '');
110
+ const apiKey = await ask('Sonarr API key (Settings > General > Security)', prior.sonarr?.apiKey);
111
+ const client = new SonarrClient(url, apiKey);
112
+ const ok = await validated('Sonarr', () => client.systemStatus());
113
+ if (ok === null)
114
+ return null;
115
+ let defaults;
116
+ try {
117
+ defaults = await pickArrDefaults(client, prior.sonarr ?? {});
118
+ }
119
+ catch (err) {
120
+ log.error(`Sonarr failed: ${describeError(err)}`);
121
+ return null;
122
+ }
123
+ const monitor = await select({
124
+ message: 'Monitor mode for new series',
125
+ initialValue: prior.sonarr?.monitor ?? 'all',
126
+ options: [
127
+ { value: 'all', label: 'all โ€” every episode' },
128
+ { value: 'future', label: 'future โ€” only upcoming episodes' },
129
+ { value: 'missing', label: 'missing โ€” episodes without files' },
130
+ { value: 'firstSeason', label: 'firstSeason โ€” only season 1' },
131
+ { value: 'none', label: 'none โ€” add unmonitored episodes' },
132
+ ],
133
+ });
134
+ if (isCancel(monitor))
135
+ bail();
136
+ return { url, apiKey, ...defaults, monitor };
137
+ });
138
+ const sabnzbd = await askUntilValid(async () => {
139
+ const url = (await ask('SABnzbd URL (e.g. http://localhost:8080)', prior.sabnzbd?.url)).replace(/\/+$/, '');
140
+ const apiKey = await ask('SABnzbd API key (Config > General)', prior.sabnzbd?.apiKey);
141
+ const ok = await validated('SABnzbd', () => new SabnzbdClient(url, apiKey).isPaused());
142
+ return ok === null ? null : { url, apiKey };
143
+ });
144
+ const config = {
145
+ tmdb,
146
+ omdb,
147
+ radarr,
148
+ sonarr,
149
+ sabnzbd,
150
+ defaults: { maxEntries: prior.defaults?.maxEntries ?? 10 },
151
+ };
152
+ saveConfig(config);
153
+ outro(`Saved ${configPath()} (chmod 600). Try: trendarr trending`);
154
+ }
@@ -0,0 +1,33 @@
1
+ import { mapConcurrent } from '../concurrency.js';
2
+ import { describeError } from '../http.js';
3
+ export const ENRICH_CONCURRENCY = 5;
4
+ export async function librarySet(load, label, warnings) {
5
+ try {
6
+ return await load();
7
+ }
8
+ catch (err) {
9
+ warnings.push(`${label} unreachable โ€” in_library unknown (${describeError(err)})`);
10
+ return null;
11
+ }
12
+ }
13
+ export async function toMediaItems(entries, omdb, library, libraryKey) {
14
+ const enrichments = await mapConcurrent(entries, ENRICH_CONCURRENCY, async (e) => e.imdbId === null ? null : omdb.byImdbId(e.imdbId));
15
+ return entries.map((e, i) => {
16
+ const enrich = enrichments[i] ?? null;
17
+ const key = libraryKey(e);
18
+ return {
19
+ rank: i + 1,
20
+ title: e.title,
21
+ year: e.year,
22
+ imdb_rating: enrich?.imdbRating ?? null,
23
+ imdb_votes: enrich?.imdbVotes ?? null,
24
+ rotten_tomatoes: enrich?.rottenTomatoes ?? null,
25
+ metascore: enrich?.metascore ?? null,
26
+ genres: e.genres,
27
+ imdb_id: e.imdbId,
28
+ tmdb_id: e.tmdbId,
29
+ tvdb_id: e.tvdbId,
30
+ in_library: library === null || key === null ? null : library.has(key),
31
+ };
32
+ });
33
+ }
@@ -0,0 +1,9 @@
1
+ import { SabnzbdClient } from '../clients/sabnzbd.js';
2
+ export async function runSabnzbd(config, action) {
3
+ const client = new SabnzbdClient(config.sabnzbd.url, config.sabnzbd.apiKey);
4
+ if (action === 'pause')
5
+ await client.pause();
6
+ if (action === 'resume' || action === 'unpause')
7
+ await client.resume();
8
+ return { sabnzbd_paused: await client.isPaused() };
9
+ }
@@ -0,0 +1,26 @@
1
+ import { OmdbClient } from '../clients/omdb.js';
2
+ import { RadarrClient } from '../clients/radarr.js';
3
+ import { SonarrClient } from '../clients/sonarr.js';
4
+ import { TmdbClient } from '../clients/tmdb.js';
5
+ import { librarySet, toMediaItems } from './media.js';
6
+ export async function getSearch(config, query, opts) {
7
+ const tmdb = new TmdbClient(config.tmdb.accessToken);
8
+ const omdb = new OmdbClient(config.omdb.apiKey);
9
+ const radarr = new RadarrClient(config.radarr.url, config.radarr.apiKey);
10
+ const sonarr = new SonarrClient(config.sonarr.url, config.sonarr.apiKey);
11
+ const limit = opts.maxEntries ?? config.defaults.maxEntries;
12
+ const wantMovies = opts.type !== 'series';
13
+ const wantSeries = opts.type !== 'movies';
14
+ const warnings = [];
15
+ const [movies, shows, movieLib, seriesLib] = await Promise.all([
16
+ wantMovies ? tmdb.searchMovies(query, limit) : Promise.resolve([]),
17
+ wantSeries ? tmdb.searchShows(query, limit) : Promise.resolve([]),
18
+ wantMovies ? librarySet(() => radarr.libraryTmdbIds(), 'Radarr', warnings) : Promise.resolve(null),
19
+ wantSeries ? librarySet(() => sonarr.libraryTvdbIds(), 'Sonarr', warnings) : Promise.resolve(null),
20
+ ]);
21
+ const output = {
22
+ movies: await toMediaItems(movies, omdb, movieLib, (e) => e.tmdbId),
23
+ series: await toMediaItems(shows, omdb, seriesLib, (e) => e.tvdbId),
24
+ };
25
+ return { output, warnings };
26
+ }
@@ -0,0 +1,35 @@
1
+ import { OmdbClient } from '../clients/omdb.js';
2
+ import { RadarrClient } from '../clients/radarr.js';
3
+ import { SonarrClient } from '../clients/sonarr.js';
4
+ import { TmdbClient } from '../clients/tmdb.js';
5
+ import { librarySet, toMediaItems } from './media.js';
6
+ const DEFAULT_MIN_RATING = 6.5;
7
+ function passesMinRating(item, minRating) {
8
+ if (item.imdb_rating === null)
9
+ return true;
10
+ const rating = Number.parseFloat(item.imdb_rating);
11
+ return Number.isNaN(rating) || rating >= minRating;
12
+ }
13
+ export async function getTrending(config, opts) {
14
+ const tmdb = new TmdbClient(config.tmdb.accessToken);
15
+ const omdb = new OmdbClient(config.omdb.apiKey);
16
+ const radarr = new RadarrClient(config.radarr.url, config.radarr.apiKey);
17
+ const sonarr = new SonarrClient(config.sonarr.url, config.sonarr.apiKey);
18
+ const limit = opts.maxEntries ?? config.defaults.maxEntries;
19
+ const wantMovies = opts.type !== 'series';
20
+ const wantSeries = opts.type !== 'movies';
21
+ const warnings = [];
22
+ const [movies, shows, movieLib, seriesLib] = await Promise.all([
23
+ wantMovies ? tmdb.trendingMovies(limit) : Promise.resolve([]),
24
+ wantSeries ? tmdb.trendingShows(limit) : Promise.resolve([]),
25
+ wantMovies ? librarySet(() => radarr.libraryTmdbIds(), 'Radarr', warnings) : Promise.resolve(null),
26
+ wantSeries ? librarySet(() => sonarr.libraryTvdbIds(), 'Sonarr', warnings) : Promise.resolve(null),
27
+ ]);
28
+ const movieItems = (await toMediaItems(movies, omdb, movieLib, (e) => e.tmdbId)).map((m, i) => ({ ...m, popularity: movies[i]?.popularity ?? 0 }));
29
+ const seriesItems = (await toMediaItems(shows, omdb, seriesLib, (e) => e.tvdbId)).map((m, i) => ({ ...m, popularity: shows[i]?.popularity ?? 0 }));
30
+ const minRating = opts.minRating ?? DEFAULT_MIN_RATING;
31
+ const rankedMovies = movieItems
32
+ .filter((m) => passesMinRating(m, minRating))
33
+ .map((m, i) => ({ ...m, rank: i + 1 }));
34
+ return { output: { movies: rankedMovies, series: seriesItems }, warnings };
35
+ }
@@ -0,0 +1,15 @@
1
+ export async function mapConcurrent(items, limit, fn) {
2
+ const results = new Array(items.length);
3
+ let next = 0;
4
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
5
+ for (;;) {
6
+ const i = next;
7
+ next += 1;
8
+ if (i >= items.length)
9
+ return;
10
+ results[i] = await fn(items[i]);
11
+ }
12
+ });
13
+ await Promise.all(workers);
14
+ return results;
15
+ }
package/dist/config.js ADDED
@@ -0,0 +1,53 @@
1
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { z } from 'zod';
5
+ const arrSchema = z.object({
6
+ url: z.string().min(1),
7
+ apiKey: z.string().min(1),
8
+ qualityProfileId: z.number().int().positive(),
9
+ rootFolderPath: z.string().min(1),
10
+ });
11
+ export const configSchema = z.object({
12
+ tmdb: z.object({ accessToken: z.string().min(1) }),
13
+ omdb: z.object({ apiKey: z.string().min(1) }),
14
+ radarr: arrSchema,
15
+ sonarr: arrSchema.extend({ monitor: z.string().min(1) }),
16
+ sabnzbd: z.object({ url: z.string().min(1), apiKey: z.string().min(1) }),
17
+ defaults: z.object({ maxEntries: z.number().int().positive() }),
18
+ });
19
+ export class ConfigError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'ConfigError';
23
+ }
24
+ }
25
+ const CONFIG_ERROR_MESSAGE = "Config missing/invalid โ€” run 'trendarr init'.";
26
+ export function configPath() {
27
+ return join(homedir(), '.trendarr', 'config.json');
28
+ }
29
+ export function loadConfig(path = configPath()) {
30
+ let text;
31
+ try {
32
+ text = readFileSync(path, 'utf8');
33
+ }
34
+ catch {
35
+ throw new ConfigError(CONFIG_ERROR_MESSAGE);
36
+ }
37
+ let raw;
38
+ try {
39
+ raw = JSON.parse(text);
40
+ }
41
+ catch {
42
+ throw new ConfigError(CONFIG_ERROR_MESSAGE);
43
+ }
44
+ const parsed = configSchema.safeParse(raw);
45
+ if (!parsed.success)
46
+ throw new ConfigError(CONFIG_ERROR_MESSAGE);
47
+ return parsed.data;
48
+ }
49
+ export function saveConfig(config, path = configPath()) {
50
+ mkdirSync(dirname(path), { recursive: true });
51
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
52
+ chmodSync(path, 0o600);
53
+ }
package/dist/format.js ADDED
@@ -0,0 +1,87 @@
1
+ import pc from 'picocolors';
2
+ export function toJson(value) {
3
+ return JSON.stringify(value, null, 2);
4
+ }
5
+ function cell(value, width) {
6
+ const clipped = value.length > width ? `${value.slice(0, width - 1)}โ€ฆ` : value;
7
+ return clipped.padEnd(width);
8
+ }
9
+ const dash = (v) => (v === null ? '-' : String(v));
10
+ const tableLib = (item) => (item.in_library === null ? '?' : item.in_library ? 'โœ“' : '');
11
+ const tableLink = (item) => item.imdb_id === null ? '-' : `https://www.imdb.com/title/${item.imdb_id}`;
12
+ function trendingRows(items) {
13
+ const header = `${cell('#', 3)} ${cell('TITLE', 34)} ${cell('YEAR', 5)} ${cell('POP', 6)} ${cell('IMDB', 5)} ${cell('LIB', 3)} LINK`;
14
+ const rows = items.map((i) => `${cell(String(i.rank), 3)} ${cell(i.title, 34)} ${cell(dash(i.year), 5)} ${cell(String(Math.round(i.popularity)), 6)} ${cell(dash(i.imdb_rating), 5)} ${cell(tableLib(i), 3)} ${tableLink(i)}`);
15
+ return [pc.bold(header), ...rows];
16
+ }
17
+ function searchRows(items) {
18
+ const header = `${cell('#', 3)} ${cell('TITLE', 34)} ${cell('YEAR', 5)} ${cell('IMDB', 5)} ${cell('LIB', 3)} LINK`;
19
+ const rows = items.map((i) => `${cell(String(i.rank), 3)} ${cell(i.title, 34)} ${cell(dash(i.year), 5)} ${cell(dash(i.imdb_rating), 5)} ${cell(tableLib(i), 3)} ${tableLink(i)}`);
20
+ return [pc.bold(header), ...rows];
21
+ }
22
+ function renderBlocks(movies, series, moviesEmpty, seriesEmpty) {
23
+ const sections = [];
24
+ if (!moviesEmpty)
25
+ sections.push(pc.bold(pc.cyan('MOVIES')), ...movies);
26
+ if (!seriesEmpty) {
27
+ if (sections.length > 0)
28
+ sections.push('');
29
+ sections.push(pc.bold(pc.cyan('SERIES')), ...series);
30
+ }
31
+ if (sections.length === 0)
32
+ sections.push('No results.');
33
+ return sections.join('\n');
34
+ }
35
+ export function renderTrendingTable(output) {
36
+ return renderBlocks(trendingRows(output.movies), trendingRows(output.series), output.movies.length === 0, output.series.length === 0);
37
+ }
38
+ export function renderSearchTable(output) {
39
+ return renderBlocks(searchRows(output.movies), searchRows(output.series), output.movies.length === 0, output.series.length === 0);
40
+ }
41
+ function escapeDiscord(text) {
42
+ return text.replace(/([\\*_~`|[\]])/g, '\\$1');
43
+ }
44
+ function discordTitleLink(item) {
45
+ const year = item.year === null ? '' : ` (${item.year})`;
46
+ const label = escapeDiscord(`${item.title}${year}`);
47
+ return item.imdb_id === null ? label : `[${label}](<https://www.imdb.com/title/${item.imdb_id}/>)`;
48
+ }
49
+ function discordLibSuffix(item) {
50
+ return item.in_library === null ? ' โ“' : item.in_library ? ' โœ…' : ' โŒ';
51
+ }
52
+ function trendingDiscordLine(item) {
53
+ const rating = item.imdb_rating === null ? '' : `${item.imdb_rating} ยท `;
54
+ return `${item.rank}. ${discordTitleLink(item)} โ€” ${rating}๐Ÿ”ฅ${Math.round(item.popularity)}${discordLibSuffix(item)}`;
55
+ }
56
+ function searchDiscordLine(item) {
57
+ const rating = item.imdb_rating === null ? '' : ` โ€” ${item.imdb_rating}`;
58
+ return `${item.rank}. ${discordTitleLink(item)}${rating}${discordLibSuffix(item)}`;
59
+ }
60
+ function discordBlock(header, items, line) {
61
+ if (items.length === 0)
62
+ return `${header}\n_none_`;
63
+ return [header, ...items.map(line)].join('\n');
64
+ }
65
+ export function renderTrendingDiscord(output) {
66
+ return `${discordBlock('**๐ŸŽฌ Movies**', output.movies, trendingDiscordLine)}\n\n${discordBlock('**๐Ÿ“บ Series**', output.series, trendingDiscordLine)}`;
67
+ }
68
+ export function renderSearchDiscord(output) {
69
+ return `${discordBlock('**๐ŸŽฌ Movies**', output.movies, searchDiscordLine)}\n\n${discordBlock('**๐Ÿ“บ Series**', output.series, searchDiscordLine)}`;
70
+ }
71
+ export function renderSabStatus(paused) {
72
+ return `SABnzbd paused: ${paused ? 'yes' : 'no'}`;
73
+ }
74
+ export function renderAddTable(output) {
75
+ const lines = output.results.map((r) => {
76
+ const title = r.title ?? '?';
77
+ const detail = r.detail === null ? '' : ` (${r.detail})`;
78
+ const status = r.status === 'added'
79
+ ? pc.green(r.status)
80
+ : r.status === 'already_exists'
81
+ ? pc.yellow(r.status)
82
+ : pc.red(r.status);
83
+ return `${cell(r.imdb_id, 12)} ${cell(title, 34)} ${status}${detail}`;
84
+ });
85
+ const sab = output.sabnzbd_paused === null ? 'SABnzbd status: unknown' : renderSabStatus(output.sabnzbd_paused);
86
+ return [...lines, '', sab].join('\n');
87
+ }
package/dist/http.js ADDED
@@ -0,0 +1,63 @@
1
+ function redactUrl(url) {
2
+ try {
3
+ const parsed = new URL(url);
4
+ parsed.search = '';
5
+ return parsed.toString();
6
+ }
7
+ catch {
8
+ const queryIndex = url.indexOf('?');
9
+ return queryIndex === -1 ? url : url.slice(0, queryIndex);
10
+ }
11
+ }
12
+ export class HttpError extends Error {
13
+ status;
14
+ url;
15
+ body;
16
+ retryAfterSeconds;
17
+ constructor(status, url, body, retryAfterSeconds) {
18
+ super(`HTTP ${status} from ${redactUrl(url)}`);
19
+ this.status = status;
20
+ this.url = url;
21
+ this.body = body;
22
+ this.retryAfterSeconds = retryAfterSeconds;
23
+ this.name = 'HttpError';
24
+ }
25
+ }
26
+ export async function fetchJson(url, opts = {}) {
27
+ const { method = 'GET', headers = {}, body, timeoutMs = 10_000 } = opts;
28
+ const res = await fetch(url, {
29
+ method,
30
+ headers: body === undefined ? headers : { 'Content-Type': 'application/json', ...headers },
31
+ body: body === undefined ? undefined : JSON.stringify(body),
32
+ signal: AbortSignal.timeout(timeoutMs),
33
+ });
34
+ const text = await res.text();
35
+ let json = null;
36
+ if (text.length > 0) {
37
+ try {
38
+ json = JSON.parse(text);
39
+ }
40
+ catch {
41
+ json = text;
42
+ }
43
+ }
44
+ if (!res.ok) {
45
+ const retryAfter = res.headers.get('Retry-After');
46
+ const seconds = retryAfter === null ? undefined : Number(retryAfter);
47
+ throw new HttpError(res.status, url, json, Number.isFinite(seconds) ? seconds : undefined);
48
+ }
49
+ return json;
50
+ }
51
+ export function describeError(err) {
52
+ if (err instanceof HttpError) {
53
+ if (err.status === 401 || err.status === 403)
54
+ return `API key rejected (${err.status}) by ${redactUrl(err.url)}`;
55
+ return err.message;
56
+ }
57
+ if (err instanceof Error && err.name === 'TimeoutError')
58
+ return 'request timed out';
59
+ if (err instanceof Error && err.cause instanceof Error && 'code' in err.cause) {
60
+ return `server unreachable (${String(err.cause.code)})`;
61
+ }
62
+ return err instanceof Error ? err.message : String(err);
63
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@astrofoundry/trendarr",
3
+ "version": "0.6.0",
4
+ "description": "TMDB trending โ†’ OMDb ratings โ†’ Radarr/Sonarr adds โ†’ SABnzbd control, from the terminal",
5
+ "scripts": {
6
+ "build": "tsc -p tsconfig.build.json && chmod +x dist/cli.js",
7
+ "lint": "eslint .",
8
+ "test": "vitest run",
9
+ "check": "tsc --noEmit && eslint . && vitest run",
10
+ "release:patch": "npm version patch && git push --follow-tags",
11
+ "release:minor": "npm version minor && git push --follow-tags",
12
+ "release:major": "npm version major && git push --follow-tags"
13
+ },
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "dependencies": {
17
+ "@clack/prompts": "^1.7.0",
18
+ "commander": "^15.0.0",
19
+ "picocolors": "^1.1.1",
20
+ "zod": "^4.4.3"
21
+ },
22
+ "devDependencies": {
23
+ "@eslint/js": "^10.0.1",
24
+ "@types/node": "^24.13.3",
25
+ "eslint": "^10.7.0",
26
+ "msw": "^2.15.0",
27
+ "typescript": "6.0.3",
28
+ "typescript-eslint": "^8.65.0",
29
+ "vitest": "^4.1.10"
30
+ },
31
+ "bin": {
32
+ "trendarr": "dist/cli.js"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "engines": {
38
+ "node": ">=24"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/astrofoundry/traktarr.git"
46
+ }
47
+ }