-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
3537 lines (3148 loc) · 132 KB
/
content.js
File metadata and controls
3537 lines (3148 loc) · 132 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
(() => {
const DEBUG = false;
const DEBUG_PREFIX = '[StreamSaver][content]';
const SETTINGS_MENU_DEBUG_MODE = false;
const QUALITY_VALUES = ['160p', '360p', '480p', '720p', '1080p', '1440p', '2160p', 'Source'];
const QUALITY_SET = new Set(QUALITY_VALUES);
const QUALITY_ORDER_MAP = QUALITY_VALUES.reduce((acc, quality, index) => {
acc[quality] = index;
return acc;
}, {});
const QUALITY_ENTRY_TERMS = ['quality', 'qualität', 'video quality', 'resolution', 'auflösung'];
const SETTINGS_TRIGGER_TERMS = ['settings', 'einstellungen'];
const SETTINGS_MENU_LABEL_GROUPS = {
quality: ['qualität', 'quality', 'auflösung', 'resolution'],
subtitles: ['untertitel', 'subtitles'],
advanced: ['erweitert', 'advanced']
};
const SETTINGS_MENU_CLOSE_TERMS = ['schließen', 'schliessen', 'close'];
const SETTINGS_MENU_BACK_TERMS = ['zurück', 'zurueck', 'back', 'go back'];
const SOURCE_TERMS = ['source', 'quelle', 'chunked'];
const RESOLUTION_PATTERN = /\b(160|360|480|720|1080|1440|2160)\s*p?\d*\b/i;
const MODE_VALUES = {
LOW: 'low',
HIGH: 'high'
};
const MODE_SET = new Set(Object.values(MODE_VALUES));
const STORAGE_KEYS = {
FAST_TOGGLE_LOW: 'fastToggleLow',
FAST_TOGGLE_HIGH: 'fastToggleHigh',
ACTIVE_MODE: 'activeMode',
PLUGIN_ENABLED: 'pluginEnabled'
};
const DEFAULT_MODE_SETTINGS = {
[STORAGE_KEYS.FAST_TOGGLE_LOW]: '480p',
[STORAGE_KEYS.FAST_TOGGLE_HIGH]: 'Source',
[STORAGE_KEYS.ACTIVE_MODE]: MODE_VALUES.HIGH,
[STORAGE_KEYS.PLUGIN_ENABLED]: true
};
const ENFORCEMENT_COOLDOWN_MS = 6000;
const ENFORCEMENT_DEBOUNCE_MS = 600;
const ENFORCEMENT_PLAYER_READY_TIMEOUT_MS = 6000;
const QUALITY_TRUST_TTL_MS = 25_000; // skip detect+set when quality was recently confirmed
let activeSetQualityRun = null;
const enforcementState = {
inProgress: false,
scheduledTimerId: null,
lastRunAtMs: 0,
lastRunUrl: '',
lastResolvedTargetQuality: '',
lastConfirmedQualityAtMs: 0, // when quality was last successfully confirmed (detect or set)
urlWatchTimerId: null
};
const fullscreenState = {
userIntended: false, // user explicitly entered fullscreen
restorationAttempts: 0,
restorationInProgress: false
};
// Guard: run only on twitch.tv hosts.
if (!location.hostname.endsWith('twitch.tv')) {
return;
}
/** Lightweight debug logger that can be disabled from one flag. */
function debug(message, details) {
if (!DEBUG) return;
if (details !== undefined) {
console.log(`${DEBUG_PREFIX} ${message}`, details);
return;
}
console.log(`${DEBUG_PREFIX} ${message}`);
}
/** Standard result envelope for internal automation steps. */
function createResult(ok, code, message, details = null) {
return { ok, code, message, details };
}
/** Serializes values into message-safe JSON data. */
function serializeForMessage(value, depth = 0, seen = new WeakSet()) {
if (depth > 8) {
return '[MaxDepth]';
}
if (value === null || value === undefined) {
return value;
}
const valueType = typeof value;
if (valueType === 'string' || valueType === 'number' || valueType === 'boolean') {
return value;
}
if (valueType === 'function') {
return '[Function]';
}
if (value instanceof Element) {
const tagName = value.tagName ? value.tagName.toLowerCase() : 'element';
return `[DOM:${tagName}]`;
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message
};
}
if (Array.isArray(value)) {
return value.map((item) => serializeForMessage(item, depth + 1, seen));
}
if (valueType === 'object') {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
const output = {};
for (const [key, nestedValue] of Object.entries(value)) {
output[key] = serializeForMessage(nestedValue, depth + 1, seen);
}
return output;
}
return String(value);
}
/** Promise-based sleep helper for retry loops. */
function wait(ms) {
const delay = Number.isFinite(ms) ? Math.max(0, ms) : 0;
return new Promise((resolve) => setTimeout(resolve, delay));
}
/** Returns a small random offset in [-px, +px] to de-mechanize synthetic coordinates. */
function jitter(px = 8) {
return (Math.random() - 0.5) * px * 2;
}
/** Visibility guard used before reading/clicking Twitch UI elements. */
function isElementVisible(element) {
if (!(element instanceof Element) || !element.isConnected) {
return false;
}
if (element.hasAttribute('hidden') || element.getAttribute('aria-hidden') === 'true') {
return false;
}
const style = window.getComputedStyle(element);
if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') {
return false;
}
if (Number(style.opacity) === 0) {
return false;
}
const rect = element.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
/** Lighter visibility check for entries already inside a validated menu root.
* Uses offsetWidth/offsetHeight instead of getBoundingClientRect to avoid
* false-negatives in Firefox when a parent has filter:opacity(0) applied
* (the menu hider), which can cause child rects to be misreported as 0×0. */
function isMenuEntryUsable(element) {
if (!(element instanceof Element) || !element.isConnected) return false;
if (element.hasAttribute('hidden') || element.getAttribute('aria-hidden') === 'true') return false;
const style = window.getComputedStyle(element);
if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') return false;
return element.offsetWidth > 0 || element.offsetHeight > 0;
}
/** Returns readable text with ARIA/title fallbacks for menu matching. */
function getVisibleText(element) {
if (!(element instanceof Element) || !isElementVisible(element)) {
return '';
}
const ariaLabel = element.getAttribute('aria-label');
const title = element.getAttribute('title');
const rawText = ariaLabel || element.innerText || title || element.textContent || '';
return rawText.replace(/\s+/g, ' ').trim();
}
/** Performs a defensive click with pre-checks and safe focus/scroll attempts. */
function clickElementSafely(element, options = {}) {
if (!(element instanceof HTMLElement)) {
return createResult(false, 'INVALID_ELEMENT', 'Click target is not an HTML element.');
}
if (!isElementVisible(element)) {
return createResult(false, 'ELEMENT_HIDDEN', 'Click target is not visible.');
}
if (element.matches('[disabled], [aria-disabled="true"]')) {
return createResult(false, 'ELEMENT_DISABLED', 'Click target is disabled.');
}
if (options.prepare !== false) {
try {
element.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
} catch (error) {
debug('scrollIntoView failed but continuing', String(error));
}
try {
element.focus({ preventScroll: true });
} catch (error) {
debug('focus failed but continuing', String(error));
}
}
if (element.tagName === 'A' && element.hasAttribute('href')) {
return createResult(false, 'NAVIGATION_LINK', 'Refusing to click anchor with href — would cause page navigation.');
}
try {
element.click();
return createResult(true, 'CLICKED', 'Element clicked successfully.');
} catch (error) {
return createResult(false, 'CLICK_FAILED', 'Element click threw an error.', {
error: String(error)
});
}
}
/** Waits until a condition succeeds or times out. */
async function waitForCondition(fn, options = {}) {
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 5000;
const intervalMs = Number.isFinite(options.intervalMs) ? options.intervalMs : 100;
const description = typeof options.description === 'string' ? options.description : 'condition';
const startedAt = Date.now();
let attempts = 0;
let lastError = null;
while (Date.now() - startedAt < timeoutMs) {
attempts += 1;
try {
const value = await fn();
if (value) {
return createResult(true, 'CONDITION_MET', `${description} satisfied.`, {
value,
attempts,
elapsedMs: Date.now() - startedAt
});
}
} catch (error) {
lastError = String(error);
}
await wait(intervalMs);
}
return createResult(false, 'TIMEOUT', `Timed out waiting for ${description}.`, {
attempts,
elapsedMs: Date.now() - startedAt,
lastError
});
}
/** Normalizes Twitch quality labels into extension-level quality keys. */
function normalizeQualityLabel(label) {
const raw = String(label || '').replace(/\s+/g, ' ').trim();
if (!raw) {
return '';
}
const lower = raw.toLowerCase();
if (SOURCE_TERMS.some((term) => lower.includes(term))) return 'Source';
if (hasResolutionValue(lower, '2160')) return '2160p';
if (hasResolutionValue(lower, '1440')) return '1440p';
if (hasResolutionValue(lower, '1080')) return '1080p';
if (hasResolutionValue(lower, '720')) return '720p';
if (hasResolutionValue(lower, '480')) return '480p';
if (hasResolutionValue(lower, '360')) return '360p';
if (hasResolutionValue(lower, '160')) return '160p';
return '';
}
/** Matches one numeric resolution token while avoiding partial number collisions. */
function hasResolutionValue(text, value) {
const lower = String(text || '').toLowerCase();
const pattern = new RegExp(`(^|[^0-9])${value}(?:\\s*p\\d*)?(?=$|[^0-9])`, 'i');
return pattern.test(lower);
}
/** Extracts a normalized resolution key from option text. */
function extractResolutionQuality(label) {
const lower = String(label || '').toLowerCase();
if (!lower) {
return '';
}
if (hasResolutionValue(lower, '2160')) return '2160p';
if (hasResolutionValue(lower, '1440')) return '1440p';
if (hasResolutionValue(lower, '1080')) return '1080p';
if (hasResolutionValue(lower, '720')) return '720p';
if (hasResolutionValue(lower, '480')) return '480p';
if (hasResolutionValue(lower, '360')) return '360p';
if (hasResolutionValue(lower, '160')) return '160p';
return '';
}
/** Detects whether a label uses any source-level alias terms. */
function labelHasSourceAlias(label) {
const lower = String(label || '').toLowerCase();
return SOURCE_TERMS.some((term) => lower.includes(term));
}
/** Infers which concrete resolutions are represented by source-like menu labels. */
function inferSourceAliasTargets(qualityEntryLabel, options = []) {
const inferred = new Set();
// Add source-like labels only when they include a concrete resolution.
const maybeAdd = (label) => {
if (!labelHasSourceAlias(label)) {
return;
}
const resolution = extractResolutionQuality(label);
if (resolution && QUALITY_SET.has(resolution)) {
inferred.add(resolution);
}
};
maybeAdd(qualityEntryLabel);
for (const option of Array.isArray(options) ? options : []) {
if (option && typeof option.label === 'string') {
maybeAdd(option.label);
}
}
return inferred;
}
/** Checks whether a settings row looks like quality. */
function analyzeQualityEntryText(label) {
const text = String(label || '').replace(/\s+/g, ' ').trim();
const lower = text.toLowerCase();
const matchedBy = [];
if (QUALITY_ENTRY_TERMS.some((term) => lower.includes(term))) {
matchedBy.push('qualityLabel');
}
if (RESOLUTION_PATTERN.test(lower)) {
matchedBy.push('resolutionValue');
}
if (SOURCE_TERMS.some((term) => lower.includes(term))) {
matchedBy.push('sourceLabel');
}
// Prefer explicit quality terms, but allow resolution+source hints.
const isQualityEntry =
matchedBy.includes('qualityLabel') ||
(matchedBy.includes('resolutionValue') && matchedBy.includes('sourceLabel'));
return { isQualityEntry, matchedBy };
}
/** Matches a requested quality against option text. */
function qualityLabelMatchesTarget(label, normalizedTarget, options = {}) {
const lower = String(label || '').toLowerCase();
if (!lower || !QUALITY_SET.has(normalizedTarget)) {
return false;
}
if (normalizedTarget === 'Source') {
// Source can appear as Source, Quelle, or Chunked.
return labelHasSourceAlias(lower);
}
const resolution = extractResolutionQuality(lower);
if (resolution === normalizedTarget) {
return true;
}
const allowSourceAliasForTargets = options?.allowSourceAliasForTargets;
const canUseSourceAlias =
allowSourceAliasForTargets instanceof Set && allowSourceAliasForTargets.has(normalizedTarget);
if (canUseSourceAlias && labelHasSourceAlias(lower)) {
return true;
}
return false;
}
/** Finds the best visible root for the Twitch player. */
function getPlayerRoot() {
const selectors = [
'[data-a-target="video-player"]',
'[role="application"][aria-label*="player" i]',
'[role="region"][aria-label*="player" i]',
'[role="region"][aria-label*="video" i]',
'video'
];
for (const selector of selectors) {
const candidates = Array.from(document.querySelectorAll(selector));
for (const candidate of candidates) {
const root = selector === 'video' ? candidate.closest('section, div, main, article') || candidate : candidate;
if (isElementVisible(root)) {
return createResult(true, 'PLAYER_FOUND', 'Found likely Twitch player root.', {
selector,
element: root
});
}
}
}
return createResult(false, 'PLAYER_NOT_FOUND', 'No visible Twitch player root was found.');
}
// Ref-count for the menu hider. showMenuHider increments, hideMenuHider decrements.
// The style is only removed when the count reaches zero AND menus are confirmed closed,
// so back-to-back automation calls (detect → set) share one continuous hider lifetime.
let _menuHiderCount = 0;
/** Injects a CSS rule that makes Twitch player menus visually transparent while the
* extension interacts with them.
* - filter:opacity(0) — hides menus visually without affecting isElementVisible() or
* getBoundingClientRect(), so all JS-driven interaction still works.
* - pointer-events:none — lets document.elementFromPoint() see through the invisible menu
* to the player below, which is required for closeMenusIfNeeded's
* player-area click fallback to find a valid click target. */
function showMenuHider() {
_menuHiderCount++;
debug('menuHider: show', { count: _menuHiderCount, t: Date.now() });
if (document.getElementById('streamsaver-menu-hider')) return;
const style = document.createElement('style');
style.id = 'streamsaver-menu-hider';
style.textContent =
'[role="menu"],[role="listbox"],' +
'[data-a-target*="settings-menu" i],' +
'[data-a-target*="dropdown-menu" i],[data-test-selector*="menu" i],' +
'[class*="settings-menu" i]{filter:opacity(0)!important;pointer-events:none!important;}';
document.head.appendChild(style);
}
/** Decrements the hider ref-count and, once it reaches zero, polls until menus are
* confirmed gone before removing the style. This ensures a lingering or stuck menu is
* never revealed to the user when the hider lifts. Hard timeout: 800 ms. */
async function hideMenuHider() {
_menuHiderCount = Math.max(0, _menuHiderCount - 1);
if (_menuHiderCount > 0) return;
// If menus are still open, make one extra close attempt. pointer-events:none is still
// active here, so document.elementFromPoint() sees through the invisible menu to the
// player — this is the path that was failing at channel-join time.
if (findVisibleMenuRoots().length > 0) {
await closeMenusIfNeeded({ allowBodyClick: true, aggressiveBodyClicks: true, maxAttempts: 2 });
}
// Poll briefly to confirm menus are gone before lifting the hider.
const deadline = Date.now() + 400;
while (Date.now() < deadline) {
if (_menuHiderCount > 0) return;
if (findVisibleMenuRoots().length === 0) break;
await wait(60);
}
if (_menuHiderCount > 0) return;
debug('menuHider: hide (lock lifted)', { t: Date.now() });
document.getElementById('streamsaver-menu-hider')?.remove();
}
/** Collects visible menu-like overlay roots. */
function findVisibleMenuRoots() {
const selectors = [
'[role="menu"]',
'[role="listbox"]',
'[role="dialog"]',
'[aria-label*="settings" i][role="dialog"]',
'[data-a-target*="player-settings" i]',
'[data-a-target*="settings-menu" i]',
'[data-a-target*="dropdown-menu" i]',
'[data-test-selector*="menu" i]',
'[class*="settings-menu" i]'
];
const seen = new Set();
const roots = [];
for (const selector of selectors) {
for (const element of Array.from(document.querySelectorAll(selector))) {
if (!isElementVisible(element)) {
continue;
}
if (seen.has(element)) {
continue;
}
seen.add(element);
roots.push(element);
}
}
return roots;
}
/** Fallback finder for settings-like containers by visible text. */
function findSettingsMenuRootsByText() {
const selector = 'div, section, [role="dialog"], [data-a-target], [class*="menu" i]';
const raw = [];
for (const element of Array.from(document.querySelectorAll(selector))) {
if (!isElementVisible(element)) {
continue;
}
const rect = element.getBoundingClientRect();
if (rect.width < 180 || rect.height < 120) {
continue;
}
if (rect.width > window.innerWidth * 0.96 || rect.height > window.innerHeight * 0.96) {
continue;
}
const lower = String(element.innerText || element.textContent || '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
if (!lower) {
continue;
}
const hasQuality = SETTINGS_MENU_LABEL_GROUPS.quality.some((term) => lower.includes(term));
const hasSubtitles = SETTINGS_MENU_LABEL_GROUPS.subtitles.some((term) => lower.includes(term));
const hasAdvanced = SETTINGS_MENU_LABEL_GROUPS.advanced.some((term) => lower.includes(term));
const hasClose = SETTINGS_MENU_CLOSE_TERMS.some((term) => lower.includes(term));
const matchedGroupCount = Number(hasQuality) + Number(hasSubtitles) + Number(hasAdvanced);
if (!(matchedGroupCount >= 2 || (hasQuality && hasClose))) {
continue;
}
raw.push(element);
}
// Keep smallest matching containers to avoid huge wrapper nodes.
raw.sort((a, b) => {
const rectA = a.getBoundingClientRect();
const rectB = b.getBoundingClientRect();
return rectA.width * rectA.height - rectB.width * rectB.height;
});
const kept = [];
for (const element of raw) {
if (kept.some((existing) => element.contains(existing))) {
continue;
}
kept.push(element);
if (kept.length >= 3) {
break;
}
}
return kept;
}
/** Fallback probe: player-near panel with visible quality text. */
function findPlayerNearQualityPanel(playerRoot) {
if (!(playerRoot instanceof Element) || !isElementVisible(playerRoot)) {
return null;
}
const roots = findVisibleMenuRoots();
const seen = new Set(roots);
for (const root of findSettingsMenuRootsByText()) {
if (!seen.has(root)) {
seen.add(root);
roots.push(root);
}
}
const playerRect = playerRoot.getBoundingClientRect();
for (const root of roots) {
if (!isElementVisible(root)) {
continue;
}
const rect = root.getBoundingClientRect();
if (!isRectNear(playerRect, rect, 120)) {
continue;
}
const text = String(root.innerText || root.textContent || '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
if (!text) {
continue;
}
const hasQuality = SETTINGS_MENU_LABEL_GROUPS.quality.some((term) => text.includes(term));
if (!hasQuality) {
continue;
}
return {
rect: serializeRect(rect),
hasQuality,
hasClose: SETTINGS_MENU_CLOSE_TERMS.some((term) => text.includes(term)),
textPreview: text.slice(0, 220)
};
}
return null;
}
/** Shows player controls by dispatching hover events. */
function triggerPlayerHover(playerRoot) {
if (!(playerRoot instanceof Element)) {
return;
}
const rect = playerRoot.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) {
return;
}
const hoverPoints = [
{ x: rect.left + rect.width * 0.5 + jitter(), y: rect.top + rect.height * 0.5 + jitter() },
{ x: rect.left + rect.width * 0.85 + jitter(), y: rect.top + rect.height * 0.9 + jitter() }
];
for (const point of hoverPoints) {
playerRoot.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, clientX: point.x, clientY: point.y }));
playerRoot.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, clientX: point.x, clientY: point.y }));
playerRoot.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: point.x, clientY: point.y }));
}
}
/** Serializes DOMRect values into compact integer coordinates for debug payloads. */
function serializeRect(rect) {
return {
x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.round(rect.width),
height: Math.round(rect.height)
};
}
/** Checks whether `innerRect` is inside `outerRect`. */
function isRectInside(outerRect, innerRect, tolerance = 0) {
return (
innerRect.left >= outerRect.left - tolerance &&
innerRect.right <= outerRect.right + tolerance &&
innerRect.top >= outerRect.top - tolerance &&
innerRect.bottom <= outerRect.bottom + tolerance
);
}
/** Checks whether two rectangles overlap or are nearby. */
function isRectNear(rectA, rectB, threshold = 40) {
return !(
rectA.right < rectB.left - threshold ||
rectA.left > rectB.right + threshold ||
rectA.bottom < rectB.top - threshold ||
rectA.top > rectB.bottom + threshold
);
}
/** Finds visible player control containers inside the active player root. */
function findPlayerControlScopes(playerRoot) {
if (!(playerRoot instanceof Element)) {
return [];
}
const selectors = [
'[data-a-target*="player-controls" i]',
'[data-a-target*="player-control" i]',
'[data-a-target*="player-overlay" i]',
'[aria-label*="player controls" i]',
'[class*="player-controls" i]',
'[role="toolbar"]'
];
const seen = new Set();
const scopes = [];
for (const selector of selectors) {
for (const element of Array.from(playerRoot.querySelectorAll(selector))) {
if (!isElementVisible(element) || seen.has(element)) {
continue;
}
seen.add(element);
scopes.push({
selector,
element,
rect: serializeRect(element.getBoundingClientRect())
});
}
}
return scopes;
}
/** Finds settings-button candidates only inside the player controls region. */
function collectSettingsButtonCandidates(playerRoot, controlScopes) {
if (!(playerRoot instanceof Element)) {
return [];
}
if (controlScopes.length === 0) {
return [];
}
const playerRect = playerRoot.getBoundingClientRect();
const scopeElements = controlScopes.map((scope) => scope.element);
const triggerSelectors = [
'[aria-label]',
'[title]',
'[data-a-target]',
'button',
'[role="button"]'
];
const seen = new Set();
const candidates = [];
for (const selector of triggerSelectors) {
for (const scopeElement of scopeElements) {
for (const node of Array.from(scopeElement.querySelectorAll(selector))) {
if (!(node instanceof HTMLElement) || !isElementVisible(node) || seen.has(node)) {
continue;
}
seen.add(node);
if (!playerRoot.contains(node)) {
continue;
}
if (node.matches('a, [role="link"]')) {
continue;
}
if (!node.matches('button, [role="button"], [data-a-target]')) {
continue;
}
const rect = node.getBoundingClientRect();
if (!isRectInside(playerRect, rect, 8)) {
continue;
}
const text = getVisibleText(node);
const ariaLabel = String(node.getAttribute('aria-label') || '');
const title = String(node.getAttribute('title') || '');
const dataTarget = String(node.getAttribute('data-a-target') || '');
const textLower = text.toLowerCase();
const ariaLower = ariaLabel.toLowerCase();
const titleLower = title.toLowerCase();
const dataTargetLower = dataTarget.toLowerCase();
const matchedBy = [];
if (SETTINGS_TRIGGER_TERMS.some((term) => textLower.includes(term))) matchedBy.push('visibleText');
if (SETTINGS_TRIGGER_TERMS.some((term) => ariaLower.includes(term))) matchedBy.push('ariaLabel');
if (SETTINGS_TRIGGER_TERMS.some((term) => titleLower.includes(term))) matchedBy.push('title');
if (SETTINGS_TRIGGER_TERMS.some((term) => dataTargetLower.includes(term))) matchedBy.push('dataATarget');
if (matchedBy.length === 0) {
continue;
}
const inControlScope = controlScopes.some((scope) => scope.element.contains(node));
if (!inControlScope) {
continue;
}
const score = matchedBy.length + 2 + (dataTargetLower.includes('player') ? 1 : 0);
candidates.push({
element: node,
selector,
text,
ariaLabel,
title,
dataTarget,
matchedBy,
inControlScope,
score,
rect: serializeRect(rect)
});
}
}
}
candidates.sort((a, b) => b.score - a.score || b.rect.x - a.rect.x);
return candidates;
}
/** Collects visible menu labels with dedupe and fallback parsing. */
function getVisibleMenuEntryTexts(menuRoot) {
const selector = 'button, [role="menuitem"], [role="menuitemradio"], [role="option"], [role="button"], a';
const seen = new Set();
const entries = [];
for (const entry of Array.from(menuRoot.querySelectorAll(selector))) {
if (!isElementVisible(entry)) {
continue;
}
const text = getVisibleText(entry);
if (!text) {
continue;
}
const key = text.toLowerCase();
if (seen.has(key)) {
continue;
}
seen.add(key);
entries.push(text);
}
if (entries.length > 0) {
return entries;
}
// Fallback for menu variants that render plain text rows.
const rootText = String(menuRoot.innerText || menuRoot.textContent || '');
if (!rootText.trim()) {
return [];
}
const textLines = rootText
.split(/\n+/)
.map((line) => line.replace(/\s+/g, ' ').trim())
.filter((line) => line.length >= 2);
const deduped = [];
const seenLines = new Set();
for (const line of textLines) {
const key = line.toLowerCase();
if (seenLines.has(key)) {
continue;
}
seenLines.add(key);
deduped.push(line);
if (deduped.length >= 20) {
break;
}
}
return deduped;
}
/** Checks whether a visible menu resembles player settings. */
function isLikelyPlayerSettingsMenu(menuRoot, playerRoot) {
if (!(menuRoot instanceof Element) || !isElementVisible(menuRoot)) {
return {
accepted: false,
reason: 'Rejected: menu is not visible.',
details: {
menuItemCount: 0,
entryTexts: []
}
};
}
const playerRect = playerRoot.getBoundingClientRect();
const menuRect = menuRoot.getBoundingClientRect();
const nearPlayer = isRectNear(playerRect, menuRect, 48);
const entryTexts = getVisibleMenuEntryTexts(menuRoot);
const loweredEntries = entryTexts.map((text) => text.toLowerCase());
const rootTextLower = String(menuRoot.innerText || menuRoot.textContent || '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
// Check entry labels and full menu text because Twitch markup varies.
const containsTerm = (terms) => {
return terms.some((term) => loweredEntries.some((text) => text.includes(term)) || rootTextLower.includes(term));
};
const hasQuality = containsTerm(SETTINGS_MENU_LABEL_GROUPS.quality);
const hasSubtitles = containsTerm(SETTINGS_MENU_LABEL_GROUPS.subtitles);
const hasAdvanced = containsTerm(SETTINGS_MENU_LABEL_GROUPS.advanced);
const hasClose = containsTerm(SETTINGS_MENU_CLOSE_TERMS);
const matchedGroups = [];
if (hasQuality) matchedGroups.push('quality');
if (hasSubtitles) matchedGroups.push('subtitles');
if (hasAdvanced) matchedGroups.push('advanced');
const strongSemanticMatch = matchedGroups.length >= 2 || (matchedGroups.includes('quality') && hasClose);
const accepted = entryTexts.length > 0 && matchedGroups.length > 0 && (nearPlayer || strongSemanticMatch);
let reason = 'Accepted: menu matches player-settings entries and location.';
if (entryTexts.length === 0) {
reason = 'Rejected: menu has no visible entries.';
} else if (matchedGroups.length === 0) {
reason = 'Rejected: menu entries do not contain quality/subtitles/advanced labels.';
} else if (!nearPlayer && !strongSemanticMatch) {
reason = 'Rejected: menu is not near player and semantic match is too weak.';
} else if (!nearPlayer && strongSemanticMatch) {
reason = 'Accepted: strong semantic match despite imperfect geometry.';
}
return {
accepted,
reason,
details: {
nearPlayer,
role: String(menuRoot.getAttribute('role') || ''),
ariaLabel: String(menuRoot.getAttribute('aria-label') || ''),
dataTarget: String(menuRoot.getAttribute('data-a-target') || ''),
rect: serializeRect(menuRect),
menuItemCount: entryTexts.length,
hasClose,
matchedGroups,
entryTexts
}
};
}
/** Returns settings menu state with one clear match. */
function findOpenPlayerSettingsMenu(playerRoot, options = {}) {
if (!(playerRoot instanceof Element) || !isElementVisible(playerRoot)) {
return createResult(false, 'PLAYER_NOT_FOUND', 'Cannot inspect menus without a visible player root.');
}
const menuRoots = findVisibleMenuRoots();
const seenRoots = new Set(menuRoots);
const textFallbackRoots = findSettingsMenuRootsByText();
for (const root of textFallbackRoots) {
if (!seenRoots.has(root)) {
seenRoots.add(root);
menuRoots.push(root);
}
}
const assessedMenus = menuRoots.map((menuRoot, index) => ({
index,
menuRoot,
assessment: isLikelyPlayerSettingsMenu(menuRoot, playerRoot)
}));
const relevantMenus = assessedMenus.filter((item) => {
const nearPlayer = Boolean(item.assessment.details?.nearPlayer);
const menuItemCount = item.assessment.details?.menuItemCount || 0;
const matchedGroupsCount = item.assessment.details?.matchedGroups?.length || 0;
const hasClose = Boolean(item.assessment.details?.hasClose);
const hasSemantic = matchedGroupsCount >= 1 || hasClose;
return hasSemantic || (nearPlayer && menuItemCount >= 2);
});
const acceptedMenus = relevantMenus.filter((item) => item.assessment.accepted);
const topLevelAcceptedMenus = acceptedMenus.filter((item) => {
return !acceptedMenus.some((other) => other !== item && other.menuRoot.contains(item.menuRoot));
});
const assessments = assessedMenus.map((item) => item.assessment);
if (options.log !== false) {
debug('findOpenPlayerSettingsMenu: menu assessments', assessments.map((assessment, index) => ({
index,
nearPlayer: Boolean(assessment.details?.nearPlayer),
accepted: assessment.accepted,
reason: assessment.reason,
menuItemCount: assessment.details?.menuItemCount ?? 0,
matchedGroups: assessment.details?.matchedGroups || [],
entryTexts: assessment.details?.entryTexts || []
})));
debug('findOpenPlayerSettingsMenu: menu assessment summary', assessments.map((assessment, index) => {
const groups = (assessment.details?.matchedGroups || []).join(',');
const entryPreview = (assessment.details?.entryTexts || []).slice(0, 4).join(' | ');
return `#${index} near=${Boolean(assessment.details?.nearPlayer)} accepted=${assessment.accepted} groups=[${groups}] entries=${entryPreview}`;
}));
}
if (topLevelAcceptedMenus.length === 1) {
return createResult(true, 'PLAYER_SETTINGS_MENU_OPEN', 'One valid player settings menu is open.', {
menuCount: topLevelAcceptedMenus.length,
relevantCount: relevantMenus.length,
globalMenuCount: assessments.length,
acceptedCount: topLevelAcceptedMenus.length,
acceptedRawCount: acceptedMenus.length,
assessments
});
}
if (relevantMenus.length === 0) {
return createResult(false, 'NO_VISIBLE_MENUS', 'No visible player-near menus are open.', {
menuCount: 0,
relevantCount: 0,
globalMenuCount: assessments.length,
acceptedCount: 0,
acceptedRawCount: 0,
assessments
});
}
if (acceptedMenus.length === 0) {
return createResult(false, 'NO_VALID_PLAYER_SETTINGS_MENU', 'Visible menus found, but none match player settings.', {
menuCount: relevantMenus.length,
relevantCount: relevantMenus.length,
globalMenuCount: assessments.length,
acceptedCount: 0,
acceptedRawCount: 0,
assessments
});
}
return createResult(false, 'MULTIPLE_MENUS_OPEN', 'Multiple menus detected; expected exactly one player settings menu.', {
menuCount: topLevelAcceptedMenus.length,
relevantCount: relevantMenus.length,
globalMenuCount: assessments.length,
acceptedCount: topLevelAcceptedMenus.length,
acceptedRawCount: acceptedMenus.length,
assessments
});
}
/** Opens player settings and waits for the overlay. */
async function openSettingsMenu() {
debug('openSettingsMenu: locating settings trigger');
const playerRootResult = getPlayerRoot();
if (!playerRootResult.ok) {
debug('openSettingsMenu: player root not found', playerRootResult);
return createResult(false, 'PLAYER_NOT_FOUND', 'Cannot open settings without a visible player.');
}
const playerRoot = playerRootResult.details.element;
const playerRect = playerRoot.getBoundingClientRect();
debug('openSettingsMenu: player root found', {
selector: playerRootResult.details.selector,
rect: serializeRect(playerRect)