@serifpersia/dango 3.6.7 → 3.6.9

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 (156) hide show
  1. package/README.md +1 -1
  2. package/client/dist/assets/{AnimeCard-C3P9zWi9.js → AnimeCard-DKDJK8Mp.js} +1 -1
  3. package/client/dist/assets/{AnimeInfo-Et6687Tl.js → AnimeInfo-CTcvfjva.js} +1 -1
  4. package/client/dist/assets/{AnimeInfoPage-DX4eNnlH.js → AnimeInfoPage-B_UiacIN.js} +2 -2
  5. package/client/dist/assets/{Asmr-CCdEWrFi.js → Asmr-DMSN2vxl.js} +2 -2
  6. package/client/dist/assets/{AsmrResetProgressModal-DgEWBJOw.js → AsmrResetProgressModal-CRwfOatX.js} +1 -1
  7. package/client/dist/assets/{AvSyncCalibrator-CQ2fjf2E.js → AvSyncCalibrator-CRJsi-vz.js} +1 -1
  8. package/client/dist/assets/{Home-DUkUTTTy.js → Home-pwmK9_Eh.js} +1 -1
  9. package/client/dist/assets/{Insights-QCh4xW12.js → Insights-m7kFzg2A.js} +1 -1
  10. package/client/dist/assets/{LibraryListPage-BoTxRqHz.js → LibraryListPage-C1wpPvu6.js} +1 -1
  11. package/client/dist/assets/ListeningList-OzfEI1Ga.js +1 -0
  12. package/client/dist/assets/{Manga-HydR-L7o.js → Manga-ChRCExhK.js} +1 -1
  13. package/client/dist/assets/{MangaInfoPage-CBakEI9a.js → MangaInfoPage-DSHJPo2A.js} +1 -1
  14. package/client/dist/assets/{MangaReadPage-DwAR3iPy.js → MangaReadPage-CzOVY1wA.js} +1 -1
  15. package/client/dist/assets/{MangaResetProgressModal-DGzl8vsO.js → MangaResetProgressModal-CJfzdUBb.js} +1 -1
  16. package/client/dist/assets/{Mature-Pi0TxKuF.js → Mature-CifQMfhs.js} +1 -1
  17. package/client/dist/assets/{MediaCard--cuFxOCS.js → MediaCard-CM10yB9V.js} +1 -1
  18. package/client/dist/assets/{OptionListMenu-B3D39dGS.js → OptionListMenu-6Kovbsqw.js} +1 -1
  19. package/client/dist/assets/{Player-CsH4x_I_.js → Player-CK0hT-u4.js} +2 -2
  20. package/client/dist/assets/{PlayerSettings-DGxBsi3F.js → PlayerSettings-Bb66uqT9.js} +1 -1
  21. package/client/dist/assets/{QueueOptionsButton-Djq4Cpex.js → QueueOptionsButton-C_nTj8_q.js} +1 -1
  22. package/client/dist/assets/{QueueRail-DOrYgNVX.js → QueueRail-DUK7URAE.js} +1 -1
  23. package/client/dist/assets/{ReadingList-DwYoBrNk.js → ReadingList-Ck9LJThU.js} +1 -1
  24. package/client/dist/assets/{ResetProgressModal-CMF86mX6.js → ResetProgressModal-BUphIv0k.js} +1 -1
  25. package/client/dist/assets/{Search-DFkhuk-x.js → Search-zJyP15h6.js} +1 -1
  26. package/client/dist/assets/{Settings-DBB2r0VQ.js → Settings-BYdoSEUh.js} +1 -1
  27. package/client/dist/assets/{SkeletonGrid-DJelJgAv.js → SkeletonGrid-CqgbOhjX.js} +1 -1
  28. package/client/dist/assets/{Trackers-DGYXFhYZ.js → Trackers-BVjyv6CM.js} +1 -1
  29. package/client/dist/assets/{Tv-C5MDGD2Z.js → Tv-L13ylswR.js} +1 -1
  30. package/client/dist/assets/{TvInfo-DrKuK13u.js → TvInfo-Cvcm5U2D.js} +1 -1
  31. package/client/dist/assets/{TvPopup-DtHilRDT.js → TvPopup-DhxfKvYm.js} +1 -1
  32. package/client/dist/assets/{TvSearch-CzNxdu_w.js → TvSearch-P8bFE6_X.js} +1 -1
  33. package/client/dist/assets/{TvWatchlist-D7p4br6S.js → TvWatchlist-D5gVPjtb.js} +1 -1
  34. package/client/dist/assets/{Watchlist-DrOzswl2.js → Watchlist-Cjq8l3rU.js} +1 -1
  35. package/client/dist/assets/{hls-BGCX7mJy.js → hls-BkzuANAg.js} +1 -1
  36. package/client/dist/assets/{index-CnfZwsds.js → index-CLVgzKLk.js} +19 -19
  37. package/client/dist/assets/{useAnimeInfoData-DYXWBPF-.js → useAnimeInfoData-DZJZu-so.js} +1 -1
  38. package/client/dist/assets/{useAsmr-BbhQ59bk.js → useAsmr-CvrMGHuo.js} +1 -1
  39. package/client/dist/assets/useAsmrPopup-Bimy8Ouw.js +1 -0
  40. package/client/dist/assets/{useMangaLibrary-DuesWQaE.js → useMangaLibrary--MiN11uR.js} +1 -1
  41. package/client/dist/assets/{useMangaPopup-D57OVGUr.js → useMangaPopup-CR5XhKKS.js} +1 -1
  42. package/client/dist/assets/{useProviders-mpQb_dix.js → useProviders-DqdT4fA5.js} +1 -1
  43. package/client/dist/assets/{useTv-DGflCsSI.js → useTv-BL0HMDyP.js} +1 -1
  44. package/client/dist/assets/{useTvLibrary-BqeSmyc4.js → useTvLibrary-D4U4iqN8.js} +1 -1
  45. package/client/dist/index.html +1 -1
  46. package/package.json +3 -5
  47. package/server/dist/config.js +1 -174
  48. package/server/dist/server.js +1068 -289
  49. package/server/dist/shipped-defaults.js +1 -6
  50. package/server/package.json +4 -5
  51. package/client/dist/assets/Asmr.module-CdWlioTY.js +0 -1
  52. package/client/dist/assets/ListeningList-DguKjI_t.js +0 -1
  53. package/client/dist/assets/Music-BGH_0voi.css +0 -1
  54. package/client/dist/assets/Music-CQpyXTLH.js +0 -1
  55. package/client/dist/assets/Radio-CCHNFN7R.css +0 -1
  56. package/client/dist/assets/Radio-DF6g6odd.js +0 -1
  57. package/client/dist/assets/Radio.module-DGSZLpKM.js +0 -1
  58. package/client/dist/assets/useAsmrPopup-SymV1J-b.js +0 -1
  59. package/server/dist/app-auth.js +0 -157
  60. package/server/dist/app-hono.js +0 -598
  61. package/server/dist/db/drizzle.js +0 -16
  62. package/server/dist/db/schema-anime.js +0 -61
  63. package/server/dist/db/schema-asmr.js +0 -13
  64. package/server/dist/db/schema-manga.js +0 -31
  65. package/server/dist/db/schema-tv.js +0 -18
  66. package/server/dist/db.js +0 -217
  67. package/server/dist/discord-gateway.js +0 -385
  68. package/server/dist/discord-rpc.js +0 -413
  69. package/server/dist/github-sync.js +0 -508
  70. package/server/dist/google.js +0 -741
  71. package/server/dist/hono/asmr.js +0 -10
  72. package/server/dist/hono/auth.js +0 -49
  73. package/server/dist/hono/music.js +0 -209
  74. package/server/dist/hono/proxy.js +0 -827
  75. package/server/dist/hono/tv.js +0 -200
  76. package/server/dist/hono/watchlist.js +0 -341
  77. package/server/dist/lib/anilist.js +0 -1583
  78. package/server/dist/lib/anischedule.js +0 -191
  79. package/server/dist/lib/insights.js +0 -185
  80. package/server/dist/lib/ipc.js +0 -23
  81. package/server/dist/lib/kitsu.js +0 -517
  82. package/server/dist/lib/mal-import.js +0 -291
  83. package/server/dist/lib/mal.js +0 -957
  84. package/server/dist/lib/migration.js +0 -310
  85. package/server/dist/lib/offline-db.js +0 -395
  86. package/server/dist/lib/potoken.js +0 -135
  87. package/server/dist/lib/recommendations.service.js +0 -216
  88. package/server/dist/lib/temp-ids.js +0 -3
  89. package/server/dist/lib/tmdb.js +0 -72
  90. package/server/dist/lib/tracker/anilist-tracker.js +0 -308
  91. package/server/dist/lib/tracker/manga-sync.service.js +0 -773
  92. package/server/dist/lib/tracker/sync-state.js +0 -21
  93. package/server/dist/lib/tracker/sync.service.js +0 -476
  94. package/server/dist/lib/translate.js +0 -79
  95. package/server/dist/lib/ump.js +0 -106
  96. package/server/dist/lib/ytmusic.js +0 -162
  97. package/server/dist/logger.js +0 -16
  98. package/server/dist/providers/manga/manga.types.js +0 -1
  99. package/server/dist/providers/provider.interface.js +0 -1
  100. package/server/dist/providers/remote-loader.js +0 -614
  101. package/server/dist/providers/remote-types.js +0 -159
  102. package/server/dist/providers/title-matching.js +0 -226
  103. package/server/dist/providers/tv.types.js +0 -1
  104. package/server/dist/rclone.js +0 -120
  105. package/server/dist/repositories/asmr.repository.js +0 -77
  106. package/server/dist/repositories/insights.repository.js +0 -106
  107. package/server/dist/repositories/library.repository.js +0 -94
  108. package/server/dist/repositories/mal-cache.repository.js +0 -52
  109. package/server/dist/repositories/manga.repository.js +0 -95
  110. package/server/dist/repositories/notifications.repository.js +0 -60
  111. package/server/dist/repositories/queue.repository.js +0 -72
  112. package/server/dist/repositories/settings.repository.js +0 -30
  113. package/server/dist/repositories/shows-meta.repository.js +0 -58
  114. package/server/dist/repositories/temp-show-ids.repository.js +0 -63
  115. package/server/dist/repositories/tv.repository.js +0 -93
  116. package/server/dist/repositories/watched-episodes.repository.js +0 -82
  117. package/server/dist/repositories/watchlist.repository.js +0 -60
  118. package/server/dist/scripts/backfill-episode-duration.js +0 -42
  119. package/server/dist/sync-payload.js +0 -91
  120. package/server/dist/sync.js +0 -657
  121. package/server/dist/trpc/context.js +0 -7
  122. package/server/dist/trpc/errors.js +0 -15
  123. package/server/dist/trpc/index.js +0 -18
  124. package/server/dist/trpc/router.js +0 -49
  125. package/server/dist/trpc/routers/asmr-library.js +0 -112
  126. package/server/dist/trpc/routers/asmr-progress.js +0 -121
  127. package/server/dist/trpc/routers/asmr.js +0 -87
  128. package/server/dist/trpc/routers/auth.js +0 -194
  129. package/server/dist/trpc/routers/continue-watching.js +0 -81
  130. package/server/dist/trpc/routers/data.js +0 -1026
  131. package/server/dist/trpc/routers/discord.js +0 -285
  132. package/server/dist/trpc/routers/discovery.js +0 -11
  133. package/server/dist/trpc/routers/insights.js +0 -14
  134. package/server/dist/trpc/routers/manga-library.js +0 -263
  135. package/server/dist/trpc/routers/manga-progress.js +0 -169
  136. package/server/dist/trpc/routers/manga.js +0 -201
  137. package/server/dist/trpc/routers/music.js +0 -655
  138. package/server/dist/trpc/routers/notifications.js +0 -80
  139. package/server/dist/trpc/routers/progress.js +0 -109
  140. package/server/dist/trpc/routers/queue.js +0 -93
  141. package/server/dist/trpc/routers/radio.js +0 -145
  142. package/server/dist/trpc/routers/settings.js +0 -96
  143. package/server/dist/trpc/routers/tracker.js +0 -213
  144. package/server/dist/trpc/routers/tv-library.js +0 -135
  145. package/server/dist/trpc/routers/tv-progress.js +0 -159
  146. package/server/dist/trpc/routers/tv.js +0 -551
  147. package/server/dist/trpc/routers/watchlist.js +0 -550
  148. package/server/dist/trpc/validation.js +0 -258
  149. package/server/dist/utils/cache.utils.js +0 -25
  150. package/server/dist/utils/cookie.utils.js +0 -13
  151. package/server/dist/utils/db-utils.js +0 -17
  152. package/server/dist/utils/env.utils.js +0 -77
  153. package/server/dist/utils/http.utils.js +0 -82
  154. package/server/dist/utils/request-context.js +0 -2
  155. package/server/dist/utils/security.utils.js +0 -76
  156. /package/client/dist/assets/{Asmr-D1KuQwQy.css → useAsmrPopup-D1KuQwQy.css} +0 -0
