@dominevo/series-scraper-core 0.0.91 → 0.0.93

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.
Files changed (31) hide show
  1. package/dist/controllers/notifications.controller.d.ts +4 -11
  2. package/dist/controllers/notifications.controller.js +7 -5
  3. package/dist/controllers/settings.controller.d.ts +3 -3
  4. package/dist/controllers/settings.controller.js +6 -4
  5. package/dist/controllers/sites.controller.d.ts +5 -53
  6. package/dist/controllers/sites.controller.js +47 -14
  7. package/dist/controllers/vpn.controller.js +2 -0
  8. package/dist/docker-layout/secret-layout.js +19 -7
  9. package/dist/ports/secret-store.d.ts +2 -0
  10. package/dist/ports/secret-store.js +2 -0
  11. package/dist/repositories/settings.repository.d.ts +5 -0
  12. package/dist/repositories/settings.repository.js +18 -1
  13. package/dist/repositories/sites.repository.d.ts +6 -1
  14. package/dist/repositories/sites.repository.js +34 -5
  15. package/dist/repositories/webhook.repository.d.ts +3 -0
  16. package/dist/repositories/webhook.repository.js +13 -4
  17. package/dist/scraper.module.js +2 -0
  18. package/dist/services/download.service.d.ts +4 -0
  19. package/dist/services/download.service.js +24 -16
  20. package/dist/services/library-permissions.d.ts +27 -0
  21. package/dist/services/library-permissions.js +113 -0
  22. package/dist/services/plugin-settings.service.d.ts +2 -0
  23. package/dist/services/plugin-settings.service.js +16 -3
  24. package/dist/services/secret-migration.service.d.ts +22 -0
  25. package/dist/services/secret-migration.service.js +48 -0
  26. package/dist/services/secret-views.d.ts +56 -0
  27. package/dist/services/secret-views.js +120 -0
  28. package/dist/services/sonarr.service.d.ts +8 -0
  29. package/dist/services/sonarr.service.js +31 -0
  30. package/dist/types.d.ts +6 -0
  31. package/package.json +1 -1
@@ -83,6 +83,7 @@ const captcha_service_1 = require("./captcha.service");
83
83
  const maxstream_page_1 = require("./maxstream-page");
84
84
  const captcha_fallback_1 = require("./captcha-fallback");
85
85
  const failure_reason_1 = require("./failure-reason");
86
+ const library_permissions_1 = require("./library-permissions");
86
87
  /**
87
88
  * Bounded-concurrency scheduler with **per-group auto-balancing cap**.
88
89
  *
@@ -716,7 +717,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
716
717
  }
717
718
  if (!cachedFinalDirBase)
718
719
  return null;
719
- const seasonFolder = `Season ${String(seasonNumber).padStart(2, '0')}`;
720
+ const seasonFolder = await this.seasonFolderName(seasonNumber);
720
721
  return path.join(path.resolve(settings.sonarrRootPath), cachedFinalDirBase, seasonFolder);
721
722
  };
722
723
  const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
@@ -1026,8 +1027,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1026
1027
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
1027
1028
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, childId, job);
1028
1029
  if (finalDir) {
1029
- await fs.mkdir(finalDir, { recursive: true });
1030
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
1030
+ await this.placeInLibrary(tempPath, finalDir);
1031
1031
  }
1032
1032
  await this.sonarr.rescanSeries(entry.arrId);
1033
1033
  if (settings.renameEp)
@@ -1341,9 +1341,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1341
1341
  // Move atomically to Radarr's library folder if moveEp is enabled
1342
1342
  let finalPath = tempPath;
1343
1343
  if (finalDir) {
1344
- await fs.mkdir(finalDir, { recursive: true });
1345
- const destPath = path.join(finalDir, path.basename(tempPath));
1346
- await this.moveFile(tempPath, destPath);
1344
+ const destPath = await this.placeInLibrary(tempPath, finalDir);
1347
1345
  finalPath = destPath;
1348
1346
  }
1349
1347
  await this.radarr.rescanMovie(entry.arrId);
@@ -2240,6 +2238,20 @@ let DownloadService = DownloadService_1 = class DownloadService {
2240
2238
  /**
2241
2239
  * Move a file atomically. Falls back to copy+delete if src and dest are on different devices.
2242
2240
  */
