-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopen-stremio-links-on-mpv.user.js
More file actions
806 lines (676 loc) · 24.2 KB
/
Copy pathopen-stremio-links-on-mpv.user.js
File metadata and controls
806 lines (676 loc) · 24.2 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
// ==UserScript==
// @name Open Stremio Links on MPV
// @name:en-US Open Stremio Links on MPV
// @name:pt-BR Abrir Links do Stremio no MPV
// @name:pt-PT Abrir Ligações do Stremio no MPV
// @description Replaces the links when the option "M3U Playlist" is active and opens them on MPV via mpv-handler
// @description:en-US Replaces the links when the option "M3U Playlist" is active and opens them on MPV via mpv-handler
// @description:pt-BR Substitui os links quando a opção "M3U Playlist" está ativa e os abre no MPV via mpv-handler
// @description:pt-PT Substitui as ligações quando a opção "M3U Playlist" está activa e abre-as no MPV via mpv-handler
// @namespace open-stremio-links-on-mpv
// @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.net/gh/sizzlemctwizzle/GM_config@06f2015c04db3aaab9717298394ca4f025802873/gm_config.js
// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_notification
// @grant GM_registerMenuCommand
// @run-at document-idle
// @noframes
// @match *://web.stremio.com/*
// @match *://stremio.zarg.me/*
// @downloadURL https://github.com/ang3lo-azevedo/open-stremio-links-on-mpv/raw/refs/heads/main/open-stremio-links-on-mpv.user.js
// @updateURL https://github.com/ang3lo-azevedo/open-stremio-links-on-mpv/raw/refs/heads/main/open-stremio-links-on-mpv.user.js
// ==/UserScript==
"use strict";
const MPV_HANDLER_VERSION = "v0.3.15";
const css = String.raw;
const ICON_MPV =
"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0\
PSI2NCIgdmVyc2lvbj0iMSI+CiA8Y2lyY2xlIHN0eWxlPSJvcGFjaXR5Oi4yIiBjeD0iMzIiIGN5\
PSIzMyIgcj0iMjgiLz4KIDxjaXJjbGUgc3R5bGU9ImZpbGw6IzhkMzQ4ZSIgY3g9IjMyIiBjeT0i\
MzIiIHI9IjI4Ii8+CiA8Y2lyY2xlIHN0eWxlPSJvcGFjaXR5Oi4zIiBjeD0iMzQuNSIgY3k9IjI5\
LjUiIHI9IjIwLjUiLz4KIDxjaXJjbGUgc3R5bGU9Im9wYWNpdHk6LjIiIGN4PSIzMiIgY3k9IjMz\
IiByPSIxNCIvPgogPGNpcmNsZSBzdHlsZT0iZmlsbDojZmZmZmZmIiBjeD0iMzIiIGN5PSIzMiIg\
cj0iMTQiLz4KIDxwYXRoIHN0eWxlPSJmaWxsOiM2OTFmNjkiIHRyYW5zZm9ybT0ibWF0cml4KDEu\
NTE1NTQ0NSwwLDAsMS41LC0zLjY1Mzg3OSwtNC45ODczODQ4KSIgZD0ibTI3LjE1NDUxNyAyNC42\
NTgyNTctMy40NjQxMDEgMi0zLjQ2NDEwMiAxLjk5OTk5OXYtNC0z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U2MjUgTCA0LjQ4NDM3NSAxMi4yMjg1MTYgQSA1LjUgNS41IDAgMCAwIDYuMDk1NzAz\
MSAxMy4xNTIzNDQgTCA2LjI0NjA5MzggMTUuMDAxOTUzIEwgOS43NDYwOTM4IDE1LjAwMTk1MyBM\
IDkuOTAwMzkwNiAxMy4xNTgyMDMgQSA1LjUgNS41IDAgMCAwIDExLjUwNzgxMiAxMi4yMjg1MTYg\
TCAxMy4xODM1OTQgMTMuMDE3NTc4IEwgMTQuOTMzNTk0IDkuOTg2MzI4MSBMIDEzLjQxMjEwOSA4\
LjkyOTY4NzUgQSA1LjUgNS41IDAgMCAwIDEzLjQ5NjA5NCA4LjAwMTk1MzEgQSA1LjUgNS41IDAg\
MCAwIDEzLjQxNjAxNiA3LjA3MDMxMjUgTCAxNC45MzM1OTQgNi4wMTc1NzgxIEwgMTMuMTgzNTk0\
IDIuOTg2MzI4MSBMIDExLjUxMTcxOSAzLjc3MzQzNzUgQSA1LjUgNS41IDAgMCAwIDkuOTAwMzkw\
NiAyLjg0OTYwOTQgTCA5Ljc1IDEgTCA2LjI1IDEgeiBNIDggNiBBIDIgMiAwIDAgMSAxMCA4IEEg\
MiAyIDAgMCAxIDggMTAgQSAyIDIgMCAwIDEgNiA4IEEgMiAyIDAgMCAxIDggNiB6IiB0cmFuc2Zv\
cm09InRyYW5zbGF0ZSg0IDQpIi8+Cjwvc3ZnPgo=";
const CONFIG_ID = "stremio-mpv-config";
const CONFIG_CSS = css`
body {
display: flex;
justify-content: center;
}
#${CONFIG_ID}_wrapper {
display: flex;
flex-direction: column;
justify-content: center;
}
#${CONFIG_ID} .config_header {
display: flex;
align-items: center;
padding: 12px;
}
#${CONFIG_ID} .config_var {
margin: 0 0 12px 0;
}
#${CONFIG_ID} .field_label {
display: inline-block;
width: 140px;
font-size: 14px;
}
#${CONFIG_ID}_field_profile,
#${CONFIG_ID}_field_quality,
#${CONFIG_ID}_field_console {
width: 80px;
height: 24px;
font-size: 14px;
text-align: center;
}
#${CONFIG_ID}_buttons_holder {
display: flex;
flex-direction: column;
}
#${CONFIG_ID} .saveclose_buttons {
margin: 1px;
padding: 4px 0;
}
#${CONFIG_ID} .reset_holder {
padding-top: 4px;
}
`;
const CONFIG_IFRAME_CSS = css`
position: fixed;
z-index: 99999;
width: 300px;
height: 320px;
border: 1px solid;
border-radius: 10px;
`;
const CONFIG_FIELDS = {
profile: {
label: "MPV Profile",
type: "text",
default: "default",
},
quality: {
label: "Prefer Video Quality",
type: "select",
options: ["default", "2160p", "1440p", "1080p", "720p", "480p", "360p"],
default: "default",
},
console: {
label: "Run With Console",
type: "select",
options: ["yes", "no"],
default: "yes",
},
};
// GM_config init
GM_config.init({
id: CONFIG_ID,
title: GM_info.script.name,
fields: CONFIG_FIELDS,
events: {
init: () => {
let quality = GM_config.get("quality").toLowerCase();
if (!CONFIG_FIELDS.quality.options.includes(quality)) {
GM_config.set("quality", "default");
}
},
save: () => {
let profile = GM_config.get("profile").trim();
if (profile === "") {
GM_config.set("profile", "default");
} else {
GM_config.set("profile", profile);
}
GM_config.close();
},
reset: () => {
GM_config.save();
},
},
css: CONFIG_CSS.trim(),
});
// Inject MPV settings into Stremio's native settings panel
function injectStremioSettings() {
// Look for the settings panel container
const settingsPanels = document.querySelectorAll('[class*="settings-container"]');
if (settingsPanels.length === 0) {
return;
}
const settingsContainer = settingsPanels[0];
// Check if we've already injected our settings
if (settingsContainer.querySelector('[data-mpv-settings]')) {
return;
}
// Find all settings sections to understand the structure
const sections = settingsContainer.querySelectorAll('[class*="section-"]');
if (sections.length === 0) {
return;
}
// Create MPV settings section matching Stremio's style
const mpvSection = document.createElement('div');
mpvSection.setAttribute('data-mpv-settings', 'true');
mpvSection.setAttribute('class', sections[0].getAttribute('class'));
mpvSection.style.marginTop = '24px';
// Create section title
const sectionTitle = document.createElement('div');
sectionTitle.setAttribute('class', sections[0].querySelector('[class*="section-"]')?.getAttribute('class') || 'section-title');
sectionTitle.textContent = 'MPV Player';
sectionTitle.style.fontSize = '14px';
sectionTitle.style.fontWeight = '500';
sectionTitle.style.marginBottom = '16px';
sectionTitle.style.color = 'rgba(255, 255, 255, 0.7)';
mpvSection.appendChild(sectionTitle);
// Create options container
const optionsContainer = document.createElement('div');
// Profile setting
const profileOption = createSettingOption('profile', 'MPV Profile', 'text', null);
optionsContainer.appendChild(profileOption);
// Quality setting
const qualityOption = createSettingOption('quality', 'Prefer Video Quality', 'select', CONFIG_FIELDS.quality.options);
optionsContainer.appendChild(qualityOption);
// Console setting
const consoleOption = createSettingOption('console', 'Run With Console', 'select', CONFIG_FIELDS.console.options);
optionsContainer.appendChild(consoleOption);
mpvSection.appendChild(optionsContainer);
// Add to settings container
settingsContainer.appendChild(mpvSection);
}
// Create a single settings option element
function createSettingOption(fieldName, label, type, options) {
const optionContainer = document.createElement('div');
optionContainer.setAttribute('class', 'mpv-setting-option');
optionContainer.style.marginBottom = '16px';
optionContainer.style.display = 'flex';
optionContainer.style.alignItems = 'center';
optionContainer.style.justifyContent = 'space-between';
// Create label
const labelEl = document.createElement('label');
labelEl.textContent = label;
labelEl.style.fontSize = '14px';
labelEl.style.color = 'rgba(255, 255, 255, 0.9)';
labelEl.style.flex = '1';
// Create input
let inputEl;
const currentValue = GM_config.get(fieldName);
if (type === 'select') {
inputEl = document.createElement('select');
inputEl.style.padding = '6px 8px';
inputEl.style.borderRadius = '4px';
inputEl.style.border = '1px solid rgba(255, 255, 255, 0.2)';
inputEl.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
inputEl.style.color = 'rgba(255, 255, 255, 0.9)';
inputEl.style.fontSize = '14px';
inputEl.style.cursor = 'pointer';
options.forEach(opt => {
const optionEl = document.createElement('option');
optionEl.value = opt;
optionEl.textContent = opt;
optionEl.selected = opt === currentValue;
inputEl.appendChild(optionEl);
});
inputEl.addEventListener('change', (e) => {
GM_config.set(fieldName, e.target.value);
});
} else if (type === 'text') {
inputEl = document.createElement('input');
inputEl.type = 'text';
inputEl.value = currentValue;
inputEl.style.padding = '6px 8px';
inputEl.style.borderRadius = '4px';
inputEl.style.border = '1px solid rgba(255, 255, 255, 0.2)';
inputEl.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
inputEl.style.color = 'rgba(255, 255, 255, 0.9)';
inputEl.style.fontSize = '14px';
inputEl.style.width = '200px';
inputEl.addEventListener('change', (e) => {
let value = e.target.value.trim();
if (value === '') {
value = 'default';
inputEl.value = value;
}
GM_config.set(fieldName, value);
});
}
optionContainer.appendChild(labelEl);
optionContainer.appendChild(inputEl);
return optionContainer;
}
// Watch for settings panel and inject our settings
function setupSettingsIntegration() {
// Try to inject immediately
injectStremioSettings();
// Watch for hash changes to detect settings panel navigation
window.addEventListener('hashchange', () => {
if (window.location.hash.includes('settings')) {
// Wait a bit for the panel to render
setTimeout(injectStremioSettings, 100);
}
});
// Also watch for DOM mutations to catch dynamic panel creation
const settingsObserver = new MutationObserver(() => {
injectStremioSettings();
});
// Start observing when we detect the settings panel root
const checkForSettingsPanel = setInterval(() => {
const panel = document.querySelector('[class*="settings-container"]');
if (panel) {
settingsObserver.observe(panel.parentNode || document.body, {
childList: true,
subtree: true,
});
clearInterval(checkForSettingsPanel);
}
}, 500);
// Clear the interval after 30 seconds to avoid infinite checking
setTimeout(() => clearInterval(checkForSettingsPanel), 30000);
}
// URL-safe base64 encode
function btoaUrl(url) {
return btoa(url).replace(/\//g, "_").replace(/\+/g, "-").replace(/\=/g, "");
}
// Generate protocol URL for mpv-handler
function generateProto(url) {
let profile = GM_config.get("profile").trim();
let quality = GM_config.get("quality").toLowerCase();
let console = GM_config.get("console").toLowerCase();
let options = [];
let proto;
if (console === "yes") {
proto = "mpv-handler-debug://play/" + btoaUrl(url);
} else {
proto = "mpv-handler://play/" + btoaUrl(url);
}
if (profile !== "default" && profile !== "") {
options.push("profile=" + profile);
}
if (quality !== "default") {
options.push("quality=" + quality);
}
if (options.length !== 0) {
proto += "/?";
options.forEach((option, index) => {
proto += option;
if (index + 1 !== options.length) {
proto += "&";
}
});
}
return proto;
}
// Function to decode base64 URL from data URI and extract the actual stream URL
function decodeDataUrl(dataUrl) {
try {
const base64Data = dataUrl.split(',')[1];
const decodedData = atob(base64Data);
// Look for HTTP/HTTPS URLs in the decoded data
const urlMatch = decodedData.match(/(https?:\/\/[^\s\n\r\t]+)/);
if (urlMatch) {
const extractedUrl = urlMatch[1];
return extractedUrl;
}
// Alternative: look for lines that contain URLs
const lines = decodedData.split('\n');
for (const line of lines) {
if (line.startsWith('http://') || line.startsWith('https://')) {
return line.trim();
}
}
return null;
} catch (e) {
return null;
}
}
function padBase64(value) {
const padding = value.length % 4;
if (padding === 0) {
return value;
}
return value + "=".repeat(4 - padding);
}
function safeJsonParse(value) {
try {
return JSON.parse(value);
} catch (e) {
return null;
}
}
function extractJsonObject(text) {
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
if (start === -1 || end === -1 || end <= start) {
return null;
}
return safeJsonParse(text.slice(start, end + 1));
}
function buildMagnetFromInfoHash(streamData) {
if (!streamData || !streamData.infoHash) {
return null;
}
const magnet = new URLSearchParams();
magnet.append("xt", "urn:btih:" + streamData.infoHash);
if (streamData.name) {
magnet.append("dn", streamData.name);
}
if (Array.isArray(streamData.announce)) {
streamData.announce.forEach((tracker) => {
if (typeof tracker === "string" && tracker.trim() !== "") {
magnet.append("tr", tracker.trim());
}
});
}
return "magnet:?" + magnet.toString();
}
function decodePlayerPayload(payload) {
const candidates = [payload, payload.replace(/-/g, "+").replace(/_/g, "/")];
for (const candidate of candidates) {
try {
const decoded = atob(padBase64(candidate));
const parsed = extractJsonObject(decoded);
if (parsed) {
return parsed;
}
} catch (e) {
// Ignore invalid base64 payloads and continue with the next candidate.
}
}
return extractJsonObject(payload);
}
function decodePlayerRouteUrl(linkUrl) {
const marker = "#/player/";
const markerIndex = linkUrl.indexOf(marker);
if (markerIndex === -1) {
return null;
}
const route = linkUrl.slice(markerIndex + marker.length);
// Try to extract direct playable media URLs encoded in the route.
try {
const decodedRoute = decodeURIComponent(route);
const directMediaMatch = decodedRoute.match(/(https?:\/\/[^\s"']+\.(?:m3u8|mpd|mp4|mkv|webm)(?:\?[^\s"']*)?)/i);
if (directMediaMatch) {
return directMediaMatch[1];
}
} catch (e) {
// Ignore decode errors and continue with payload decoding.
}
const payloadEndIndex = route.search(/\/(?:https?|http)%3A%2F%2F/i);
const encodedPayload = payloadEndIndex === -1 ? route.split("/")[0] : route.slice(0, payloadEndIndex);
if (!encodedPayload) {
return null;
}
let payload;
try {
payload = decodeURIComponent(encodedPayload);
} catch (e) {
payload = encodedPayload;
}
const streamData = decodePlayerPayload(payload);
if (!streamData) {
return null;
}
if (typeof streamData.url === "string" && streamData.url.trim() !== "") {
return streamData.url.trim();
}
return buildMagnetFromInfoHash(streamData);
}
function extractStreamUrl(linkUrl) {
if (linkUrl.startsWith("data:application/octet-stream;charset=utf-8;base64,")) {
return decodeDataUrl(linkUrl);
}
if (linkUrl.includes("#/player/")) {
return decodePlayerRouteUrl(linkUrl);
}
return null;
}
function notifyOpeningInMpv(link) {
const linkText = (link.textContent || "").trim();
const streamLabel = linkText !== "" ? linkText : "Selected stream";
const compactLabel = streamLabel.replace(/\s+/g, " ").slice(0, 72);
const container = document.querySelector(".toasts-container-oKECy") || document.querySelector("#app");
if (!container) {
return;
}
const toast = document.createElement("div");
toast.className = "tooltip-container-Qpse8 tooltip-item-gfYXu";
toast.textContent = `Opening in MPV: ${compactLabel}`;
// Keep the visual feel aligned with Stremio while guaranteeing visibility.
toast.style.position = "fixed";
toast.style.right = "16px";
toast.style.bottom = "16px";
toast.style.zIndex = "999999";
toast.style.padding = "10px 14px";
toast.style.borderRadius = "10px";
toast.style.background = "rgba(32, 34, 38, 0.95)";
toast.style.color = "#f2f3f5";
toast.style.fontSize = "13px";
toast.style.lineHeight = "1.3";
toast.style.border = "1px solid rgba(255, 255, 255, 0.12)";
toast.style.boxShadow = "0 8px 24px rgba(0, 0, 0, 0.35)";
toast.style.maxWidth = "360px";
toast.style.pointerEvents = "none";
toast.style.opacity = "0";
toast.style.transform = "translateY(8px)";
toast.style.transition = "opacity 140ms ease, transform 140ms ease";
container.appendChild(toast);
requestAnimationFrame(() => {
toast.style.opacity = "1";
toast.style.transform = "translateY(0)";
});
setTimeout(() => {
toast.remove();
}, 2200);
}
function bindMpvClick(link) {
if (link.dataset.clickBound === "true") {
return;
}
link.dataset.clickBound = "true";
link.target = "_self";
link.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
notifyOpeningInMpv(link);
setTimeout(() => {
window.location.href = link.href;
}, 120);
});
}
let lastContextMenuStreamLink = null;
function getMpvHandlerUrlFromLink(link) {
if (!link || typeof link.href !== "string") {
return null;
}
if (link.href.startsWith("mpv-handler://") || link.href.startsWith("mpv-handler-debug://")) {
return link.href;
}
const decodedUrl = extractStreamUrl(link.href);
if (!decodedUrl) {
return null;
}
return generateProto(decodedUrl);
}
function resolveContextMenuStreamLink(menuContent) {
return (
menuContent.closest("a.stream-container-JPdah") ||
document.querySelector("a.stream-container-JPdah.active") ||
lastContextMenuStreamLink
);
}
function injectPlayOnMpvContextOption(menuContent, streamLink) {
if (menuContent.querySelector('[data-mpv-context-option="true"]')) {
return;
}
const templateOption = menuContent.querySelector(".context-menu-option-container-BZGla");
if (!templateOption) {
return;
}
const mpvHandlerUrl = getMpvHandlerUrlFromLink(streamLink);
if (!streamLink || !mpvHandlerUrl) {
return;
}
const option = templateOption.cloneNode(true);
option.dataset.mpvContextOption = "true";
option.title = "Play on MPV";
const label = option.querySelector(".context-menu-option-label-EbNNz");
if (label) {
label.textContent = "Play on MPV";
}
option.addEventListener(
"click",
(event) => {
event.preventDefault();
event.stohttps://web.stremio.com/#/settingspPropagation();
notifyOpeningInMpv(streamLink);
setTimeout(() => {
window.location.href = mpvHandlerUrl;
}, 120);
},
true,
);
// Insert after the title and before the first Play button
const titleElement = menuContent.querySelector(".context-menu-title-aoWE4");
if (titleElement && titleElement.nextElementSibling) {
menuContent.insertBefore(option, titleElement.nextElementSibling);
} else {
menuContent.insertBefore(option, menuContent.firstChild);
}
}
function enhanceContextMenus() {
const menuContents = document.querySelectorAll(".context-menu-content-Xe_lN");
menuContents.forEach((menuContent) => {
const streamLink = resolveContextMenuStreamLink(menuContent);
if (streamLink) {
injectPlayOnMpvContextOption(menuContent, streamLink);
}
});
}
function trackContextMenuTarget() {
document.addEventListener(
"contextmenu",
(event) => {
const streamLink = event.target.closest("a.stream-container-JPdah");
if (streamLink) {
lastContextMenuStreamLink = streamLink;
// Inject option immediately without async delay
const menuContent = document.querySelector(".context-menu-content-Xe_lN");
if (menuContent) {
injectPlayOnMpvContextOption(menuContent, streamLink);
}
}
},
true,
);
}
// Function to process links with enhanced mpv-handler integration
function processLinks() {
// Stream links are left unmodified for default streaming behavior.
// The "Play on MPV" option is available only via right-click context menu.
// This is handled by enhanceContextMenus() which is called separately.
}
// Notify update about mpv-handler
function notifyUpdate() {
let version = GM_getValue("mpvHandlerVersion", null);
if (version !== MPV_HANDLER_VERSION) {
const UPDATE_NOTIFY = {
title: `${GM_info.script.name}`,
text: `mpv-handler is upgraded to ${MPV_HANDLER_VERSION}\n\nClick to check updates`,
onclick: () => {
window.open("https://github.com/akiirui/mpv-handler/releases/latest");
},
};
GM_notification(UPDATE_NOTIFY);
GM_setValue("mpvHandlerVersion", MPV_HANDLER_VERSION);
}
}
// Register menu commands for easy access to settings
function registerMenuCommands() {
GM_registerMenuCommand("MPV Settings", () => {
if (!GM_config.isOpen) {
GM_config.open();
GM_config.frame.style = CONFIG_IFRAME_CSS.trim();
}
});
GM_registerMenuCommand("Process Links Manually", () => {
processLinks();
GM_notification({
title: 'Stremio MPV',
text: 'Processing Stremio links...',
timeout: 2000
});
});
}
// Create a MutationObserver to watch for DOM changes with throttling
let processTimeout;
const observer = new MutationObserver(() => {
// Throttle the processing to avoid multiple rapid calls
clearTimeout(processTimeout);
processTimeout = setTimeout(() => {
processLinks();
enhanceContextMenus();
}, 500); // Wait 500ms before processing
});
// Start observing the document
function startObserver() {
if (document.body) {
observer.observe(document.body, {
childList: true,
subtree: true
});
} else {
// If body is not ready, wait and try again
setTimeout(startObserver, 100);
}
}
// Fix TrustedHTML
if (window.trustedTypes && window.trustedTypes.createPolicy) {
window.trustedTypes.createPolicy("default", {
createHTML: (string) => string,
});
}
// Initialize the script
function init() {
notifyUpdate();
setupSettingsIntegration();
registerMenuCommands();
trackContextMenuTarget();
startObserver();
// Initial processing
processLinks();
enhanceContextMenus();
}
// Wait for DOM to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}