-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathnode_test_syncnextplugin_play.js
More file actions
executable file
·1239 lines (1091 loc) · 36 KB
/
node_test_syncnextplugin_play.js
File metadata and controls
executable file
·1239 lines (1091 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require("fs");
const fsp = fs.promises;
const path = require("path");
const vm = require("vm");
const DEFAULT_UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15";
function getArg(name, fallback) {
const prefix = `--${name}=`;
const hit = process.argv.find((arg) => arg.startsWith(prefix));
if (!hit) return fallback;
return hit.slice(prefix.length);
}
function hasFlag(name) {
return process.argv.includes(`--${name}`);
}
function toInt(value, fallback) {
const n = Number(value);
return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
}
function tsCompact() {
const d = new Date();
const p2 = (n) => String(n).padStart(2, "0");
return (
d.getFullYear() +
p2(d.getMonth() + 1) +
p2(d.getDate()) +
"-" +
p2(d.getHours()) +
p2(d.getMinutes()) +
p2(d.getSeconds())
);
}
function isoNow() {
return new Date().toISOString();
}
function createLogger(logPath) {
const stream = fs.createWriteStream(logPath, { flags: "a" });
return {
log(msg) {
const line = String(msg == null ? "" : msg);
process.stdout.write(line + "\n");
stream.write(line + "\n");
},
error(msg) {
const line = String(msg == null ? "" : msg);
process.stderr.write(line + "\n");
stream.write(line + "\n");
},
close() {
stream.end();
},
};
}
function createFetchImpl() {
if (typeof fetch === "function") {
return fetch.bind(globalThis);
}
try {
const mod = require("node-fetch");
return (mod.default || mod);
} catch (_) {}
try {
const fallback = require(path.resolve(
__dirname,
"..",
"SyncnextPlugin_official",
"node_modules",
"node-fetch"
));
return fallback.default || fallback;
} catch (_) {}
throw new Error("fetch is unavailable. Use Node 18+ or install node-fetch.");
}
const fetchImpl = createFetchImpl();
async function fetchWithTimeout(url, options, timeoutMs) {
const ms = toInt(timeoutMs, 20000);
if (typeof AbortController === "function") {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), ms);
try {
return await fetchImpl(url, Object.assign({}, options || {}, { signal: ac.signal }));
} finally {
clearTimeout(timer);
}
}
return await Promise.race([
fetchImpl(url, options || {}),
new Promise((_, reject) => {
setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
}),
]);
}
function looksLikeURL(input) {
return /^https?:\/\//i.test(String(input || ""));
}
function normalizeURL(url) {
return String(url || "").trim();
}
function removeSyncnextPluginScheme(apiValue) {
return String(apiValue || "").replace(/^syncnextplugin:\/\//i, "");
}
function extractPluginFolderByConfigURL(configURL) {
const hit = String(configURL || "").match(/\/(plugin_[^\/?#]+)\/config\.json(?:[?#].*)?$/i);
return hit && hit[1] ? hit[1] : "";
}
function headersToObject(headers) {
const out = {};
if (headers && typeof headers.forEach === "function") {
headers.forEach((value, key) => {
out[key] = value;
});
}
const setCookies = extractSetCookies(headers);
if (setCookies.length > 0) {
out["set-cookie"] = setCookies;
out["Set-Cookie"] = setCookies;
}
return out;
}
function extractSetCookies(headers) {
if (!headers) return [];
if (typeof headers.getSetCookie === "function") {
const arr = headers.getSetCookie();
return Array.isArray(arr) ? arr.filter(Boolean) : [];
}
if (typeof headers.raw === "function") {
const raw = headers.raw();
const arr = raw && raw["set-cookie"];
return Array.isArray(arr) ? arr.filter(Boolean) : [];
}
if (typeof headers.get === "function") {
const value = headers.get("set-cookie");
if (value) return [value];
}
return [];
}
function safeJSONParse(input, fallback) {
try {
return JSON.parse(input);
} catch (_) {
return fallback;
}
}
function containsSafeLineMarkers(text) {
return /safeline|SafeLineChallenge|雷池|\/\.safeline\/|Protected By .*WAF|访问已被拦截|Access Forbidden/i.test(
String(text || "")
);
}
function extractHeaderValue(headers, key) {
const lowerKey = String(key || "").toLowerCase();
if (!headers || typeof headers !== "object") return "";
for (const k of Object.keys(headers)) {
if (String(k).toLowerCase() === lowerKey) {
return String(headers[k] || "");
}
}
return "";
}
function isSafeLineChallenge(status, body, headers) {
if (Number(status) === 468) return true;
const text = String(body || "");
const contentType = extractHeaderValue(headers, "content-type");
if (/text\/html/i.test(contentType) && containsSafeLineMarkers(text)) return true;
return containsSafeLineMarkers(text);
}
function compactHTTPEvents(events) {
return (events || []).slice(-6).map((item) => ({
method: item.method,
url: item.url,
status: item.status,
safeLine: !!item.safeLine,
error: item.error || "",
}));
}
function explainFailure(errorText, httpEvents) {
const text = String(errorText || "");
const events = Array.isArray(httpEvents) ? httpEvents : [];
const safeLineEvents = events.filter((item) => item && item.safeLine);
if (safeLineEvents.length > 0) {
return {
reasonCode: "safeline_challenge_blocked",
reasonText: "偵測到 SafeLine 挑戰頁,導致播放器頁未返回原始 HTML",
};
}
if (/emptyView:/i.test(text)) {
return {
reasonCode: "plugin_empty_view",
reasonText: "插件回傳 emptyView,未取得可播放地址",
};
}
if (/callback timeout/i.test(text)) {
return {
reasonCode: "callback_timeout",
reasonText: "等待插件回調超時,可能是站點回應慢或頁面結構改版",
};
}
return {
reasonCode: "unknown",
reasonText: text || "unknown error",
};
}
function parseArrayPayload(payload) {
if (Array.isArray(payload)) return payload;
if (payload == null) return [];
if (typeof payload === "string") {
const text = payload.trim();
if (!text) return [];
const parsed = safeJSONParse(text, null);
if (Array.isArray(parsed)) return parsed;
if (parsed && typeof parsed === "object") return [parsed];
return [];
}
if (typeof payload === "object") return [payload];
return [];
}
function pickMediaDetailURL(media) {
if (!media || typeof media !== "object") return "";
const candidates = [
media.detailURLString,
media.detailURL,
media.episodeDetailURL,
media.href,
media.url,
media.id,
];
for (const value of candidates) {
const text = String(value || "").trim();
if (looksLikeURL(text)) return text;
}
for (const value of candidates) {
const text = String(value || "").trim();
if (text) return text;
}
return "";
}
function pickEpisodeURL(episode) {
if (!episode || typeof episode !== "object") return "";
const candidates = [
episode.episodeDetailURL,
episode.detailURLString,
episode.playURL,
episode.url,
episode.id,
];
for (const value of candidates) {
const text = String(value || "").trim();
if (looksLikeURL(text)) return text;
}
for (const value of candidates) {
const text = String(value || "").trim();
if (text) return text;
}
return "";
}
function normalizePageURL(urlTemplate) {
return String(urlTemplate || "")
.replace(/\$\{pageNumber\}/g, "1")
.replace(/\$\{keyword\}/g, "test");
}
function pickIndexPage(config) {
const pages = Array.isArray(config && config.pages) ? config.pages : [];
if (pages.length === 0) return null;
let page = pages.find((item) => String(item && item.key || "").toLowerCase() === "index");
if (!page) {
page = pages.find((item) => /最近|更新|首頁|首页/i.test(String(item && item.title || "")));
}
if (!page) page = pages[0];
return page;
}
function toAbsoluteFilePathIfExists(filePath) {
try {
if (fs.existsSync(filePath)) return path.resolve(filePath);
} catch (_) {}
return "";
}
async function readLocalText(filePath) {
return await fsp.readFile(filePath, "utf8");
}
async function readRemoteText(url, timeoutMs) {
const res = await fetchWithTimeout(
url,
{
method: "GET",
headers: {
"User-Agent": DEFAULT_UA,
Accept: "*/*",
},
redirect: "follow",
},
timeoutMs
);
if (!res.ok) {
throw new Error(`GET ${url} failed: ${res.status}`);
}
return await res.text();
}
async function resolvePluginSource(subscription, options) {
const apiURL = normalizeURL(removeSyncnextPluginScheme(subscription.api));
if (!looksLikeURL(apiURL)) {
throw new Error(`invalid syncnextPlugin URL: ${subscription.api}`);
}
const pluginFolder = extractPluginFolderByConfigURL(apiURL);
const pluginRoot = options.pluginRoot;
let mode = "remote";
let localDir = "";
if (pluginFolder && pluginRoot) {
const candidateDir = path.join(pluginRoot, pluginFolder);
const localConfig = path.join(candidateDir, "config.json");
if (toAbsoluteFilePathIfExists(localConfig)) {
mode = "local";
localDir = candidateDir;
}
}
let configText = "";
if (mode === "local") {
configText = await readLocalText(path.join(localDir, "config.json"));
} else {
configText = await readRemoteText(apiURL, options.requestTimeoutMs);
}
const config = safeJSONParse(configText, null);
if (!config || typeof config !== "object") {
throw new Error("config.json parse failed");
}
const files = Array.isArray(config.files) ? config.files.slice() : [];
if (files.length === 0) {
throw new Error("config.files is empty");
}
const baseRemoteURL = apiURL.replace(/\/config\.json(?:[?#].*)?$/i, "");
const loadedFiles = [];
for (const fileName of files) {
const name = String(fileName || "").trim();
if (!name) continue;
let content = "";
if (mode === "local") {
const abs = path.join(localDir, name);
content = await readLocalText(abs);
loadedFiles.push({ name, source: abs, content });
continue;
}
const fileURL = looksLikeURL(name) ? name : `${baseRemoteURL}/${name}`;
content = await readRemoteText(fileURL, options.requestTimeoutMs);
loadedFiles.push({ name, source: fileURL, content });
}
return {
subscription,
apiURL,
pluginFolder,
mode,
config,
files: loadedFiles,
};
}
function buildPlayerResult(callbackType, payload) {
if (callbackType === "toPlayer") {
return {
url: String(payload == null ? "" : payload).trim(),
headers: {},
raw: payload,
};
}
if (callbackType === "toPlayerByJSON") {
const parsed =
typeof payload === "string"
? safeJSONParse(payload, {})
: (payload && typeof payload === "object" ? payload : {});
return {
url: String(parsed.url || "").trim(),
headers: parsed.headers && typeof parsed.headers === "object" ? parsed.headers : {},
raw: payload,
};
}
if (callbackType === "toPlayerCandidates") {
const parsed =
typeof payload === "string"
? safeJSONParse(payload, {})
: (payload && typeof payload === "object" ? payload : {});
const list = Array.isArray(parsed.candidates) ? parsed.candidates : [];
const first = list[0] || {};
const url = typeof first === "string" ? first : String(first.url || "");
const headers =
first && typeof first === "object" && first.headers && typeof first.headers === "object"
? first.headers
: {};
return {
url: url.trim(),
headers,
raw: payload,
};
}
return { url: "", headers: {}, raw: payload };
}
function buildInvocationAdapter(options) {
const state = {
pending: null,
emptyViews: [],
};
function reset() {
state.pending = null;
state.emptyViews = [];
}
function setPending(expected, timeoutMs) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
state.pending = null;
const hint =
state.emptyViews.length > 0
? `; emptyView=${state.emptyViews[state.emptyViews.length - 1]}`
: "";
reject(new Error(`callback timeout (${expected})${hint}`));
}, timeoutMs);
state.pending = {
expected,
resolve,
reject,
timer,
};
});
}
function clearPending() {
if (!state.pending) return;
clearTimeout(state.pending.timer);
state.pending = null;
}
function isAccepted(expected, callbackType) {
if (expected === "medias") {
return callbackType === "toMedias" || callbackType === "toSearchMedias";
}
if (expected === "episodes") {
return callbackType === "toEpisodes" || callbackType === "toEpisodesCandidates";
}
if (expected === "player") {
return (
callbackType === "toPlayer" ||
callbackType === "toPlayerByJSON" ||
callbackType === "toPlayerCandidates"
);
}
return false;
}
function onCallback(callbackType, payload, key) {
if (!state.pending) return;
if (!isAccepted(state.pending.expected, callbackType)) return;
const pending = state.pending;
clearPending();
pending.resolve({
callbackType,
payload,
key,
emptyViews: state.emptyViews.slice(),
});
}
function onEmptyView(message) {
const text = String(message == null ? "" : message);
state.emptyViews.push(text);
if (
options.failOnEmptyView &&
state.pending &&
(state.pending.expected === "player" || state.pending.expected === "episodes")
) {
const pending = state.pending;
clearPending();
pending.reject(new Error(`emptyView: ${text || "unknown"}`));
}
}
async function invoke(context, fnName, args, expected, timeoutMs) {
reset();
const fn = context[fnName];
if (typeof fn !== "function") {
throw new Error(`function not found: ${fnName}`);
}
const waitCallback = setPending(expected, timeoutMs);
try {
const ret = fn.apply(context, args || []);
if (ret && typeof ret.then === "function") {
ret.catch((error) => {
if (state.pending) {
const pending = state.pending;
clearPending();
pending.reject(error);
}
});
}
} catch (error) {
clearPending();
throw error;
}
return await waitCallback;
}
return {
onCallback,
onEmptyView,
invoke,
};
}
function createPluginRuntime(pluginSource, options, logger) {
const adapter = buildInvocationAdapter(options);
const httpEvents = [];
function pushHTTPEvent(event) {
httpEvents.push(event);
if (httpEvents.length > 500) {
httpEvents.shift();
}
}
async function doHTTP(req, methodOverride) {
const request = req && typeof req === "object" ? req : {};
const url = String(request.url || "").trim();
if (!url) {
throw new Error("$http.fetch missing req.url");
}
const method = String(methodOverride || request.method || "GET").toUpperCase();
const headers = Object.assign({}, request.headers || {});
if (!headers["User-Agent"] && !headers["user-agent"]) {
headers["User-Agent"] = DEFAULT_UA;
}
const fetchOptions = {
method,
headers,
redirect: "follow",
};
if (method !== "HEAD" && request.body != null && method !== "GET") {
fetchOptions.body = typeof request.body === "string" ? request.body : JSON.stringify(request.body);
}
const event = {
at: isoNow(),
method,
url,
status: 0,
safeLine: false,
error: "",
};
try {
const response = await fetchWithTimeout(url, fetchOptions, options.requestTimeoutMs);
const responseHeaders = headersToObject(response.headers);
let body = method === "HEAD" ? "" : await response.text();
let status = response.status;
let finalURL = response.url;
event.status = status;
event.safeLine = method === "GET" && isSafeLineChallenge(status, body, responseHeaders);
pushHTTPEvent(event);
return {
status,
statusCode: status,
headers: responseHeaders,
body,
url: finalURL,
};
} catch (error) {
event.error = error.message || String(error);
if (options.verboseConsole) {
logger.error(`[http-error] ${method} ${url} -> ${error.message || error}`);
}
pushHTTPEvent(event);
return {
status: 0,
statusCode: 0,
headers: {},
body: "",
url,
error: error.message || String(error),
};
}
}
const context = {
console: {
log: (...args) => {
if (!options.verboseConsole) return;
logger.log(
`[plugin-log] ${args
.map((item) => (typeof item === "string" ? item : JSON.stringify(item)))
.join(" ")}`
);
},
error: (...args) => {
logger.error(
`[plugin-error] ${args
.map((item) => (typeof item === "string" ? item : JSON.stringify(item)))
.join(" ")}`
);
},
},
setTimeout,
clearTimeout,
setInterval,
clearInterval,
Promise,
Buffer,
URL,
URLSearchParams,
atob: (input) => Buffer.from(String(input || ""), "base64").toString("binary"),
btoa: (input) => Buffer.from(String(input || ""), "binary").toString("base64"),
$http: {
fetch: (req) => doHTTP(req, null),
head: (req) => doHTTP(req, "HEAD"),
},
$next: {
toMedias: (json, key) => adapter.onCallback("toMedias", json, key),
toSearchMedias: (json, key) => adapter.onCallback("toSearchMedias", json, key),
toEpisodes: (json, key) => adapter.onCallback("toEpisodes", json, key),
toEpisodesCandidates: (json, key) => adapter.onCallback("toEpisodesCandidates", json, key),
toPlayer: (value, key) => adapter.onCallback("toPlayer", value, key),
toPlayerByJSON: (json, key) => adapter.onCallback("toPlayerByJSON", json, key),
toPlayerCandidates: (json, key) => adapter.onCallback("toPlayerCandidates", json, key),
emptyView: (msg) => adapter.onEmptyView(msg),
aliLink: () => {},
aliPlay: () => {},
},
};
context.window = context;
context.global = context;
context.self = context;
vm.createContext(context);
for (const file of pluginSource.files) {
vm.runInContext(file.content, context, {
filename: file.name,
timeout: options.vmLoadTimeoutMs,
});
}
return {
context,
invoke: (fnName, args, expected, timeoutMs) =>
adapter.invoke(context, fnName, args, expected, timeoutMs),
getHTTPEvents: () => httpEvents.slice(),
getHTTPEventsSince: (index) => httpEvents.slice(index || 0),
};
}
function stageTimeoutMs(stageConfig, fallbackMs) {
const sec = Number(stageConfig && stageConfig.timeout);
if (Number.isFinite(sec) && sec > 0) {
return Math.max(fallbackMs, Math.floor(sec * 1000) + 5000);
}
return fallbackMs;
}
async function probePlayableURL(url, headers, options) {
const result = {
ok: false,
method: "HEAD",
status: 0,
contentType: "",
error: "",
};
const target = String(url || "").trim();
if (!looksLikeURL(target)) {
result.error = "non-http url";
return result;
}
const reqHeaders = Object.assign({}, headers || {});
if (!reqHeaders["User-Agent"] && !reqHeaders["user-agent"]) {
reqHeaders["User-Agent"] = DEFAULT_UA;
}
try {
const headRes = await fetchWithTimeout(
target,
{
method: "HEAD",
headers: reqHeaders,
redirect: "follow",
},
options.probeTimeoutMs
);
result.status = headRes.status;
result.contentType = headRes.headers.get("content-type") || "";
if (headRes.status >= 200 && headRes.status < 400) {
result.ok = true;
return result;
}
} catch (error) {
result.error = error.message || String(error);
}
result.method = "GET";
const getHeaders = Object.assign({}, reqHeaders, { Range: "bytes=0-1023" });
try {
const getRes = await fetchWithTimeout(
target,
{
method: "GET",
headers: getHeaders,
redirect: "follow",
},
options.probeTimeoutMs
);
const body = await getRes.text();
const contentType = getRes.headers.get("content-type") || "";
result.status = getRes.status;
result.contentType = contentType;
const looksLikeMediaType =
/mpegurl|video|octet-stream|application\/vnd\.apple\.mpegurl|audio/i.test(contentType);
const looksLikeM3U8 = /^#EXTM3U/i.test(String(body || "").trim());
const looksLikeMediaURL = /\.(m3u8|mp4|m4v|mov|flv|ts)(\?|$)/i.test(target);
if (getRes.status >= 200 && getRes.status < 400 && (looksLikeMediaType || looksLikeM3U8 || looksLikeMediaURL)) {
result.ok = true;
return result;
}
if (!result.error) {
result.error = `status ${getRes.status}`;
}
} catch (error) {
result.error = error.message || String(error);
}
return result;
}
function buildSubscriptionLabel(entry, index) {
const name = String(entry.name || entry.title || "").trim();
if (name) return name;
return `plugin-${index + 1}`;
}
async function runSinglePlugin(subscription, index, options, logger) {
const startedAt = isoNow();
const pluginReport = {
index: index + 1,
subscriptionName: buildSubscriptionLabel(subscription, index),
api: subscription.api,
startedAt,
endedAt: "",
mode: "",
pluginName: "",
pluginFolder: "",
indexPage: null,
summary: {
casesTotal: 0,
ok: 0,
fail: 0,
},
cases: [],
errors: [],
};
try {
const source = await resolvePluginSource(subscription, options);
pluginReport.mode = source.mode;
pluginReport.pluginFolder = source.pluginFolder;
pluginReport.pluginName = String(source.config.name || pluginReport.subscriptionName);
const runtime = createPluginRuntime(source, options, logger);
function buildFailureMeta(errorText, stageEvents) {
const explained = explainFailure(errorText, stageEvents);
return {
reasonCode: explained.reasonCode,
reasonText: explained.reasonText,
httpDiagnostics: compactHTTPEvents(stageEvents),
};
}
const indexPage = pickIndexPage(source.config);
if (!indexPage || !indexPage.javascript || !indexPage.url) {
throw new Error("index page config missing");
}
const indexURL = normalizePageURL(indexPage.url);
const indexTimeout = stageTimeoutMs(indexPage, options.invokeTimeoutMs);
const episodesTimeout = stageTimeoutMs(source.config.episodes, options.invokeTimeoutMs);
const playerTimeout = stageTimeoutMs(source.config.player, options.invokeTimeoutMs);
pluginReport.indexPage = {
key: indexPage.key || "",
title: indexPage.title || "",
url: indexURL,
javascript: indexPage.javascript,
};
logger.log(
`[plugin ${index + 1}] ${pluginReport.pluginName} | mode=${source.mode} | index=${indexURL}`
);
const mediasResult = await runtime.invoke(
indexPage.javascript,
[indexURL, source.apiURL],
"medias",
indexTimeout
);
const medias = parseArrayPayload(mediasResult.payload);
const selectedMedias =
options.limitMedias > 0 ? medias.slice(0, options.limitMedias) : medias.slice();
logger.log(
`[plugin ${index + 1}] medias total=${medias.length}, testing=${selectedMedias.length}`
);
if (selectedMedias.length === 0) {
const mediaFailure = explainFailure("no medias returned", runtime.getHTTPEvents());
throw new Error(`no medias returned; ${mediaFailure.reasonText}`);
}
for (let mediaIndex = 0; mediaIndex < selectedMedias.length; mediaIndex++) {
const media = selectedMedias[mediaIndex];
const mediaTitle = String(media && media.title || `media-${mediaIndex + 1}`);
const detailURL = pickMediaDetailURL(media);
if (!detailURL) {
const failureMeta = buildFailureMeta("detailURL missing", []);
pluginReport.cases.push({
ok: false,
stage: "episodes",
mediaTitle,
episodeTitle: "",
detailURL: "",
episodeURL: "",
playURL: "",
probe: null,
error: "detailURL missing",
reasonCode: failureMeta.reasonCode,
reasonText: failureMeta.reasonText,
httpDiagnostics: failureMeta.httpDiagnostics,
});
logger.log(`[FAIL] ${pluginReport.pluginName} | ${mediaTitle} | detailURL missing`);
continue;
}
let episodesResult;
const episodesHTTPIndex = runtime.getHTTPEvents().length;
try {
episodesResult = await runtime.invoke(
source.config.episodes && source.config.episodes.javascript,
[detailURL],
"episodes",
episodesTimeout
);
} catch (error) {
const stageEvents = runtime.getHTTPEventsSince(episodesHTTPIndex);
const failureMeta = buildFailureMeta(error.message || String(error), stageEvents);
pluginReport.cases.push({
ok: false,
stage: "episodes",
mediaTitle,
episodeTitle: "",
detailURL,
episodeURL: "",
playURL: "",
probe: null,
error: error.message || String(error),
reasonCode: failureMeta.reasonCode,
reasonText: failureMeta.reasonText,
httpDiagnostics: failureMeta.httpDiagnostics,
});
logger.log(
`[FAIL] ${pluginReport.pluginName} | ${mediaTitle} | episodes -> ${error.message || error} | reason=${failureMeta.reasonCode}`
);
continue;
}
let episodes = [];
if (episodesResult.callbackType === "toEpisodesCandidates") {
const parsed =
typeof episodesResult.payload === "string"
? safeJSONParse(episodesResult.payload, {})
: (episodesResult.payload && typeof episodesResult.payload === "object"
? episodesResult.payload
: {});
const candidates = Array.isArray(parsed.candidates) ? parsed.candidates : [];
const firstCandidate = candidates[0] || {};
episodes = parseArrayPayload(firstCandidate.list || firstCandidate.episodes || []);
} else {
episodes = parseArrayPayload(episodesResult.payload);
}
const targetEpisodes = options.allEpisodes ? episodes : episodes.slice(0, 1);
if (targetEpisodes.length === 0) {
const failureMeta = buildFailureMeta("no episodes", runtime.getHTTPEventsSince(episodesHTTPIndex));
pluginReport.cases.push({
ok: false,
stage: "episodes",
mediaTitle,
episodeTitle: "",
detailURL,
episodeURL: "",
playURL: "",
probe: null,
error: "no episodes",
reasonCode: failureMeta.reasonCode,
reasonText: failureMeta.reasonText,
httpDiagnostics: failureMeta.httpDiagnostics,
});
logger.log(
`[FAIL] ${pluginReport.pluginName} | ${mediaTitle} | no episodes | reason=${failureMeta.reasonCode}`
);
continue;
}
for (let epIndex = 0; epIndex < targetEpisodes.length; epIndex++) {
const episode = targetEpisodes[epIndex];
const episodeTitle = String(episode && episode.title || `episode-${epIndex + 1}`);
const episodeURL = pickEpisodeURL(episode);
if (!episodeURL) {
const failureMeta = buildFailureMeta("episodeURL missing", []);
pluginReport.cases.push({
ok: false,
stage: "player",
mediaTitle,
episodeTitle,