2241
+ /** The season folder name: Sonarr's own naming when readable, else "Season NN". */
2242
+ async seasonFolderName(season) {
2243
+ const named = await this.sonarr.getSeasonFolderName(season);
2244
+ return named ?? `Season ${String(season).padStart(2, '0')}`;
2245
+ }
2246
+ /** mkdir the library dir, move the file in, and open permissions on both (a chmod failure never fails the move). */
2247
+ async placeInLibrary(tempPath, finalDir) {
2248
+ const settings = this.settings.get();
2249
+ await (0, library_permissions_1.mkdirLibrary)(finalDir, settings, this.logger);
2250
+ const dest = path.join(finalDir, path.basename(tempPath));
2251
+ await this.moveFile(tempPath, dest);
2252
+ await (0, library_permissions_1.openLibraryFile)(dest, settings, this.logger);
2253
+ return dest;
2254
+ }
2243
2255
  async moveFile(src, dest) {
2244
2256
  try {
2245
2257
  await fs.rename(src, dest);
@@ -3068,7 +3080,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3068
3080
  const series = await this.sonarr.getSeriesById(entry.arrId);
3069
3081
  if (series) {
3070
3082
  const seriesFolder = path.basename(series.path);
3071
- const seasonFolder = `Season ${String(season).padStart(2, '0')}`;
3083
+ const seasonFolder = await this.seasonFolderName(season);
3072
3084
  finalDir = path.join(path.resolve(settings.sonarrRootPath), seriesFolder, seasonFolder);
3073
3085
  }
3074
3086
  }
@@ -3100,8 +3112,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3100
3112
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
3101
3113
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3102
3114
  if (finalDir) {
3103
- await fs.mkdir(finalDir, { recursive: true });
3104
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3115
+ await this.placeInLibrary(tempPath, finalDir);
3105
3116
  }
3106
3117
  await this.sonarr.rescanSeries(entry.arrId);
3107
3118
  if (settings.renameEp)
@@ -3153,8 +3164,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3153
3164
  };
3154
3165
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3155
3166
  if (finalDir) {
3156
- await fs.mkdir(finalDir, { recursive: true });
3157
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3167
+ await this.placeInLibrary(tempPath, finalDir);
3158
3168
  }
3159
3169
  await this.radarr.rescanMovie(entry.arrId);
3160
3170
  if (settings.renameEp)
@@ -3389,13 +3399,12 @@ let DownloadService = DownloadService_1 = class DownloadService {
3389
3399
  const series = await this.sonarr.getSeriesById(entry.arrId);
3390
3400
  if (series) {
3391
3401
  const seriesFolder = path.basename(series.path);
3392
- const seasonFolder = `Season ${String(partial.season).padStart(2, '0')}`;
3402
+ const seasonFolder = await this.seasonFolderName(partial.season);
3393
3403
  finalDir = path.join(path.resolve(settings.sonarrRootPath), seriesFolder, seasonFolder);
3394
3404
  }
3395
3405
  }
3396
3406
  if (finalDir) {
3397
- await fs.mkdir(finalDir, { recursive: true });
3398
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3407
+ await this.placeInLibrary(tempPath, finalDir);
3399
3408
  }
3400
3409
  await this.sonarr.rescanSeries(entry.arrId);
3401
3410
  if (settings.renameEp)
@@ -3416,8 +3425,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3416
3425
  finalDir = path.join(path.resolve(settings.radarrRootPath), path.basename(movie.path));
3417
3426
  }
3418
3427
  if (finalDir) {
3419
- await fs.mkdir(finalDir, { recursive: true });
3420
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3428
+ await this.placeInLibrary(tempPath, finalDir);
3421
3429
  }
3422
3430
  await this.radarr.rescanMovie(entry.arrId);
3423
3431
  if (settings.renameEp)
