Repository navigation
Expand file tree
/
Copy pathEmbyNativeTrailer.js
More file actions
2053 lines (1802 loc) · 76.8 KB
/
Copy pathEmbyNativeTrailer.js
File metadata and controls
2053 lines (1802 loc) · 76.8 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
// 本脚本的作用为在 CustomCssJS 插件下:将 Emby 的原生预告片按钮替换为外部预告片源。
// 如果 Emby 因为 NFO 文件中没有预告片 URL 而隐藏了原生预告片按钮,则此脚本会注入一个新的预告片按钮
// 当用户点击预告片按钮时,脚本会尝试从页面中提取番号信息,并查找预告片并播放,特殊番号需要使用 EmbyCustomTrailerBridge.user.js 提供的桥接 API 查询
(function () {
"use strict";
const SCRIPT_KEY = "__customTrailerInstalled";
if (window[SCRIPT_KEY]) return;
window[SCRIPT_KEY] = true;
console.log("[CustomTrailer] Script loaded");
// Only intercept trailer clicks inside these Emby library ids.
const ENABLED_LIBRARIES = [
"565020",
"565027"
];
const API_BASE = "https://javp.cc.cd/trailers/";
const TRAILER_CACHE_PREFIX = "customTrailerResult_v3_";
const JAVP_QUALITY_OPTIONS = [
{ quality: "4k", label: "4K" },
{ quality: "hhb", label: "1080P" },
{ quality: "hmb", label: "720P" },
{ quality: "mhb", label: "576P" },
{ quality: "mmb", label: "432P" }
];
const EXTRA_QUALITY_OPTIONS = [
{ quality: "1080p", label: "1080P" },
{ quality: "720p", label: "720P" },
{ quality: "540p", label: "540P" },
{ quality: "480p", label: "480P" },
{ quality: "396p", label: "396P" },
{ quality: "360p", label: "360P" },
{ quality: "240p", label: "240P" }
];
const ALL_QUALITY_OPTIONS = JAVP_QUALITY_OPTIONS.concat(EXTRA_QUALITY_OPTIONS);
const MGSTAGE_PREFIX_MAP = {
LUXU: "259LUXU",
MIUM: "300MIUM",
GANA: "200GANA",
SIRO: "SIRO",
DCV: "277DCV",
JNT: "390JNT",
JAC: "390JAC",
HHH: "451HHH",
HLM: "436HLM",
SYS: "332SYS",
NAMA: "332NAMA",
HEN: "353HEN",
ARA: "261ARA"
};
const CUSTOM_BUTTON_CLASS = "custom-trailer-button";
const CUSTOM_BUTTON_SELECTOR = "." + CUSTOM_BUTTON_CLASS;
const CUSTOM_ACTIONS_CLASS = "custom-trailer-actions";
const CUSTOM_STYLE_ID = "custom-trailer-style";
const TRAILER_BUTTON_SELECTOR = [
CUSTOM_BUTTON_SELECTOR,
".itemTrailerButton",
".btnPlayTrailer",
"[data-action='playTrailer']",
"[data-action='playtrailer']",
"button[title*='Trailer']",
"button[aria-label*='Trailer']",
"button[title*='预告']",
"button[aria-label*='预告']"
].join(",");
let isHandlingClick = false;
let scanTimer = null;
let ensureRunId = 0;
const itemLibraryCache = new Map();
const itemLibraryPending = new Map();
window.addEventListener("click", handleTrailerClick, true);
document.addEventListener("click", handleTrailerClick, true);
window.addEventListener("hashchange", scheduleEnsureTrailerButtonBurst);
window.addEventListener("popstate", scheduleEnsureTrailerButtonBurst);
window.addEventListener("pageshow", scheduleEnsureTrailerButtonBurst);
startTrailerButtonObserver();
installDebugApi();
function handleTrailerClick(e) {
if (isInsideTrailerOverlay(e.target)) return;
const btn = findTrailerButton(e.target);
if (!btn) return;
const detailRoot = getVisibleDetailRoot() || getDetailRootForNode(btn);
const clickScope = detailRoot || btn;
const itemId = getCurrentItemId(clickScope);
const isCustomButton = btn.classList?.contains(CUSTOM_BUTTON_CLASS);
const cachedState = getCachedLibraryState(clickScope);
const buttonLibraryId = isCustomButton ? btn.dataset.customTrailerLibraryId : null;
const libraryId = cachedState?.enabled ? cachedState.libraryId : buttonLibraryId;
console.log("[CustomTrailer] 当前 API LibraryId:", libraryId || null, "itemId:", itemId);
if (isCustomButton && btn.dataset.customTrailerItemId && itemId && btn.dataset.customTrailerItemId !== String(itemId)) {
removeCustomTrailerButtons(document);
console.log("[CustomTrailer] 自定义按钮已过期,忽略本次点击");
return;
}
if (!libraryId || !isEnabledLibraryId(libraryId)) {
if (itemId && !cachedState) {
resolveLibraryStateByItemId(itemId);
}
console.log("[CustomTrailer] API 未确认当前项目属于启用库,放行 Emby 原生预告片");
return;
}
// This must happen synchronously, before any async lookup, otherwise Emby may still
// receive the same click and open its native trailer player.
e.preventDefault();
e.stopPropagation();
if (typeof e.stopImmediatePropagation === "function") {
e.stopImmediatePropagation();
}
if (isHandlingClick) return;
isHandlingClick = true;
openTrailerForCurrentPage({
root: detailRoot,
button: btn,
number: btn.dataset.customTrailerNumber
}).finally(() => {
isHandlingClick = false;
});
}
function isInsideTrailerOverlay(target) {
return !!(target && target.closest && target.closest("#custom-trailer-overlay, .trailer-overlay, .jav-player-close"));
}
function startTrailerButtonObserver() {
if (!document.body) {
document.addEventListener("DOMContentLoaded", startTrailerButtonObserver, { once: true });
return;
}
const observer = new MutationObserver((mutations) => {
if (mutations.some(isRelevantDetailMutation)) {
scheduleEnsureTrailerButton();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
scheduleEnsureTrailerButtonBurst();
}
function installDebugApi() {
window.CustomTrailerDebug = function () {
window.__customTrailerDebug = true;
return ensureCustomTrailerButton({ forceLog: true });
};
}
function isRelevantDetailMutation(mutation) {
const nodes = [mutation.target].concat(Array.from(mutation.addedNodes || []));
return nodes.some((node) => {
if (!node || node.nodeType !== 1) return false;
return !!(
node.matches?.(".itemDetailPage, .detailPageWrapper, .page, .view, .mainDetailButtons, .detailButtons, .detailButtonContainer, .itemDetailButtons, .itemDetailButtonContainer, .buttons, .btnPlay, [data-action='resume'], [data-action='play'], [data-itemid]") ||
node.querySelector?.(".itemDetailPage, .detailPageWrapper, .page, .view, .mainDetailButtons, .detailButtons, .detailButtonContainer, .itemDetailButtons, .itemDetailButtonContainer, .buttons, .btnPlay, [data-action='resume'], [data-action='play'], [data-itemid]")
);
});
}
function scheduleEnsureTrailerButton() {
clearTimeout(scanTimer);
scanTimer = setTimeout(ensureCustomTrailerButton, 350);
}
function scheduleEnsureTrailerButtonBurst() {
[300, 900, 1800].forEach((delay) => {
setTimeout(ensureCustomTrailerButton, delay);
});
}
async function ensureCustomTrailerButton(options) {
const runId = ++ensureRunId;
const forceLog = !!(options && options.forceLog);
if (document.getElementById("custom-trailer-overlay")) {
return debugEnsureSkipped("播放器已打开,跳过补按钮", null, forceLog);
}
if (isLibraryListUrl()) {
removeCustomTrailerButtons(document);
return debugEnsureSkipped("当前是库列表页,跳过补按钮", collectEnsureState(), forceLog);
}
const detailRoot = getVisibleDetailRoot() || document.body;
const number = extractNumberFromPage(detailRoot) || extractNumberFromPage(document);
if (!number) {
removeCustomTrailerButtons(document);
return debugEnsureSkipped("未找到当前详情页番号", collectEnsureState(), forceLog);
}
const libraryState = await resolveCurrentLibraryState(detailRoot);
if (runId !== ensureRunId) {
return debugEnsureSkipped("已有新的详情页检测,忽略本次结果", {
libraryState,
number
}, forceLog);
}
const libraryId = libraryState?.libraryId || null;
const isEnabledLibrary = libraryId && isEnabledLibraryId(libraryId);
const actionContainer = findDetailActionContainer(detailRoot) || ensureFallbackActionContainer(detailRoot);
const nativeButton = findNativeTrailerButton(detailRoot);
if (!isEnabledLibrary || !actionContainer || nativeButton) {
if (detailRoot.querySelector(CUSTOM_BUTTON_SELECTOR)) {
removeCustomTrailerButtons(detailRoot);
}
return debugEnsureSkipped("跳过补按钮", {
libraryId,
isEnabledLibrary,
hasActionContainer: !!actionContainer,
hasNativeButton: !!nativeButton,
itemId: libraryState?.itemId || getCurrentItemId(detailRoot),
number
}, forceLog);
}
if (actionContainer.querySelector(CUSTOM_BUTTON_SELECTOR)) {
return debugEnsureSkipped("自定义预告片按钮已存在", {
libraryId,
itemId: libraryState?.itemId || getCurrentItemId(detailRoot),
number
}, forceLog);
}
removeCustomTrailerButtons(detailRoot);
ensureCustomTrailerStyles();
insertCustomTrailerButton(actionContainer, createCustomTrailerButton(number, libraryState));
console.log("[CustomTrailer] 已补充自定义预告片按钮:", number || "点击时提取");
return true;
}
function getVisibleDetailRoot() {
const actionContainer = findVisibleDetailActionContainer();
if (actionContainer) {
const root = actionContainer.closest(".itemDetailPage, .detailPageWrapper, .page, .view") || document.body;
return looksLikeDetailRoot(root) ? root : null;
}
const roots = Array.from(document.querySelectorAll(".itemDetailPage, .detailPageWrapper, .page, .view"));
return roots.find((root) => {
return isElementVisible(root) && looksLikeDetailRoot(root);
}) || null;
}
function getDetailRootForNode(node) {
if (!node || !node.closest) return null;
return node.closest(".itemDetailPage, .detailPageWrapper");
}
function findNativeTrailerButton(root) {
return Array.from(root.querySelectorAll(TRAILER_BUTTON_SELECTOR)).find((btn) => {
return !btn.classList.contains(CUSTOM_BUTTON_CLASS) &&
(btn.matches("button") || btn.classList.contains("emby-button") || btn.classList.contains("paper-icon-button-light")) &&
!isInsideTrailerOverlay(btn) &&
isElementVisible(btn);
}) || null;
}
function findVisibleDetailActionContainer() {
const selectors = [
".mainDetailButtons",
".detailButtons",
".detailButtonContainer",
".itemDetailButtons",
".itemDetailButtonContainer",
".detailPagePrimaryContainer .buttons",
".detailPagePrimaryContent .buttons"
];
for (const selector of selectors) {
const match = Array.from(document.querySelectorAll(selector)).find((node) => {
const container = getActionContainerFromNode(node);
return container && isElementVisible(container) && looksLikeDetailRoot(container.closest(".itemDetailPage, .detailPageWrapper, .page, .view") || document.body);
});
if (match) return getActionContainerFromNode(match);
}
return null;
}
function findDetailActionContainer(root) {
const scope = root || document;
const selectors = [
".mainDetailButtons",
".detailButtons",
".detailButtonContainer",
".itemDetailButtons",
".itemDetailButtonContainer",
".detailButtonWrapper",
".itemDetailPageButtons",
".mediaInfoButtons",
".primaryMediaInfo .buttons",
".detailPagePrimaryContainer .buttons",
".detailPagePrimaryContent .buttons"
];
for (const selector of selectors) {
const container = scope.querySelector(selector);
if (container && !isInsideTrailerOverlay(container) && isElementVisible(container)) return container;
}
const anchorButton = scope.querySelector(".btnPlay, [data-action='resume'], [data-action='play']");
return anchorButton && !isInsideTrailerOverlay(anchorButton) ? getActionContainerFromNode(anchorButton) : null;
}
function ensureFallbackActionContainer(root) {
const scope = root || document.body;
const existing = scope.querySelector("." + CUSTOM_ACTIONS_CLASS);
if (existing) return existing;
const title = findTitleElement(scope);
if (!title || !title.parentElement) return null;
const container = document.createElement("div");
container.className = CUSTOM_ACTIONS_CLASS;
title.insertAdjacentElement("afterend", container);
return container;
}
function findTitleElement(scope) {
const root = scope || document;
const selectors = [
".itemName",
".itemNameOriginal",
".detailPagePrimaryContent .itemName",
".detailPagePrimaryContainer .itemName",
"h1",
".title",
".itemTitle",
".mediaTitle"
];
for (const selector of selectors) {
const el = root.querySelector?.(selector) || document.querySelector(selector);
if (el && isElementVisible(el) && extractNumber(el.textContent)) return el;
}
return null;
}
function getActionContainerFromNode(node) {
if (!node) return null;
if (node.matches?.(".mainDetailButtons, .detailButtons, .detailButtonContainer, .itemDetailButtons, .itemDetailButtonContainer")) {
return node;
}
return node.closest?.(".mainDetailButtons, .detailButtons, .detailButtonContainer, .itemDetailButtons, .itemDetailButtonContainer, .buttons") ||
node.parentElement ||
null;
}
function looksLikeDetailRoot(root) {
if (!root) return false;
const hasDetailShell = !!root.querySelector?.(".detailPagePrimaryContent, .detailPageContent, .mainDetailButtons, .detailButtons, .itemDetailButtons");
const hasTitleNumber = getTitleCandidates(root).some((candidate) => !!extractNumber(candidate));
return hasDetailShell && hasTitleNumber;
}
function isElementVisible(el) {
if (!el || !el.isConnected) return false;
const style = window.getComputedStyle(el);
if (style.display === "none" || style.visibility === "hidden") return false;
return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
}
function removeCustomTrailerButtons(root) {
root.querySelectorAll(CUSTOM_BUTTON_SELECTOR).forEach((btn) => btn.remove());
}
function insertCustomTrailerButton(container, btn) {
const playButton = container.querySelector(".btnPlay, [data-action='resume'], [data-action='play']");
if (playButton && playButton.nextSibling) {
container.insertBefore(btn, playButton.nextSibling);
return;
}
container.appendChild(btn);
}
function createCustomTrailerButton(number, libraryState) {
let btn;
try {
btn = document.createElement("button", { is: "emby-button" });
} catch (err) {
btn = document.createElement("button");
}
btn.type = "button";
btn.className = "btnPlayTrailer btnPlayTrailer-main raised detailButton emby-button button-hoverable detailButton-stacked " + CUSTOM_BUTTON_CLASS;
btn.setAttribute("is", "emby-button");
btn.setAttribute("title", "预告片");
btn.setAttribute("aria-label", "预告片");
if (number) {
btn.dataset.customTrailerNumber = number;
}
if (libraryState?.itemId) {
btn.dataset.customTrailerItemId = String(libraryState.itemId);
}
if (libraryState?.libraryId) {
btn.dataset.customTrailerLibraryId = String(libraryState.libraryId);
}
btn.innerHTML = `
<i class="md-icon button-icon button-icon-left"></i>
<span>预告片</span>
`;
return btn;
}
function ensureCustomTrailerStyles() {
if (document.getElementById(CUSTOM_STYLE_ID)) return;
const style = document.createElement("style");
style.id = CUSTOM_STYLE_ID;
style.textContent = `
.${CUSTOM_ACTIONS_CLASS} {
display: flex;
align-items: center;
gap: .35em;
margin: .45em 0 .65em;
}
.${CUSTOM_BUTTON_CLASS} {
cursor: pointer;
}
`;
document.head.appendChild(style);
}
function collectEnsureState() {
const root = getVisibleDetailRoot() || document;
const itemId = getCurrentItemId(root);
const cachedLibraryState = itemId ? itemLibraryCache.get(String(itemId)) || null : null;
return {
href: location.href,
itemId,
cachedLibraryState,
hasPendingLibraryLookup: itemId ? itemLibraryPending.has(String(itemId)) : false,
enabledLibraries: ENABLED_LIBRARIES.slice(),
itemDetailPageCount: document.querySelectorAll(".itemDetailPage").length,
detailPageWrapperCount: document.querySelectorAll(".detailPageWrapper").length,
pageCount: document.querySelectorAll(".page").length,
viewCount: document.querySelectorAll(".view").length,
actionContainerCount: document.querySelectorAll(".mainDetailButtons, .detailButtons, .detailButtonContainer, .itemDetailButtons, .itemDetailButtonContainer, .buttons").length,
playButtonCount: document.querySelectorAll(".btnPlay, [data-action='resume'], [data-action='play']").length,
itemName: document.querySelector(".itemName")?.textContent || "",
title: document.title
};
}
function debugEnsureSkipped(message, detail, forceLog) {
if (!forceLog && !window.__customTrailerDebug) return false;
console.log("[CustomTrailer]", message, detail || "");
return false;
}
function findTrailerButton(target) {
if (!target || !target.closest) return null;
const direct = target.closest(TRAILER_BUTTON_SELECTOR);
if (direct) return direct;
const button = target.closest("button, .emby-button, .paper-icon-button-light");
if (!button) return null;
const text = [
button.className,
button.getAttribute("title"),
button.getAttribute("aria-label"),
button.getAttribute("data-action"),
button.textContent
].filter(Boolean).join(" ").toLowerCase();
return /trailer|预告/.test(text) ? button : null;
}
function isEnabledLibraryId(id) {
return ENABLED_LIBRARIES.includes(String(id || ""));
}
function getCurrentItemId(scope) {
return getItemIdFromLocation() || getItemIdFromDom(scope);
}
function getItemIdFromLocation() {
const href = location.href || "";
const hash = location.hash || "";
const matches = [
href.match(/[?&]id=([^&#]+)/i),
href.match(/[?&]itemId=([^&#]+)/i),
hash.match(/[?&]id=([^&#]+)/i),
hash.match(/[?&]itemId=([^&#]+)/i),
href.match(/#!\/item\/([^?&#/]+)/i),
href.match(/\/items\/([^?&#/]+)/i)
];
for (const match of matches) {
if (match && match[1]) return decodeURIComponent(match[1]);
}
return null;
}
function getItemIdFromDom(scope) {
const root = scope || getVisibleDetailRoot() || document;
const candidates = [
root?.dataset?.itemid,
root?.dataset?.itemId,
root?.getAttribute?.("data-id"),
root?.closest?.("[data-itemid]")?.dataset.itemid,
root?.closest?.("[data-id]")?.getAttribute("data-id"),
root?.querySelector?.("[data-itemid]")?.dataset.itemid,
root?.querySelector?.("[data-id]")?.getAttribute("data-id"),
document.querySelector(".itemDetailPage[data-itemid]")?.dataset.itemid,
document.querySelector(".detailPageWrapper[data-itemid]")?.dataset.itemid,
document.querySelector("[data-itemid]")?.dataset.itemid
].filter(Boolean);
return candidates.find((id) => /^\d+$/.test(String(id))) || candidates[0] || null;
}
function getCachedLibraryState(scope) {
const itemId = getCurrentItemId(scope);
if (!itemId) return null;
return itemLibraryCache.get(String(itemId)) || null;
}
async function resolveCurrentLibraryState(scope) {
const itemId = getCurrentItemId(scope);
if (!itemId) {
return {
enabled: false,
libraryId: null,
itemId: null,
reason: "missing-item-id"
};
}
return await resolveLibraryStateByItemId(itemId);
}
async function resolveLibraryStateByItemId(itemId) {
const key = String(itemId || "");
if (!key) {
return {
enabled: false,
libraryId: null,
itemId: null,
reason: "missing-item-id"
};
}
const cached = itemLibraryCache.get(key);
if (cached) return cached;
if (itemLibraryPending.has(key)) {
return await itemLibraryPending.get(key);
}
const pending = fetchItemLibraryState(key)
.catch((err) => {
console.warn("[CustomTrailer] 查询媒体库归属失败:", err);
return {
enabled: false,
libraryId: null,
itemId: key,
reason: "api-error"
};
})
.then((state) => {
itemLibraryCache.set(key, state);
itemLibraryPending.delete(key);
return state;
});
itemLibraryPending.set(key, pending);
return await pending;
}
async function fetchItemLibraryState(itemId) {
const item = await fetchEmbyItem(itemId).catch((err) => {
console.warn("[CustomTrailer] 查询项目详情失败,继续查询祖先库:", err);
return null;
});
const ancestors = await fetchEmbyItemAncestors(itemId).catch((err) => {
console.warn("[CustomTrailer] 查询项目祖先库失败:", err);
return [];
});
const ids = []
.concat(item ? [item.ParentId, item.TopParentId, item.CollectionFolderId, item.Id] : [])
.concat((ancestors || []).map((ancestor) => ancestor && ancestor.Id))
.filter(Boolean)
.map(String);
const libraryId = ids.find(isEnabledLibraryId) || null;
return {
enabled: !!libraryId,
libraryId,
itemId: String(itemId),
itemName: item?.Name || null,
ancestorIds: ids
};
}
function getApiClient() {
return window.ApiClient ||
window.Emby?.ApiClient ||
window.require?.s?.contexts?._?.defined?.ApiClient ||
null;
}
function getApiClientUserId(apiClient) {
try {
const direct = apiClient?.getCurrentUserId?.();
if (direct) return direct;
} catch (err) {
// Some Emby builds expose getCurrentUserId as a property-like method that can throw early.
}
return apiClient?._serverInfo?.UserId ||
apiClient?.serverInfo?.UserId ||
window.Dashboard?.getCurrentUserId?.() ||
null;
}
async function fetchEmbyItem(itemId) {
const apiClient = getApiClient();
const userId = getApiClientUserId(apiClient);
const attempts = [
() => apiClient?.getItem?.(userId, itemId),
() => apiClient?.getItem?.(itemId),
() => embyAjaxJson(apiClient, buildEmbyApiPath("/Users/" + encodeURIComponent(userId) + "/Items/" + encodeURIComponent(itemId))),
() => embyAjaxJson(apiClient, buildEmbyApiPath("/Items/" + encodeURIComponent(itemId)))
];
return await firstSuccessfulJson(attempts);
}
async function fetchEmbyItemAncestors(itemId) {
const apiClient = getApiClient();
const userId = getApiClientUserId(apiClient);
const userQuery = userId ? "?UserId=" + encodeURIComponent(userId) : "";
const attempts = [
() => apiClient?.getAncestors?.(userId, itemId),
() => apiClient?.getAncestors?.(itemId, userId),
() => apiClient?.getAncestors?.(itemId),
() => apiClient?.getItemAncestors?.(userId, itemId),
() => apiClient?.getItemAncestors?.(itemId, userId),
() => apiClient?.getItemAncestors?.(itemId),
() => embyAjaxJson(apiClient, buildEmbyApiPath("/Items/" + encodeURIComponent(itemId) + "/Ancestors" + userQuery)),
() => embyAjaxJson(apiClient, buildEmbyApiPath("/Users/" + encodeURIComponent(userId) + "/Items/" + encodeURIComponent(itemId) + "/Ancestors")),
() => embyAjaxJson(apiClient, buildEmbyApiPath("/Items/" + encodeURIComponent(itemId) + "/Ancestors"))
];
const result = await firstSuccessfulJson(attempts);
if (Array.isArray(result)) return result;
if (Array.isArray(result?.Items)) return result.Items;
return [];
}
async function firstSuccessfulJson(attempts) {
let lastError = null;
for (const attempt of attempts) {
try {
const result = await attempt();
if (result) return result;
} catch (err) {
lastError = err;
}
}
if (lastError) throw lastError;
return null;
}
function buildEmbyApiPath(path) {
const cleanPath = String(path || "").replace(/^\/+/, "");
return getEmbyServerBaseUrl() + cleanPath;
}
function getEmbyServerBaseUrl() {
const apiClient = getApiClient();
let base = "";
try {
base = typeof apiClient?.serverAddress === "function" ? apiClient.serverAddress() : "";
} catch (err) {
base = "";
}
if (!base) {
base = apiClient?._serverAddress ||
apiClient?.serverAddress ||
location.origin;
}
base = String(base || location.origin).replace(/\/+$/, "");
return /\/emby$/i.test(base) ? base + "/" : base + "/emby/";
}
async function embyAjaxJson(apiClient, url) {
if (!url || /\/Users\/null\//i.test(url) || /\/Users\/undefined\//i.test(url)) {
return null;
}
if (apiClient?.ajax) {
const result = await apiClient.ajax({
type: "GET",
url,
dataType: "json"
});
return typeof result === "string" ? JSON.parse(result) : result;
}
const headers = {
"Accept": "application/json"
};
const token = getApiAccessToken(apiClient);
if (token) headers["X-Emby-Token"] = token;
const res = await fetch(url, {
cache: "no-store",
credentials: "same-origin",
headers
});
if (!res.ok) throw new Error("HTTP " + res.status + " " + url);
return await res.json();
}
function getApiAccessToken(apiClient) {
try {
const direct = apiClient?.accessToken?.();
if (direct) return direct;
} catch (err) {
// Ignore and fall back to known fields/storage below.
}
const fieldToken = apiClient?._serverInfo?.AccessToken ||
apiClient?.serverInfo?.AccessToken ||
apiClient?._accessToken;
if (fieldToken) return fieldToken;
try {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (!key || !/token|access/i.test(key)) continue;
const value = localStorage.getItem(key);
if (value && /^[A-Za-z0-9+/_=-]{20,}$/.test(value)) return value;
}
} catch (err) {
// localStorage can be unavailable in restricted contexts.
}
return null;
}
function isLibraryListUrl() {
const href = location.href || "";
return /[?&]parentId=/i.test(href) && /#!\/videos/i.test(href);
}
async function openTrailerForCurrentPage(context) {
const root = context?.root || getVisibleDetailRoot() || getDetailRootForNode(context?.button);
const number = normalizeNumber(context?.number) ||
extractNumberFromPage(root) ||
extractNumberFromButtonContext(context?.button);
console.log("[CustomTrailer] 番号提取结果:", number);
if (!number) {
alert("无法从页面提取番号");
return;
}
const rawNumber = extractNumberFromPage(root, { preserveSource: true }) ||
extractNumberFromButtonContext(context?.button, { preserveSource: true }) ||
normalizeNumber(context?.number) ||
number;
const trailer = await fetchTrailer(number, rawNumber);
if (!trailer?.url) {
alert("未找到预告片:" + number);
return;
}
playTrailerOverlay(trailer);
}
function extractNumberFromPage(root, options) {
const scope = root || getVisibleDetailRoot() || document;
return extractNumberFromCandidates(getTitleCandidates(scope), options);
}
function extractNumberFromButtonContext(button, options) {
if (!button || !button.closest) return null;
return extractNumberFromCandidates([
button.closest("[data-itemid]")?.getAttribute("title"),
button.closest("[title]")?.getAttribute("title"),
document.querySelector(".itemName")?.textContent,
document.title
], options);
}
function getTitleCandidates(scope) {
const root = scope || document;
const candidates = [
root.querySelector?.(".itemName")?.textContent,
root.querySelector?.(".itemNameOriginal")?.textContent,
root.querySelector?.(".detailPagePrimaryContent .itemName")?.textContent,
root.querySelector?.(".detailPagePrimaryContainer .itemName")?.textContent,
root.querySelector?.("h1")?.textContent,
root.querySelector?.(".title")?.textContent,
root.querySelector?.(".itemTitle")?.textContent,
root.querySelector?.(".mediaTitle")?.textContent,
root.querySelector?.("[data-itemid][title]")?.getAttribute("title"),
document.querySelector(".itemName")?.textContent,
document.querySelector("h1")?.textContent,
document.title
];
return candidates
.map((value) => String(value || "").trim())
.filter(Boolean)
.filter((value, index, arr) => arr.indexOf(value) === index);
}
function extractNumberFromCandidates(candidates, options) {
for (const candidate of candidates) {
const number = extractNumber(candidate, options);
if (number) return number;
}
return null;
}
function normalizeNumber(number) {
return number ? extractNumber(String(number)) || normalizeCode(number).toLowerCase() : null;
}
function extractNumber(text, options) {
if (!text) return null;
const raw = String(text);
const mgstageHit = raw.match(/\b(\d{3}[A-Z]{2,10})[-_\s](\d{2,6})\b/i);
if (mgstageHit) return normalizeCode(mgstageHit[1] + "-" + mgstageHit[2]).toLowerCase();
const uncensoredHit = raw.match(/(?:(PACOPACOMAMA|PACO|10MUSUME|10MU|1PONDO|CARIBBEANCOM|CARIB|HEYZO)[-_\s]*)?(\d{6})([-_])(\d{2,3})/i);
if (uncensoredHit) {
if (options?.preserveSource && uncensoredHit[1]) {
return uncensoredHit[1].toLowerCase() + "_" + normalizeCode(uncensoredHit[2] + uncensoredHit[3] + uncensoredHit[4]).toLowerCase();
}
return normalizeCode(uncensoredHit[2] + uncensoredHit[3] + uncensoredHit[4]).toLowerCase();
}
const patterns = [
{ regex: /\b([A-Z]{2,15})[-_\s]([A-Z]{1,2}\d{2,10})\b/i, type: "alphanum" },
{ regex: /\b([A-Z]{2,15})[-_\s](\d{2,10})(?:[-_](\d{1,3}))?\b/i, type: "standard" },
{ regex: /\bFC2[-\s_]?(?:PPV)?[-\s_]?(\d{5,9})\b/i, type: "fc2" },
{ regex: /\b(\d{2,6}[A-Z]{2,10})[-_\s]*(\d{2,7})\b/i, type: "mgstageCompact" },
{ regex: /\b([A-Z]{2,10})(\d{3,6})\b/i, type: "compactStandard" }
];
for (const { regex, type } of patterns) {
const match = raw.match(regex);
if (!match) continue;
if (type === "alphanum") {
const prefix = match[1].toUpperCase();
if (isIgnoredNumberPrefix(prefix)) continue;
return normalizeCode(match[0].trim()).toLowerCase();
}
if (type === "standard") {
const prefix = match[1].toUpperCase();
if (isIgnoredNumberPrefix(prefix)) continue;
return normalizeCode(match[3] ? prefix + "-" + match[2] + "-" + match[3] : prefix + "-" + match[2]).toLowerCase();
}
if (type === "fc2") {
return normalizeCode("FC2-PPV-" + match[1]).toLowerCase();
}
if (type === "mgstageCompact") {
return normalizeCode(match[1] + "-" + match[2]).toLowerCase();
}
if (type === "compactStandard") {
const prefix = match[1].toUpperCase();
if (isIgnoredNumberPrefix(prefix)) continue;
const number = match[2].replace(/^0+(?=\d{3})/, "");
return normalizeCode(prefix + "-" + number).toLowerCase();
}
}
return null;
}
function normalizeCode(code) {
const raw = String(code || "").trim();
if (!raw) return "";
const normalized = raw
.replace(/\s+/g, "-")
.replace(/^FC2[-_]?PPV[-_]?/i, "FC2-")
.toUpperCase();
const uncensoredNumeric = normalized.match(/(\d{6})[-_](\d{2,3})/);
if (uncensoredNumeric) {
const sep = uncensoredNumeric[0].includes("_") ? "_" : "-";
return uncensoredNumeric[1] + sep + uncensoredNumeric[2];
}
const compact = normalized.match(/^([A-Z]{2,10})(\d{3,6})$/);
if (compact) {
const number = compact[2].replace(/^0+(?=\d{3})/, "");
return compact[1] + "-" + number;
}
const trimmed = normalized.match(/^([A-Z0-9]{2,15}[-_]\d{2,6}(?:[-_]\d{1,3})?)/);
if (trimmed) return trimmed[1];
return normalized;
}
function isIgnoredNumberPrefix(prefix) {
return [
"FULLHD",
"H264",
"H265",
"1080P",
"720P",
"480P",
"360P",
"PART",
"DISC",
"10BIT",
"tv",
"season",
"episode",
"part",
"disc",
"cd",
"dvd",
"bluray",
"video",
"movie"
].map((value) => value.toLowerCase()).includes(String(prefix || "").toLowerCase());
}
async function fetchTrailer(number, rawNumber) {
const query = normalizeTrailerQuery(number);
const rawQuery = String(rawNumber || number || "").trim();
if (!query) return null;
const cacheKey = TRAILER_CACHE_PREFIX + query + "_" + normalizeTrailerQuery(rawQuery);
const cached = getCachedTrailerResult(cacheKey);
if (cached?.url) {
console.log("[CustomTrailer] 预告片缓存命中:", query, cached);
return cached;
}
const resolvers = [
fromMgstage,
fromDirectSamples,
fromFc2Hub,
fromJavpCcCd,
fromDmmApi,
fromDmmPlayerPage,
fromJavSpyl
];
for (const resolver of resolvers) {
try {
const result = await resolver(query, rawQuery);
if (result?.url) {
const normalized = normalizeTrailerResult(result, query);
sessionStorage.setItem(cacheKey, JSON.stringify(normalized));
console.log("[CustomTrailer] 预告片来源:", normalized.source, normalized);
return normalized;
}
} catch (err) {
console.warn("[CustomTrailer] resolver failed:", resolver.name, err);