@@ -1,614 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import crypto from 'crypto';
4
- import { execFileSync } from 'node:child_process';
5
- import { pathToFileURL } from 'url';
6
- import * as cheerio from 'cheerio';
7
- import { gotScraping } from 'got-scraping';
8
- import logger from '../logger.js';
9
- import { CONFIG } from '../config.js';
10
- import { requestContext } from '../utils/request-context.js';
11
- import { sanitizeCfClearance, buildCfClearanceCookie } from '../utils/cookie.utils.js';
12
- import { decodeMaybeGzip, parseJsonBody } from '../utils/http.utils.js';
13
- import { buildQueryVariants, pickBestMatch } from './title-matching.js';
14
- import { anilistRequest, parseMalId, searchAnilistByTitle } from '../lib/anilist.js';
15
- import { kitsuMetaByAnilistId } from '../lib/kitsu.js';
16
- import { getTmdbKey, TMDB_BASE, TMDB_IMAGE } from '../lib/tmdb.js';
17
- import { parseRegistry, } from './remote-types.js';
18
- const FETCH_TIMEOUT_MS = 15000;
19
- const GENERIC_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
20
- function withTimeout(p, ms, label) {
21
- let timer;
22
- const timeout = new Promise((_, reject) => {
23
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
24
- });
25
- return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
26
- }
27
- function isHttp(url) {
28
- return /^https?:\/\//i.test(url);
29
- }
30
- function stripFilePrefix(p) {
31
- if (p.startsWith('file://')) {
32
- const u = new URL(p);
33
- return u.pathname;
34
- }
35
- return p;
36
- }
37
- function looksLikePath(p) {
38
- if (isHttp(p) || p.startsWith('file://'))
39
- return false;
40
- return p.includes('/') || p.includes('\\') || p.endsWith('.json');
41
- }
42
- async function readManifestBytes(registryUrl) {
43
- if (isHttp(registryUrl)) {
44
- const res = await withTimeout(fetch(registryUrl, { headers: { 'User-Agent': GENERIC_UA, Accept: 'application/json' } }), FETCH_TIMEOUT_MS, 'registry fetch');
45
- if (!res.ok)
46
- throw new Error(`registry HTTP ${res.status}: ${registryUrl}`);
47
- return decodeMaybeGzip(Buffer.from(await res.arrayBuffer()));
48
- }
49
- const filePath = path.resolve(stripFilePrefix(registryUrl));
50
- return await fs.promises.readFile(filePath);
51
- }
52
- async function readModuleBytes(entryUrl) {
53
- if (isHttp(entryUrl)) {
54
- const res = await withTimeout(fetch(entryUrl, { headers: { 'User-Agent': GENERIC_UA, Accept: 'text/javascript,*/*' } }), FETCH_TIMEOUT_MS, 'provider fetch');
55
- if (!res.ok)
56
- throw new Error(`provider HTTP ${res.status}: ${entryUrl}`);
57
- return decodeMaybeGzip(Buffer.from(await res.arrayBuffer()));
58
- }
59
- const filePath = path.resolve(stripFilePrefix(entryUrl));
60
- return await fs.promises.readFile(filePath);
61
- }
62
- function resolveEntryUrl(entry, registryUrl) {
63
- const e = (entry ?? '').trim();
64
- if (isHttp(e) || e.startsWith('file://'))
65
- return e;
66
- if (isHttp(registryUrl))
67
- return new URL(e, registryUrl).href;
68
- const baseDir = path.dirname(path.resolve(stripFilePrefix(registryUrl)));
69
- return path.resolve(baseDir, e);
70
- }
71
- function sha256Hex(data) {
72
- return crypto.createHash('sha256').update(data).digest('hex');
73
- }
74
- function aes256CbcDecryptJson(b64url, keyUtf8, ivUtf8) {
75
- let encrypted;
76
- try {
77
- encrypted = Buffer.from(b64url, 'base64url');
78
- }
79
- catch {
80
- return null;
81
- }
82
- if (!encrypted.length || encrypted.length % 16 !== 0)
83
- return null;
84
- try {
85
- const key = Buffer.alloc(32);
86
- Buffer.from(keyUtf8).copy(key);
87
- const decipher = crypto.createDecipheriv('aes-256-cbc', key, Buffer.from(ivUtf8));
88
- const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
89
- return JSON.parse(decrypted.toString('utf8'));
90
- }
91
- catch {
92
- return null;
93
- }
94
- }
95
- function curlRaw(url, headers) {
96
- const args = [
97
- '-sSL',
98
- '-A',
99
- GENERIC_UA,
100
- ...Object.entries(headers ?? {}).flatMap(([k, v]) => ['-H', `${k}: ${v}`]),
101
- '--max-time',
102
- '15',
103
- '-w',
104
- '\n__HTTP_STATUS__%{http_code}',
105
- '--',
106
- url,
107
- ];
108
- let out;
109
- try {
110
- out = execFileSync('curl', args, { encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
111
- }
112
- catch {
113
- return null;
114
- }
115
- const m = out.match(/__HTTP_STATUS__(\d+)\s*$/);
116
- const status = m ? parseInt(m[1], 10) : 0;
117
- return { status, body: m && m.index !== undefined ? out.slice(0, m.index) : out };
118
- }
119
- function createCtx(cache) {
120
- const fetchWithTimeout = async (url, init, ms = FETCH_TIMEOUT_MS) => {
121
- return withTimeout(fetch(url, {
122
- ...init,
123
- headers: { 'User-Agent': GENERIC_UA, ...init?.headers },
124
- }), ms, `fetch ${url}`);
125
- };
126
- return {
127
- cache: {
128
- get: (key) => cache.get(key),
129
- set: (key, value, ttlSeconds) => {
130
- cache.set(key, value, ttlSeconds);
131
- },
132
- },
133
- logger: {
134
- info: (obj, msg) => {
135
- logger.info(obj, msg);
136
- },
137
- warn: (obj, msg) => {
138
- logger.warn(obj, msg);
139
- },
140
- error: (obj, msg) => {
141
- logger.error(obj, msg);
142
- },
143
- debug: (obj, msg) => {
144
- logger.debug(obj, msg);
145
- },
146
- },
147
- fetchText: async (url, init) => {
148
- try {
149
- const res = await fetchWithTimeout(url, init);
150
- if (!res.ok)
151
- return null;
152
- return await res.text();
153
- }
154
- catch {
155
- return null;
156
- }
157
- },
158
- fetchJson: async (url, init) => {
159
- const res = await fetchWithTimeout(url, init);
160
- if (!res.ok)
161
- throw new Error(`HTTP ${res.status}: ${url}`);
162
- return parseJsonBody(res);
163
- },
164
- proxyUrl: (rawUrl, referer) => {
165
- return `/api/proxy?url=${encodeURIComponent(rawUrl)}&referer=${encodeURIComponent(referer)}`;
166
- },
167
- userAgent: GENERIC_UA,
168
- titleMatch: {
169
- buildQueryVariants,
170
- pickBestMatch,
171
- },
172
- resolveBestShowId: async (title, romaji, searchFn) => {
173
- const targets = [title, romaji].filter((t) => typeof t === 'string' && t.trim().length > 0);
174
- if (targets.length === 0)
175
- return null;
176
- for (const variant of buildQueryVariants(title, romaji)) {
177
- let results;
178
- try {
179
- results = await searchFn(variant);
180
- }
181
- catch (e) {
182
- if (e.message === 'AUTH_REQUIRED')
183
- throw e;
184
- continue;
185
- }
186
- if (!results || results.length === 0)
187
- continue;
188
- const match = pickBestMatch(results.filter((r) => r && typeof r.id === 'string' && r.id.length > 0), targets);
189
- if (match)
190
- return match.item.id;
191
- }
192
- return null;
193
- },
194
- anilist: {
195
- request: (query, vars) => anilistRequest(query, vars),
196
- parseMalId,
197
- searchByTitle: searchAnilistByTitle,
198
- },
199
- kitsu: {
200
- metaByAnilistId: kitsuMetaByAnilistId,
201
- },
202
- tmdb: {
203
- base: TMDB_BASE,
204
- image: TMDB_IMAGE,
205
- get: async (path) => {
206
- try {
207
- const key = await getTmdbKey();
208
- const sep = path.includes('?') ? '&' : '?';
209
- const res = await fetchWithTimeout(`${TMDB_BASE}${path}${sep}api_key=${key}`);
210
- if (!res.ok)
211
- return null;
212
- return parseJsonBody(res);
213
- }
214
- catch {
215
- return null;
216
- }
217
- },
218
- },
219
- request: {
220
- get: (key) => requestContext.getStore()?.get(key),
221
- },
222
- cookies: {
223
- sanitizeCfClearance,
224
- buildCfClearanceCookie,
225
- },
226
- crypto: {
227
- aes256CbcDecryptJson,
228
- hmacSha256Base64Url: (key, message) => crypto.createHmac('sha256', key).update(message).digest('base64url'),
229
- },
230
- scraping: {
231
- fetch: async (urlOrOptions, maybeOptions) => {
232
- const opts = (typeof urlOrOptions === 'string'
233
- ? { url: urlOrOptions, ...(maybeOptions ?? {}) }
234
- : urlOrOptions);
235
- const { url, ...rest } = opts;
236
- const res = await gotScraping({
237
- url: url,
238
- method: 'GET',
239
- responseType: 'text',
240
- throwHttpErrors: false,
241
- ...rest,
242
- });
243
- return { statusCode: res.statusCode, body: String(res.body ?? ''), headers: res.headers };
244
- },
245
- },
246
- curl: {
247
- getJson: async (url, headers) => {
248
- try {
249
- const r = curlRaw(url, headers);
250
- if (!r || r.status !== 200)
251
- return null;
252
- return JSON.parse(r.body);
253
- }
254
- catch {
255
- return null;
256
- }
257
- },
258
- getText: async (url, headers) => {
259
- const r = curlRaw(url, headers);
260
- if (!r || r.status !== 200)
261
- return null;
262
- return r.body;
263
- },
264
- },
265
- cheerio: {
266
- load: (html) => cheerio.load(html),
267
- },
268
- };
269
- }
270
- function shapeOf(p) {
271
- if (!p || typeof p !== 'object')
272
- return null;
273
- const o = p;
274
- return typeof o.name === 'string' ? o : null;
275
- }
276
- function hasFns(o, fns) {
277
- return fns.every((f) => typeof o[f] === 'function');
278
- }
279
- function isValidVideoProvider(p) {
280
- const o = shapeOf(p);
281
- return !!o && hasFns(o, ['search', 'getEpisodes', 'getStreamUrls']);
282
- }
283
- function isValidMangaProvider(p) {
284
- const o = shapeOf(p);
285
- return !!o && hasFns(o, ['search', 'getDetail', 'getChapters', 'getPages']);
286
- }
287
- function isValidTvProvider(p) {
288
- const o = shapeOf(p);
289
- return !!o && (typeof o.getSources === 'function' || typeof o.getEmbedUrl === 'function');
290
- }
291
- function makeEmbedProvider(id, base) {
292
- const root = base.trim().replace(/\/+$/, '');
293
- return {
294
- name: id,
295
- getEmbedUrl: async (media) => {
296
- const tmdbId = Number(media.tmdbId);
297
- if (!tmdbId)
298
- return null;
299
- if (media.type === 'movie')
300
- return `${root}/movie/${tmdbId}`;
301
- return `${root}/tv/${tmdbId}/${media.season || 1}/${media.episode || 1}`;
302
- },
303
- };
304
- }
305
- async function loadEntry(item, registryUrl, cacheDir, ctx, allowUnsigned) {
306
- if (item.embedBase) {
307
- const provider = makeEmbedProvider(item.id, item.embedBase);
308
- instanceCache.set(`${item.kind ?? 'anime'}:${item.id}-${item.version}-embed`, { provider });
309
- return { provider };
310
- }
311
- const entryUrl = resolveEntryUrl(item.entry, registryUrl);
312
- await fs.promises.mkdir(cacheDir, { recursive: true });
313
- const fileName = `${item.id}-${item.version}.mjs`;
314
- const filePath = path.join(cacheDir, fileName);
315
- const instanceKey = `${item.kind ?? 'anime'}:${item.id}-${item.version}-${(item.sha256 ?? 'nosha').slice(0, 12)}`;
316
- let bytes = null;
317
- try {
318
- const cached = await fs.promises.readFile(filePath);
319
- if (item.sha256 && sha256Hex(cached) === item.sha256) {
320
- bytes = cached;
321
- }
322
- else if (!item.sha256 && allowUnsigned) {
323
- bytes = cached;
324
- }
325
- }
326
- catch {
327
- // ignore
328
- }
329
- if (bytes) {
330
- const hit = instanceCache.get(instanceKey);
331
- if (hit) {
332
- logger.debug({ provider: item.id, version: item.version }, 'remote provider reused cached instance');
333
- return { provider: hit.provider, facets: hit.facets };
334
- }
335
- }
336
- else {
337
- try {
338
- bytes = await readModuleBytes(entryUrl);
339
- }
340
- catch (err) {
341
- return {
342
- provider: null,
343
- error: `download failed: ${err.message}`,
344
- };
345
- }
346
- if (item.sha256) {
347
- const actual = sha256Hex(bytes);
348
- if (actual !== item.sha256) {
349
- return { provider: null, error: `sha256 mismatch for ${item.id}` };
350
- }
351
- }
352
- else if (!allowUnsigned) {
353
- return { provider: null, error: `missing sha256 for ${item.id}` };
354
- }
355
- await fs.promises.writeFile(filePath, bytes);
356
- }
357
- const cacheBuster = `${item.version}-${(item.sha256 ?? 'nosha').slice(0, 12)}`;
358
- const result = await instantiateModule(filePath, cacheBuster, ctx, item);
359
- if (result.provider && !result.error) {
360
- instanceCache.set(instanceKey, { provider: result.provider, facets: result.facets });
361
- }
362
- return result;
363
- }
364
- const instanceCache = new Map();
365
- function extractBrowseFacets(mod) {
366
- let genres;
367
- let orders;
368
- for (const [key, value] of Object.entries(mod)) {
369
- if (key === 'default' || !Array.isArray(value) || value.length === 0)
370
- continue;
371
- if (!value.every((v) => typeof v === 'string' && v.length > 0))
372
- continue;
373
- const list = value.filter((v) => v.length <= 64).slice(0, 500);
374
- if (list.length === 0)
375
- continue;
376
- const name = key.toUpperCase();
377
- if (name.includes('GENRE') || name.includes('TAG')) {
378
- genres ??= list;
379
- }
380
- else if (name.includes('ORDER') || name.includes('SORT')) {
381
- orders ??= list;
382
- }
383
- }
384
- if (!genres && !orders)
385
- return undefined;
386
- return { ...(genres ? { genres } : {}), ...(orders ? { orders } : {}) };
387
- }
388
- async function instantiateModule(filePath, cacheBuster, ctx, item) {
389
- const id = item.id;
390
- let mod;
391
- try {
392
- const importUrl = `${pathToFileURL(filePath).href}?v=${encodeURIComponent(cacheBuster)}`;
393
- mod = (await withTimeout(import(importUrl), FETCH_TIMEOUT_MS, `import ${id}`));
394
- }
395
- catch (err) {
396
- return {
397
- provider: null,
398
- error: `import failed: ${err.message}`,
399
- };
400
- }
401
- const factory = mod.default;
402
- if (typeof factory !== 'function') {
403
- return { provider: null, error: 'missing default factory export' };
404
- }
405
- let provider;
406
- try {
407
- provider = await withTimeout(Promise.resolve(factory(ctx)), 10000, `factory ${id}`);
408
- }
409
- catch (err) {
410
- return {
411
- provider: null,
412
- error: `factory failed: ${err.message}`,
413
- };
414
- }
415
- if (item.kind === 'manga'
416
- ? !isValidMangaProvider(provider)
417
- : item.kind === 'tv'
418
- ? !isValidTvProvider(provider)
419
- : !isValidVideoProvider(provider)) {
420
- return { provider: null, error: 'invalid provider shape' };
421
- }
422
- return { provider, facets: extractBrowseFacets(mod) };
423
- }
424
- async function loadCachedFallback(item, prev, cacheDir, ctx) {
425
- if (!prev.sha256)
426
- return { provider: null, error: 'no verified fallback' };
427
- const filePath = path.join(cacheDir, `${prev.id}-${prev.version}.mjs`);
428
- let bytes;
429
- try {
430
- bytes = await fs.promises.readFile(filePath);
431
- }
432
- catch {
433
- return { provider: null, error: 'no cached fallback file' };
434
- }
435
- if (sha256Hex(bytes) !== prev.sha256) {
436
- return { provider: null, error: 'cached fallback failed verification' };
437
- }
438
- const cacheBuster = `${prev.version}-${prev.sha256.slice(0, 12)}`;
439
- return instantiateModule(filePath, cacheBuster, ctx, { ...item, version: prev.version });
440
- }
441
- export async function loadRemoteProviders(opts) {
442
- const registryUrl = (opts.registryUrl ?? CONFIG.PROVIDER_REPO_URL ?? '').trim();
443
- const out = {
444
- providers: {},
445
- mangaProviders: {},
446
- tvProviders: {},
447
- catalog: [],
448
- proxyRules: [],
449
- };
450
- if (!registryUrl)
451
- return out;
452
- const cacheDir = path.join(CONFIG.ROOT, 'remote-providers');
453
- const cachedManifestPath = path.join(cacheDir, 'registry.json');
454
- let prevRegistry = null;
455
- try {
456
- prevRegistry = parseRegistry(JSON.parse((await fs.promises.readFile(cachedManifestPath)).toString('utf8')));
457
- }
458
- catch {
459
- // ignore
460
- }
461
- const prevById = new Map((prevRegistry?.providers ?? []).map((p) => [p.id.toLowerCase(), p]));
462
- let raw;
463
- try {
464
- const bytes = await readManifestBytes(registryUrl);
465
- raw = JSON.parse(bytes.toString('utf8'));
466
- await fs.promises.mkdir(cacheDir, { recursive: true });
467
- await fs.promises.writeFile(cachedManifestPath, JSON.stringify(raw));
468
- }
469
- catch (err) {
470
- logger.error({ err, registryUrl }, 'remote providers: manifest fetch failed, trying disk cache');
471
- try {
472
- raw = JSON.parse((await fs.promises.readFile(cachedManifestPath)).toString('utf8'));
473
- }
474
- catch {
475
- return out;
476
- }
477
- }
478
- let registry;
479
- try {
480
- registry = parseRegistry(raw);
481
- }
482
- catch (err) {
483
- logger.error({ err, registryUrl }, 'remote providers: manifest parse failed');
484
- return out;
485
- }
486
- const enabledSet = new Set((opts.enabledProviders ?? []).map((s) => s.toLowerCase()));
487
- const explicitFilter = enabledSet.size > 0;
488
- const ctx = createCtx(opts.cache);
489
- const allowUnsigned = opts.allowUnsigned ??
490
- (process.env.DANGO_ALLOW_UNSIGNED_PROVIDERS === '1' || looksLikePath(registryUrl));
491
- for (const item of registry.providers) {
492
- const key = item.id.toLowerCase();
493
- if (item.enabledByDefault === false && (!explicitFilter || !enabledSet.has(key))) {
494
- out.catalog.push(toCatalog(item, false, 'disabled by default'));
495
- continue;
496
- }
497
- if (explicitFilter && !enabledSet.has(key)) {
498
- out.catalog.push(toCatalog(item, false, 'not in enabledProviders'));
499
- continue;
500
- }
501
- const { provider, facets, error } = await loadEntry(item, registryUrl, cacheDir, ctx, allowUnsigned);
502
- if (provider && !error) {
503
- if (item.kind === 'manga' && isValidMangaProvider(provider)) {
504
- out.mangaProviders[key] = provider;
505
- }
506
- else if (item.kind === 'tv' && isValidTvProvider(provider)) {
507
- out.tvProviders[key] = provider;
508
- }
509
- else if (item.kind !== 'manga' && item.kind !== 'tv' && isValidVideoProvider(provider)) {
510
- out.providers[key] = provider;
511
- }
512
- else {
513
- out.catalog.push(toCatalog(item, false, 'invalid provider shape for kind'));
514
- logger.warn({ provider: item.id }, 'remote provider kind mismatch, skipped');
515
- continue;
516
- }
517
- out.catalog.push(withFacets(facets, withServers(item, provider, toCatalog(item, true))));
518
- if (item.proxy)
519
- out.proxyRules.push(item.proxy);
520
- logger.info({ provider: item.id, version: item.version }, 'remote provider loaded');
521
- }
522
- else {
523
- const prev = prevById.get(key);
524
- if (prev && prev.version !== item.version) {
525
- const fb = await loadCachedFallback(item, prev, cacheDir, ctx);
526
- if (fb.provider && !fb.error) {
527
- if (item.kind === 'manga' && isValidMangaProvider(fb.provider)) {
528
- out.mangaProviders[key] = fb.provider;
529
- }
530
- else if (item.kind === 'tv' && isValidTvProvider(fb.provider)) {
531
- out.tvProviders[key] = fb.provider;
532
- }
533
- else if (item.kind !== 'manga' &&
534
- item.kind !== 'tv' &&
535
- isValidVideoProvider(fb.provider)) {
536
- out.providers[key] = fb.provider;
537
- }
538
- else {
539
- fb.error = 'cached fallback failed validation';
540
- }
541
- }
542
- if (fb.provider && !fb.error) {
543
- out.catalog.push({
544
- ...withFacets(fb.facets, withServers(item, fb.provider, toCatalog({ ...item, version: prev.version }, true))),
545
- error: `serving cached ${prev.version}: ${error}`,
546
- });
547
- if (item.proxy)
548
- out.proxyRules.push(item.proxy);
549
- logger.warn({ provider: item.id, error, fallback: prev.version }, 'remote provider update failed, serving cached version');
550
- continue;
551
- }
552
- }
553
- out.catalog.push(toCatalog(item, false, error));
554
- logger.warn({ provider: item.id, error }, 'remote provider skipped');
555
- }
556
- }
557
- const failedIds = new Set(out.catalog.filter((c) => !c.loaded).map((c) => `${c.id}-`));
558
- try {
559
- const expected = new Set(registry.providers.map((item) => `${item.id}-${item.version}.mjs`.toLowerCase()));
560
- const expectedInstances = new Set(registry.providers.map((item) => `${item.kind ?? 'anime'}:${item.id}-${item.version}-${(item.sha256 ?? 'nosha').slice(0, 12)}`.toLowerCase()));
561
- for (const key of instanceCache.keys()) {
562
- if (!expectedInstances.has(key.toLowerCase()))
563
- instanceCache.delete(key);
564
- }
565
- const files = await fs.promises.readdir(cacheDir);
566
- for (const file of files) {
567
- if (!file.toLowerCase().endsWith('.mjs'))
568
- continue;
569
- if (!expected.has(file.toLowerCase())) {
570
- if ([...failedIds].some((prefix) => file.toLowerCase().startsWith(prefix)))
571
- continue;
572
- await fs.promises.unlink(path.join(cacheDir, file));
573
- logger.info({ file }, 'remote providers: removed superseded module');
574
- }
575
- }
576
- }
577
- catch (err) {
578
- logger.warn({ err }, 'remote providers: superseded module cleanup failed');
579
- }
580
- return out;
581
- }
582
- function withServers(item, provider, cat) {
583
- if (item.kind !== 'tv' || !provider || typeof provider !== 'object')
584
- return cat;
585
- const servers = provider.servers;
586
- if (Array.isArray(servers) && servers.every((s) => typeof s === 'string') && servers.length > 0) {
587
- return { ...cat, servers: [...servers] };
588
- }
589
- return cat;
590
- }
591
- function withFacets(facets, cat) {
592
- const genres = (facets?.genres ?? []).length > 0 ? facets?.genres : undefined;
593
- const orders = (facets?.orders ?? []).length > 0 ? facets?.orders : undefined;
594
- if (!genres && !orders)
595
- return cat;
596
- return { ...cat, facets: { ...(genres ? { genres } : {}), ...(orders ? { orders } : {}) } };
597
- }
598
- function toCatalog(item, loaded, error) {
599
- return {
600
- id: item.id.toLowerCase(),
601
- label: item.label,
602
- version: item.version,
603
- mature: item.mature,
604
- kind: item.kind ?? 'anime',
605
- sub: item.sub,
606
- tier: item.tier,
607
- modes: item.modes ?? (item.kind === 'tv' ? [] : ['sub', 'dub']),
608
- browse: item.browse,
609
- enabledByDefault: item.enabledByDefault !== false,
610
- loaded,
611
- remote: true,
612
- error,
613
- };
614
- }