@@ -0,0 +1,27 @@
1
+ /** Unraid "New Permissions" convention: every user may read and write the library. */
2
+ export declare const DEFAULT_LIBRARY_DIR_MODE = "0777";
3
+ export declare const DEFAULT_LIBRARY_FILE_MODE = "0666";
4
+ export interface LibraryPermissionSettings {
5
+ libraryOpenPermissions?: boolean;
6
+ libraryDirMode?: string;
7
+ libraryFileMode?: string;
8
+ }
9
+ export interface PermissionLog {
10
+ warn(message: string): void;
11
+ }
12
+ /** Parse an octal string ("0777", "777", "0o775"); null when it is not a valid mode. */
13
+ export declare function parseOctalMode(raw: unknown): number | null;
14
+ /** chmod that never throws: a failure is logged with the path and errno. */
15
+ export declare function chmodQuiet(target: string, mode: number, log: PermissionLog): Promise<void>;
16
+ /**
17
+ * mkdir -p that also opens every directory it CREATED (an existing ancestor is
18
+ * left alone). `recursive` mkdir applies the umask, so each new level is chmod-ed.
19
+ */
20
+ export declare function mkdirLibrary(dir: string, s: LibraryPermissionSettings, log: PermissionLog): Promise<void>;
21
+ /** Open a file that was just moved or copied into a library. */
22
+ export declare function openLibraryFile(file: string, s: LibraryPermissionSettings, log: PermissionLog): Promise<void>;
23
+ /**
24
+ * Render a Sonarr `seasonFolderFormat`. Only `{season}` and `{season:00}` are
25
+ * understood; any other token returns null so the caller falls back.
26
+ */
27
+ export declare function renderSeasonFolder(format: string, season: number): string | null;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DEFAULT_LIBRARY_FILE_MODE = exports.DEFAULT_LIBRARY_DIR_MODE = void 0;
37
+ exports.parseOctalMode = parseOctalMode;
38
+ exports.chmodQuiet = chmodQuiet;
39
+ exports.mkdirLibrary = mkdirLibrary;
40
+ exports.openLibraryFile = openLibraryFile;
41
+ exports.renderSeasonFolder = renderSeasonFolder;
42
+ const fs = __importStar(require("fs/promises"));
43
+ const path = __importStar(require("path"));
44
+ /** Unraid "New Permissions" convention: every user may read and write the library. */
45
+ exports.DEFAULT_LIBRARY_DIR_MODE = '0777';
46
+ exports.DEFAULT_LIBRARY_FILE_MODE = '0666';
47
+ /** Parse an octal string ("0777", "777", "0o775"); null when it is not a valid mode. */
48
+ function parseOctalMode(raw) {
49
+ if (typeof raw !== 'string')
50
+ return null;
51
+ const text = raw.trim().replace(/^0o/i, '');
52
+ if (!/^[0-7]{3,4}$/.test(text))
53
+ return null;
54
+ return parseInt(text, 8);
55
+ }
56
+ function modeOrDefault(raw, fallback) {
57
+ return parseOctalMode(raw) ?? parseOctalMode(fallback);
58
+ }
59
+ function errnoOf(err) {
60
+ if (err && typeof err === 'object' && 'code' in err)
61
+ return String(err.code);
62
+ return 'unknown';
63
+ }
64
+ /** chmod that never throws: a failure is logged with the path and errno. */
65
+ async function chmodQuiet(target, mode, log) {
66
+ try {
67
+ await fs.chmod(target, mode);
68
+ }
69
+ catch (err) {
70
+ log.warn(`chmod ${mode.toString(8)} failed on ${target} (${errnoOf(err)}): ${err instanceof Error ? err.message : String(err)}`);
71
+ }
72
+ }
73
+ /**
74
+ * mkdir -p that also opens every directory it CREATED (an existing ancestor is
75
+ * left alone). `recursive` mkdir applies the umask, so each new level is chmod-ed.
76
+ */
77
+ async function mkdirLibrary(dir, s, log) {
78
+ const first = await fs.mkdir(dir, { recursive: true });
79
+ if (s.libraryOpenPermissions === false || !first)
80
+ return;
81
+ const mode = modeOrDefault(s.libraryDirMode, exports.DEFAULT_LIBRARY_DIR_MODE);
82
+ // `first` is the topmost directory created; open it and every level down to `dir`.
83
+ const levels = [];
84
+ for (let cur = dir;; cur = path.dirname(cur)) {
85
+ levels.unshift(cur);
86
+ if (cur === first || path.dirname(cur) === cur)
87
+ break;
88
+ }
89
+ for (const level of levels)
90
+ await chmodQuiet(level, mode, log);
91
+ }
92
+ /** Open a file that was just moved or copied into a library. */
93
+ async function openLibraryFile(file, s, log) {
94
+ if (s.libraryOpenPermissions === false)
95
+ return;
96
+ await chmodQuiet(file, modeOrDefault(s.libraryFileMode, exports.DEFAULT_LIBRARY_FILE_MODE), log);
97
+ }
98
+ /**
99
+ * Render a Sonarr `seasonFolderFormat`. Only `{season}` and `{season:00}` are
100
+ * understood; any other token returns null so the caller falls back.
101
+ */
102
+ function renderSeasonFolder(format, season) {
103
+ let unknown = false;
104
+ const out = format.replace(/\{([^}]*)\}/g, (_m, token) => {
105
+ if (token === 'season')
106
+ return String(season);
107
+ if (token === 'season:00')
108
+ return String(season).padStart(2, '0');
109
+ unknown = true;
110
+ return '';
111
+ });
112
+ return unknown || !out.trim() ? null : out;
113
+ }
@@ -6,6 +6,8 @@ export { PluginSettingsError };
6
6
  export interface PluginSettingsView {
7
7
  fields: PluginSettingField[];
8
8
  values: PluginSettingValues;
9
+ /** Text settings whose name reads like a credential: their value is never shown (`''`), and an empty one on a write keeps the stored value. */
10
+ secretKeys: string[];
9
11
  }
10
12
  export declare class PluginSettingsService {
11
13
  private readonly loader;
@@ -11,10 +11,19 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.PluginSettingsService = exports.PluginSettingsError = void 0;
13
13
  const common_1 = require("@nestjs/common");
14
+ const secret_views_1 = require("./secret-views");
14
15
  const plugin_settings_repository_1 = require("../repositories/plugin-settings.repository");
15
16
  const plugin_loader_service_1 = require("./plugin-loader.service");
16
17
  const plugin_settings_1 = require("./plugin-settings");
17
18
  Object.defineProperty(exports, "PluginSettingsError", { enumerable: true, get: function () { return plugin_settings_1.PluginSettingsError; } });
19
+ /** The text settings of a plugin that hold a credential, by the name heuristic (a schema flag may replace it). */
20
+ function secretKeysOf(fields) {
21
+ return fields.filter((f) => f.type === 'string' && (0, secret_views_1.isCredentialName)(f.key)).map((f) => f.key);
22
+ }
23
+ function viewOf(fields, values) {
24
+ const secretKeys = secretKeysOf(fields);
25
+ return { fields, values: { ...values, ...Object.fromEntries(secretKeys.map((k) => [k, ''])) }, secretKeys };
26
+ }
18
27
  let PluginSettingsService = class PluginSettingsService {
19
28
  constructor(loader, repo) {
20
29
  this.loader = loader;
@@ -25,7 +34,7 @@ let PluginSettingsService = class PluginSettingsService {
25
34
  const handle = this.loader.getSettingsHandle(pluginName);
26
35
  if (!handle)
27
36
  return null;
28
- return { fields: handle.fields, values: (0, plugin_settings_1.resolveSettingValues)(handle.fields, this.repo.getFor(pluginName)) };
37
+ return viewOf(handle.fields, (0, plugin_settings_1.resolveSettingValues)(handle.fields, this.repo.getFor(pluginName)));
29
38
  }
30
39
  /**
31
40
  * Validates, applies live through the plugin's `configure`, and persists only
@@ -35,7 +44,11 @@ let PluginSettingsService = class PluginSettingsService {
35
44
  const handle = this.loader.getSettingsHandle(pluginName);
36
45
  if (!handle)
37
46
  throw new plugin_settings_1.PluginSettingsError(`Plugin "${pluginName}" has no settings`);
38
- const changes = (0, plugin_settings_1.validateSettingValues)(handle.fields, input);
47
+ const secretKeys = secretKeysOf(handle.fields);
48
+ const typed = typeof input === 'object' && input !== null && !Array.isArray(input)
49
+ ? Object.fromEntries(Object.entries(input).filter(([k, v]) => !(secretKeys.includes(k) && (v === '' || v === undefined || v === null))))
50
+ : input;
51
+ const changes = (0, plugin_settings_1.validateSettingValues)(handle.fields, typed);
39
52
  const merged = (0, plugin_settings_1.resolveSettingValues)(handle.fields, { ...this.repo.getFor(pluginName), ...changes });
40
53
  try {
41
54
  handle.configure?.(merged);
@@ -44,7 +57,7 @@ let PluginSettingsService = class PluginSettingsService {
44
57
  throw new plugin_settings_1.PluginSettingsError(err instanceof Error ? err.message : String(err));
45
58
  }
46
59
  this.repo.setFor(pluginName, merged);
47
- return { fields: handle.fields, values: merged };
60
+ return viewOf(handle.fields, merged);
48
61
  }
49
62
  };
50
63
  exports.PluginSettingsService = PluginSettingsService;
@@ -0,0 +1,22 @@
1
+ import { OnModuleInit } from '@nestjs/common';
2
+ import { SettingsRepository } from '../repositories/settings.repository';
3
+ import { SitesRepository } from '../repositories/sites.repository';
4
+ import { WebhookRepository } from '../repositories/webhook.repository';
5
+ /**
6
+ * At boot, moves every credential an older state file still holds in plain text (API keys, the Plex token,
7
+ * webhook and site headers) into the secret store and leaves none behind. Idempotent: a second boot finds
8
+ * nothing. Logs counts only, never a value.
9
+ */
10
+ export declare class SecretMigrationService implements OnModuleInit {
11
+ private readonly settings;
12
+ private readonly webhooks;
13
+ private readonly sites;
14
+ private readonly logger;
15
+ constructor(settings: SettingsRepository, webhooks: WebhookRepository, sites: SitesRepository);
16
+ onModuleInit(): void;
17
+ run(): {
18
+ settings: number;
19
+ webhooks: number;
20
+ sites: number;
21
+ };
22
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var SecretMigrationService_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.SecretMigrationService = void 0;
14
+ const common_1 = require("@nestjs/common");
15
+ const logger_1 = require("../ports/logger");
16
+ const settings_repository_1 = require("../repositories/settings.repository");
17
+ const sites_repository_1 = require("../repositories/sites.repository");
18
+ const webhook_repository_1 = require("../repositories/webhook.repository");
19
+ /**
20
+ * At boot, moves every credential an older state file still holds in plain text (API keys, the Plex token,
21
+ * webhook and site headers) into the secret store and leaves none behind. Idempotent: a second boot finds
22
+ * nothing. Logs counts only, never a value.
23
+ */
24
+ let SecretMigrationService = SecretMigrationService_1 = class SecretMigrationService {
25
+ constructor(settings, webhooks, sites) {
26
+ this.settings = settings;
27
+ this.webhooks = webhooks;
28
+ this.sites = sites;
29
+ this.logger = new logger_1.ScopedLogger(SecretMigrationService_1.name);
30
+ }
31
+ onModuleInit() {
32
+ this.run();
33
+ }
34
+ run() {
35
+ const moved = { settings: this.settings.migratePlaintext(), webhooks: this.webhooks.migratePlaintext(), sites: this.sites.migratePlaintext() };
36
+ if (moved.settings + moved.webhooks + moved.sites > 0) {
37
+ this.logger.log(`Moved plaintext credentials to the secret store: ${moved.settings} setting(s), ${moved.webhooks} webhook(s), ${moved.sites} site(s)`);
38
+ }
39
+ return moved;
40
+ }
41
+ };
42
+ exports.SecretMigrationService = SecretMigrationService;
43
+ exports.SecretMigrationService = SecretMigrationService = SecretMigrationService_1 = __decorate([
44
+ (0, common_1.Injectable)(),
45
+ __metadata("design:paramtypes", [settings_repository_1.SettingsRepository,
46
+ webhook_repository_1.WebhookRepository,
47
+ sites_repository_1.SitesRepository])
48
+ ], SecretMigrationService);
@@ -0,0 +1,56 @@
1
+ import { AppSettings } from '../types';
2
+ import type { WebhookConfig } from '../repositories/webhook.repository';
3
+ import type { GenericSiteConfig } from '../types';
4
+ /**
5
+ * What the HTTP API shows of a credential: whether it is set, never the value. A credential is
6
+ * written only when typed (an empty field keeps the stored one) and removed by an explicit clear.
7
+ */
8
+ export declare const SETTINGS_SECRET_KEYS: readonly ["sonarrApiKey", "radarrApiKey", "plexToken"];
9
+ export type SettingsSecretKey = (typeof SETTINGS_SECRET_KEYS)[number];
10
+ /** The settings as the API answers them: every credential is `''` and its `<name>Set` flag says whether one is stored. */
11
+ export type SettingsView = Omit<AppSettings, SettingsSecretKey> & Record<SettingsSecretKey, ''> & Record<`${SettingsSecretKey}Set`, boolean>;
12
+ export declare function toSettingsView(settings: AppSettings): SettingsView;
13
+ /**
14
+ * The partial settings a PATCH body asks for. The view-only `<name>Set` flags are dropped, an empty
15
+ * credential keeps the stored one, and `clear<Name>: true` removes it.
16
+ */
17
+ export declare function parseSettingsBody(body: unknown): Partial<AppSettings>;
18
+ /** A name that reads like a credential: Authorization, X-Auth-User, X-Api-Key, Cookie, X-Session-Id, a plugin's `apiToken`. Over-matching is safe: such a value is only hidden, and a typed one still goes through. */
19
+ export declare const isCredentialName: (name: string) => boolean;
20
+ export declare const isCredentialHeader: (name: string) => boolean;
21
+ /** A webhook as the API answers it: a credential header keeps its name and answers `''`, and is listed in `secretHeaders`. */
22
+ export type WebhookView = Omit<WebhookConfig, 'headers'> & {
23
+ headers: Record<string, string>;
24
+ secretHeaders: string[];
25
+ urlSecretSet: boolean;
26
+ };
27
+ export declare function toWebhookView(webhook: WebhookConfig): WebhookView;
28
+ /**
29
+ * A webhook address in two halves: the origin (scheme://host:port), which is shown and editable, and the rest
30
+ * (path and query, where a token usually sits), which is never shown. An address that does not parse is all secret.
31
+ */
32
+ export declare function splitUrl(url: string): {
33
+ origin: string;
34
+ secret: string;
35
+ };
36
+ /**
37
+ * The address a webhook write leaves. A bare origin on the SAME origin keeps the stored path and query (an echoed
38
+ * view); a bare origin on another host means the address is that origin, so a token never follows to a new host. A
39
+ * full address replaces both. An absent or empty one keeps what is stored.
40
+ */
41
+ export declare function mergeWebhookUrl(stored: string, incoming: unknown): string;
42
+ /**
43
+ * The headers a save leaves: the ones in `incoming`, where a credential header sent empty keeps its stored
44
+ * value. A name absent from `incoming` is removed, which is the explicit clear.
45
+ */
46
+ export declare function mergeHeaders(stored: Record<string, string>, incoming: unknown): Record<string, string>;
47
+ /** A generic site as the API answers it: header names and plain values are shown, a credential header's value never. */
48
+ export type SiteView = Omit<GenericSiteConfig, 'headers'> & {
49
+ headers?: Record<string, string>;
50
+ secretHeaders?: string[];
51
+ };
52
+ export declare function toSiteView(site: GenericSiteConfig): SiteView;
53
+ /** A site as a write carries it: the view-only field dropped, the headers merged over the stored ones. */
54
+ export declare function siteFromWrite(body: Partial<GenericSiteConfig> & {
55
+ secretHeaders?: unknown;
56
+ }, stored?: GenericSiteConfig): Partial<GenericSiteConfig>;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isCredentialHeader = exports.isCredentialName = exports.SETTINGS_SECRET_KEYS = void 0;
4
+ exports.toSettingsView = toSettingsView;
5
+ exports.parseSettingsBody = parseSettingsBody;
6
+ exports.toWebhookView = toWebhookView;
7
+ exports.splitUrl = splitUrl;
8
+ exports.mergeWebhookUrl = mergeWebhookUrl;
9
+ exports.mergeHeaders = mergeHeaders;
10
+ exports.toSiteView = toSiteView;
11
+ exports.siteFromWrite = siteFromWrite;
12
+ /**
13
+ * What the HTTP API shows of a credential: whether it is set, never the value. A credential is
14
+ * written only when typed (an empty field keeps the stored one) and removed by an explicit clear.
15
+ */
16
+ exports.SETTINGS_SECRET_KEYS = ['sonarrApiKey', 'radarrApiKey', 'plexToken'];
17
+ function toSettingsView(settings) {
18
+ return {
19
+ ...settings,
20
+ sonarrApiKey: '',
21
+ radarrApiKey: '',
22
+ plexToken: '',
23
+ sonarrApiKeySet: settings.sonarrApiKey !== '',
24
+ radarrApiKeySet: settings.radarrApiKey !== '',
25
+ plexTokenSet: settings.plexToken !== '',
26
+ };
27
+ }
28
+ /**
29
+ * The partial settings a PATCH body asks for. The view-only `<name>Set` flags are dropped, an empty
30
+ * credential keeps the stored one, and `clear<Name>: true` removes it.
31
+ */
32
+ function parseSettingsBody(body) {
33
+ const raw = typeof body === 'object' && body !== null && !Array.isArray(body) ? { ...body } : {};
34
+ for (const key of exports.SETTINGS_SECRET_KEYS) {
35
+ const clear = `clear${key[0].toUpperCase()}${key.slice(1)}`;
36
+ const cleared = raw[clear] === true;
37
+ delete raw[`${key}Set`];
38
+ delete raw[clear];
39
+ if (cleared)
40
+ raw[key] = '';
41
+ else if (raw[key] === '' || raw[key] === undefined || raw[key] === null)
42
+ delete raw[key];
43
+ }
44
+ return raw;
45
+ }
46
+ /** A header whose value carries a credential: it is never shown, only its name. */
47
+ const CREDENTIAL_NAME = /auth|key|token|secret|pass|cookie|sign|cred|session/i;
48
+ /** A name that reads like a credential: Authorization, X-Auth-User, X-Api-Key, Cookie, X-Session-Id, a plugin's `apiToken`. Over-matching is safe: such a value is only hidden, and a typed one still goes through. */
49
+ const isCredentialName = (name) => CREDENTIAL_NAME.test(name);
50
+ exports.isCredentialName = isCredentialName;
51
+ exports.isCredentialHeader = exports.isCredentialName;
52
+ function toWebhookView(webhook) {
53
+ const secretHeaders = Object.keys(webhook.headers).filter(exports.isCredentialHeader);
54
+ const headers = Object.fromEntries(Object.entries(webhook.headers).map(([name, value]) => [name, (0, exports.isCredentialHeader)(name) ? '' : value]));
55
+ const { origin, secret } = splitUrl(webhook.url);
56
+ return { ...webhook, url: origin, urlSecretSet: secret !== '', headers, secretHeaders };
57
+ }
58
+ /**
59
+ * A webhook address in two halves: the origin (scheme://host:port), which is shown and editable, and the rest
60
+ * (path and query, where a token usually sits), which is never shown. An address that does not parse is all secret.
61
+ */
62
+ function splitUrl(url) {
63
+ try {
64
+ const parsed = new URL(url);
65
+ const rest = `${parsed.pathname === '/' ? '' : parsed.pathname}${parsed.search}${parsed.hash}`;
66
+ return { origin: parsed.origin, secret: rest };
67
+ }
68
+ catch {
69
+ return { origin: '', secret: url };
70
+ }
71
+ }
72
+ /**
73
+ * The address a webhook write leaves. A bare origin on the SAME origin keeps the stored path and query (an echoed
74
+ * view); a bare origin on another host means the address is that origin, so a token never follows to a new host. A
75
+ * full address replaces both. An absent or empty one keeps what is stored.
76
+ */
77
+ function mergeWebhookUrl(stored, incoming) {
78
+ if (typeof incoming !== 'string' || incoming === '')
79
+ return stored;
80
+ const next = splitUrl(incoming);
81
+ if (next.origin === '' || next.secret !== '')
82
+ return incoming;
83
+ const prior = splitUrl(stored);
84
+ return prior.origin === next.origin ? `${next.origin}${prior.secret}` : next.origin;
85
+ }
86
+ /**
87
+ * The headers a save leaves: the ones in `incoming`, where a credential header sent empty keeps its stored
88
+ * value. A name absent from `incoming` is removed, which is the explicit clear.
89
+ */
90
+ function mergeHeaders(stored, incoming) {
91
+ if (typeof incoming !== 'object' || incoming === null || Array.isArray(incoming))
92
+ return stored;
93
+ const out = {};
94
+ for (const [name, value] of Object.entries(incoming)) {
95
+ if (typeof value !== 'string')
96
+ continue;
97
+ if (value === '' && (0, exports.isCredentialHeader)(name)) {
98
+ // an empty credential keeps the stored value; with none stored there is nothing to keep, so it is not saved as a literal empty header
99
+ if (name in stored)
100
+ out[name] = stored[name];
101
+ continue;
102
+ }
103
+ out[name] = value;
104
+ }
105
+ return out;
106
+ }
107
+ function toSiteView(site) {
108
+ if (!site.headers || Object.keys(site.headers).length === 0)
109
+ return site;
110
+ const secretHeaders = Object.keys(site.headers).filter(exports.isCredentialHeader);
111
+ const headers = Object.fromEntries(Object.entries(site.headers).map(([name, value]) => [name, (0, exports.isCredentialHeader)(name) ? '' : value]));
112
+ return { ...site, headers, secretHeaders };
113
+ }
114
+ /** A site as a write carries it: the view-only field dropped, the headers merged over the stored ones. */
115
+ function siteFromWrite(body, stored) {
116
+ const { secretHeaders: _view, headers, ...rest } = body;
117
+ if (headers === undefined)
118
+ return rest;
119
+ return { ...rest, headers: mergeHeaders(stored?.headers ?? {}, headers) };
120
+ }
@@ -3,7 +3,15 @@ import { SettingsService } from './settings.service';
3
3
  export declare class SonarrService {
4
4
  private readonly settings;
5
5
  private readonly logger;
6
+ /** Sonarr's `seasonFolderFormat`, per Sonarr address; null = unreadable (fall back). */
7
+ private namingCache;
8
+ private namingErrorLogged;
6
9
  constructor(settings: SettingsService);
10
+ /**
11
+ * The season folder name as Sonarr itself would build it ("Season 5" or "Season 05"), from its naming
12
+ * config. Null when Sonarr is absent, errors (logged once) or uses a token we do not render.
13
+ */
14
+ getSeasonFolderName(season: number): Promise<string | null>;
7
15
  private getConfig;
8
16
  status(): Promise<{
9
17
  configured: boolean;
@@ -16,10 +16,41 @@ const logger_1 = require("../ports/logger");
16
16
  const egress_context_1 = require("./egress/egress-context");
17
17
  const arr_images_1 = require("./arr-images");
18
18
  const settings_service_1 = require("./settings.service");
19
+ const library_permissions_1 = require("./library-permissions");
19
20
  let SonarrService = SonarrService_1 = class SonarrService {
20
21
  constructor(settings) {
21
22
  this.settings = settings;
22
23
  this.logger = new logger_1.ScopedLogger(SonarrService_1.name);
24
+ /** Sonarr's `seasonFolderFormat`, per Sonarr address; null = unreadable (fall back). */
25
+ this.namingCache = null;
26
+ this.namingErrorLogged = false;
27
+ }
28
+ /**
29
+ * The season folder name as Sonarr itself would build it ("Season 5" or "Season 05"), from its naming
30
+ * config. Null when Sonarr is absent, errors (logged once) or uses a token we do not render.
31
+ */
32
+ async getSeasonFolderName(season) {
33
+ const config = this.getConfig();
34
+ if (!config)
35
+ return null;
36
+ const key = `${config.url}\n${config.apiKey}`;
37
+ if (this.namingCache?.key !== key) {
38
+ let format = null;
39
+ try {
40
+ const data = await this.apiGet(config, '/api/v3/config/naming');
41
+ format = typeof data.seasonFolderFormat === 'string' ? data.seasonFolderFormat : null;
42
+ this.namingErrorLogged = false;
43
+ }
44
+ catch (err) {
45
+ if (!this.namingErrorLogged) {
46
+ this.namingErrorLogged = true;
47
+ this.logger.warn(`Sonarr naming config unreadable, using "Season NN" folders: ${err}`);
48
+ }
49
+ return null; // not cached: a later call retries
50
+ }
51
+ this.namingCache = { key, format };
52
+ }
53
+ return this.namingCache.format ? (0, library_permissions_1.renderSeasonFolder)(this.namingCache.format, season) : null;
23
54
  }
24
55
  getConfig() {
25
56
  const s = this.settings.get();
package/dist/types.d.ts CHANGED
@@ -441,6 +441,12 @@ export interface AppSettings {
441
441
  scanDelay: number;
442
442
  autoBind: boolean;
443
443
  moveEp: boolean;
444
+ /** chmod everything the scraper puts in a library so Sonarr/Radarr (another uid) can rename it. */
445
+ libraryOpenPermissions: boolean;
446
+ /** Octal mode for directories the scraper creates in a library. */
447
+ libraryDirMode: string;
448
+ /** Octal mode for files the scraper moves into a library. */
449
+ libraryFileMode: string;
444
450
  renameEp: boolean;
445
451
  tagsMode: 'WHITELIST' | 'BLACKLIST';
446
452
  logLevel: 'debug' | 'info' | 'warning' | 'error';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.91",
3
+ "version": "0.0.93",
4
4
  "description": "Host-agnostic scraper core: services, repositories, controllers and the ports a host supplies",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",