-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path468740-restore-youtube-username.js
3676 lines (3051 loc) · 155 KB
/
468740-restore-youtube-username.js
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
/*
MIT License
Copyright 2023 CY Fung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// ==UserScript==
// @name Restore YouTube Username from Handle to Custom
// @namespace http://tampermonkey.net/
// @version 0.13.12
// @license MIT License
// @author CY Fung
// @match https://www.youtube.com/*
// @match https://m.youtube.com/*
// @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
// @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/general-icon.png
// @supportURL https://github.com/cyfung1031/userscript-supports
// @run-at document-start
// @grant none
// @unwrap
// @allFrames true
// @inject-into page
// @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@5d83d154956057bdde19e24f95b332cb9a78fcda/library/default-trusted-type-policy.js
// @compatible firefox Violentmonkey
// @compatible firefox Tampermonkey
// @compatible firefox Firemonkey
// @compatible chrome Violentmonkey
// @compatible chrome Tampermonkey
// @compatible opera Violentmonkey
// @compatible opera Tampermonkey
// @compatible safari Stay
// @compatible edge Violentmonkey
// @compatible edge Tampermonkey
// @compatible brave Violentmonkey
// @compatible brave Tampermonkey
// @description To restore YouTube Username to the traditional custom name
// @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
// @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
// @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
// @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
// @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
// @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
// @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
// @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
// @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
// @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
// @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
// @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
// @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
// @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
// @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
// @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
// @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
// @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
// @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
// @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
// @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
// @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
// @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
// @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
// @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
// @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
// @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
// @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
// @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
// @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
// @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
// @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
// @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
// @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
// @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
// @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
// @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
// @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
// @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
// @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
// @description:tr Özel İsme Kullanıcı Adını İade Etme
// @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
// @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
// @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
// @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
// @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
// @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
// @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
// @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
// @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
// @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
// @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
// @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
// @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
// @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
// @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
// @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
// @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
// @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
// @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
// @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
// @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
// @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్కు పునరుద్ధరించండి
// @description:kn ಹ್ಯಾಂಡಲ್ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
// @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
// @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
// @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
// @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
// @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
// @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
// @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
// @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
// ==/UserScript==
const NUM_CHANNEL_ID_MIN_LEN_old1 = 4; // 4 = @abc
const NUM_CHANNEL_ID_MIN_LEN_1 = 2; // 4 = @abc -> 2 = @a
const NUM_CHANNEL_ID_MIN_LEN_2 = 3; // 5 = /@abc -> 3 = /@a
const defaultPolicy = (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy) || { createHTML: s => s };
function createHTML(s) {
return defaultPolicy.createHTML(s);
}
let trustHTMLErr = null;
try {
document.createElement('div').innerHTML = createHTML('1');
} catch (e) {
trustHTMLErr = e;
}
if (trustHTMLErr) {
console.log(`trustHTMLErr`, trustHTMLErr);
trustHTMLErr(); // exit userscript
}
// -----------------------------------------------------------------------------------------------------------------------------
/* jshint esversion:8 */
const Object_ = Object;
/**
@typedef {string} HandleText
* \@[-_a-zA-Z0-9.]{3,30} (before May 2024)
* See isDisplayAsHandle
*/
/**
@typedef {string} ChannelId
* UC[-_a-zA-Z0-9+=.]{22}
* https://support.google.com/youtube/answer/6070344?hl=en
* The channel ID is the 24 character alphanumeric string that starts with 'UC' in the channel URL.
*/
/**
@typedef {string} DisplayName
* Display Name
*/
/**
@typedef DisplayNameResultObject
@type {Object}
@property {DisplayName} title
@property {DisplayName} langTitle
@property {ChannelId?} externalId
@property {string[]} ownerUrls
@property {string} channelUrl
@property {string} vanityChannelUrl
@property {boolean|undefined} verified123
*/
/**
@typedef ChannelIdToHandleResult
@type {Object}
@property {HandleText} handleText
@property {boolean} justPossible
*/
(function (__CONTEXT__) {
'use strict';
// const JUST_REMOVE_AT_FOR_EXPANDED_LANG = true;
const USE_RSS_FETCHER = true; // might 404
const USE_TIMEOUT_SIGNAL = false;
const USE_CHANNEL_META = true;
const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
const USE_LANG_SPECIFIC_NAME = true;
const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
const FIX_RTL_ISSUE = true;
const IGNORE_NO_NAME = false;
/** @type {globalThis.PromiseConstructor} */
const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
let controller = new AbortController();
const r = controller.signal;
let cid = setTimeout(() => {
if (cid >= 1) {
cid = 0;
controller && controller.abort();
controller = null;
}
}, timeout);
r.clearTimeout = () => {
if (cid >= 1) {
clearTimeout(cid);
cid = 0;
}
}
return r;
} : () => { };
const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
const fxOperator = (proto, propertyName) => {
let propertyDescriptorGetter = null;
try {
propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
// https://github.com/cyfung1031/userscript-supports/issues/9
// .parentNode becomes DocumentFragment
/**
*
* Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
*
* e.g. ytd-comment-renderer#comment > div#body
*
* ${div#body}.parentNode = DocumentFragment <Node.parentNode>
* ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
*
* Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
*
* Alternative way: ytCustomElement.$.xxxxxxx
*
*/
} catch (e) { }
return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
};
const fxAPI = (proto, propertyName) => {
const methodFunc = proto[propertyName];
return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
};
/** @type { (node: Node)=>Node | null } */
const nodeParent = fxOperator(Node.prototype, 'parentNode');
/** @type { (node: Node)=>Node | null } */
const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
/** @type { (node: Node)=>Node | null } */
const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
/** @type { (node: ParentNode, selector: string)=>Element | null } */
const elementQS = fxAPI(Element.prototype, 'querySelector');
/** @type { (node: ParentNode, selector: string)=>Element[] } */
const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
/*
init
initialdata
state-progress
state-responsereceived
player-autonav-pause
state-change
state-navigateend
player-initialized
renderer-module-load-start
video-data-change
player-state-change
updateui
renderer-module-load-end -> channel owner DOM available
player-autonav-pause
updateui
renderer-module-load-start
updateui
renderer-module-load-end
playing
h5player.video-progress
h5player.video-progress
h5player.video-progress
h5player.video-progress
...
navigate new video
state-navigatestart
state-change => channel owener DOM vanished
state-progress
...
h5player.player-state-change
h5player.video-data-change
h5player.player-state-change
h5player.muted-autoplay-change
h5player.volume-change
h5player.video-data-change
h5player.volume-change
...
state-progress
...
state-progress => channel owner DOM appear [just before state-responsereceived]
state-responsereceived
video-data-change
state-change
state-navigateend
UX interaction
user-activity
player-autonav-pause
EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
EventTarget.prototype.dispatchEvent = function (ev) {
if (ev instanceof Event) {
if (ev.type === 'video-progress') { } else {
console.log(ev.type, this, ev.target)
if (ev.target === null) {
console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
}
}
}
return this.uhfsE.apply(this, arguments);
}
*/
const isMobile = location.hostname === 'm.youtube.com';
if (!isMobile && typeof AbortSignal !== 'undefined') {
document.addEventListener('yt-action', () => {
try {
yt.config_.EXPERIMENT_FLAGS.enable_profile_cards_on_comments = true;
} catch (e) { }
}, { capture: true, passive: true, once: true })
}
const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
const { retrieveCE } = isMobile ? (() => {
const retrieveCE = () => {
console.warn('retrieveCE is not supported');
}
return { retrieveCE };
})() : (() => {
const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
if (typeof customElements === 'undefined') {
if (!('__CE_registry' in document)) {
// https://github.com/webcomponents/polyfills/
Object.defineProperty(document, '__CE_registry', {
get() {
// return undefined
},
set(nv) {
if (typeof nv == 'object') {
delete this.__CE_registry;
this.__CE_registry = nv;
this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
}
return true;
},
enumerable: false,
configurable: true
})
}
let eventHandler = (evt) => {
document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
const f = callback;
callback = null;
eventHandler = null;
f();
};
document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
} else {
callback();
}
});
const retrieveCE = async (nodeName) => {
try {
isCustomElementsProvided || (await promiseForCustomYtElementsReady);
await customElements.whenDefined(nodeName);
const dummy = document.querySelector(nodeName) || document.createElement(nodeName);
const cProto = insp(dummy).constructor.prototype;
return cProto;
} catch (e) {
console.warn(e);
}
}
return { retrieveCE };
})();
const cfg = {};
class Mutex {
constructor() {
this.p = Promise.resolve()
}
/**
* @param {(lockResolve: () => void)} f
*/
lockWith(f) {
this.p = this.p.then(() => new Promise(f).catch(console.warn))
}
}
class OrderedMutex extends Mutex {
constructor() {
super();
this.nextIndex = 0;
this.arr = [];
this.lockFunc = resolve => {
if (this.arr.length >= 1) {
let f = this.arr[0];
if (typeof f === 'function') {
this.arr.shift();
if (this.nextIndex > 0) this.nextIndex--;
f(resolve);
return;
} else {
// reset if unknown error
this.arr.length = 0;
this.nextIndex = 0;
}
}
resolve();
};
}
/**
* @param {(lockResolve: () => void)} f
*/
add(f) {
if (this.nextIndex === this.arr.length) {
this.arr.push(f); this.nextIndex++;
} else {
this.arr.splice(this.nextIndex++, 0, f);
}
this.lockWith(this.lockFunc);
}
}
// usage: run network request one by one
const mutex = new OrderedMutex();
const createPipeline = () => {
let pipelineMutex = Promise.resolve();
const pipelineExecution = fn => {
return new Promise((resolve, reject) => {
pipelineMutex = pipelineMutex.then(async () => {
let res;
try {
res = await fn();
} catch (e) {
console.log('error_F1', e);
reject(e);
}
resolve(res);
}).catch(console.warn);
});
};
return pipelineExecution;
};
/**
* @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
* @template T */
/**
* usage: cache the network result per web application instance.
* @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
const displayNameResStore = new Map();
/**
* usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
* @type {WeakMap<Function, Function>} */
const dataChangedFuncStore = new WeakMap();
/**
* usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
* @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
const handleToChannelId = new Map();
/**
* usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
* @type {Map<ChannelId, ChannelIdToHandleResult>} */
const channelIdToHandle = new Map();
/**
* usage: replace handle to lang-specific display name
* @type {Map<HandleText, DisplayName>} */
const langPreferredDisplayNameMap = new Map();
/**
* AsyncValue
* @class
* @template T
*/
class AsyncValue {
constructor() {
/** @type {T | null} */
this.__value__ = null;
/** @type {((value: any)=>void) | null} */
this.__resolve__ = null;
this.__promise__ = new Promise(resolve => {
this.__resolve__ = resolve;
});
}
/**
*
* @param {T} value
*/
setValue(value) {
const promise = this.__promise__;
if (promise === null) throw 'Value has already been set.';
this.__value__ = value;
this.__promise__ = null;
this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
}
/**
*
* @returns {Promise<T>}
*/
async getValue() {
const promise = this.__promise__;
if (promise === null) return this.__value__;
await promise; // promise become null
this.__promise__ = null; // just in case
this.__resolve__ = null;
return this.__value__;
}
}
let isCSSAdded = false;
const addCSSRulesIfRequired = () => {
if (isCSSAdded) return;
isCSSAdded = true;
const style = document.createElement('style')
let nonce = document.querySelector('head style[nonce]');
nonce = nonce ? nonce.getAttribute('nonce') : null;
/* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (LTR, when mixed with LTR languages) */
/* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (pure) */
const cssText01_FIX_RTL_ISSUE = FIX_RTL_ISSUE ? `
/* Left-to-Right (LTR) Languages */
#contenteditable-root.yt-formatted-string:lang(en) /* English */,
#contenteditable-root.yt-formatted-string:lang(es) /* Spanish */,
#contenteditable-root.yt-formatted-string:lang(fr) /* French */,
#contenteditable-root.yt-formatted-string:lang(de) /* German */,
#contenteditable-root.yt-formatted-string:lang(it) /* Italian */,
#contenteditable-root.yt-formatted-string:lang(pt) /* Portuguese */,
#contenteditable-root.yt-formatted-string:lang(ru) /* Russian */,
#contenteditable-root.yt-formatted-string:lang(zh) /* Chinese */,
#contenteditable-root.yt-formatted-string:lang(ja) /* Japanese */,
#contenteditable-root.yt-formatted-string:lang(ko) /* Korean */,
#contenteditable-root.yt-formatted-string:lang(nl) /* Dutch */,
#contenteditable-root.yt-formatted-string:lang(sv) /* Swedish */,
#contenteditable-root.yt-formatted-string:lang(fi) /* Finnish */,
#contenteditable-root.yt-formatted-string:lang(da) /* Danish */,
#contenteditable-root.yt-formatted-string:lang(no) /* Norwegian */,
#contenteditable-root.yt-formatted-string:lang(pl) /* Polish */,
#contenteditable-root.yt-formatted-string:lang(cs) /* Czech */,
#contenteditable-root.yt-formatted-string:lang(sk) /* Slovak */,
#contenteditable-root.yt-formatted-string:lang(hu) /* Hungarian */,
#contenteditable-root.yt-formatted-string:lang(tr) /* Turkish */,
#contenteditable-root.yt-formatted-string:lang(el) /* Greek */,
#contenteditable-root.yt-formatted-string:lang(id) /* Indonesian */,
#contenteditable-root.yt-formatted-string:lang(ms) /* Malay */,
#contenteditable-root.yt-formatted-string:lang(th) /* Thai */,
#contenteditable-root.yt-formatted-string:lang(vi) /* Vietnamese */
{
direction: ltr;
}
/* Right-to-Left (RTL) Languages */
#contenteditable-root.yt-formatted-string:lang(ar) /* Arabic */,
#contenteditable-root.yt-formatted-string:lang(fa) /* Persian */,
#contenteditable-root.yt-formatted-string:lang(ur) /* Urdu */,
#contenteditable-root.yt-formatted-string:lang(dv) /* Divehi */
{
direction: rtl;
}
` : '';
style.textContent = `
${cssText01_FIX_RTL_ISSUE}
`.trim();
if (nonce) style.setAttribute('nonce', nonce);
document.head.appendChild(style);
}
/**
*
* @param {DisplayNameResultObject} resultInfo
* @param {string} channelId
*/
const cacheHandleToChannel = (resultInfo, channelId) => {
const { vanityChannelUrl, ownerUrls } = resultInfo;
let handleText = urlToHandle(vanityChannelUrl || '');
if (handleText) {
// match = true;
} else if ((ownerUrls || 0).length >= 1) {
for (const ownerUrl of ownerUrls) {
handleText = urlToHandle(ownerUrl || '');
if (handleText) {
// match = true;
break;
}
}
}
if (handleText) {
const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
if (asyncValue instanceof AsyncValue) {
asyncValue.setValue(channelId);
}
handleToChannelId.set(handleText, channelId);
}
}
/**
*
* @param {string} channelId
* @param {Function} onDownloaded
* @param {Function} onResulted
* @param {Function} onError
*/
const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
let signal = timeoutSignal(4000);
const requestBody = {
"context": {
"client": {
"visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
"clientName": "MWEB", // "WEB", "MWEB"
"clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
"originalUrl": `https://m.youtube.com/channel/${channelId}`,
"playerType": "UNIPLAYER",
"platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
"clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
"acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"mainAppWebInfo": {
"graftUrl": `/channel/${channelId}`,
"webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
"isWebNativeShareAvailable": true
}
},
"user": {
"lockedSafetyMode": false
},
"request": {
"useSsl": true,
"internalExperimentFlags": [],
"consistencyTokenJars": []
}
},
"browseId": `${channelId}`
};
if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
Object.assign(requestBody.context.client, {
"hl": cfg.HL,
"gl": cfg.GL,
});
}
fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
"method": "POST",
"mode": "same-origin",
"credentials": "omit",
referrerPolicy: "no-referrer",
cache: "default", // no effect on POST request
// cache: "force-cache",
redirect: "error", // there shall be no redirection in this API request
integrity: "",
keepalive: false,
signal,
"headers": {
"Content-Type": "application/json", // content type of the body data in POST request
"Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
// X-Youtube-Bootstrap-Logged-In: false,
// X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
// X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
"Accept": "application/json",
},
"body": JSON.stringify(requestBody)
})).then(res => {
signal && signal.clearTimeout && signal.clearTimeout();
signal = null;
onDownloaded();
onDownloaded = null;
return res.json();
}).then(resJson => {
const resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
const title = resultInfo ? resultInfo.title : null;
if (title || title === '') {
resultInfo.title = '';
resultInfo.langTitle = title;
if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
let matched = false;
const ownerProfileUrlLowerCase = cfg.ownerProfileUrl.toLowerCase();
if (ownerProfileUrlLowerCase.endsWith(`/channel/${channelId.toLowerCase()}`)) matched = true;
else {
for (const ownerUrl of resultInfo.ownerUrls) {
if (ownerUrl.toLowerCase().endsWith(ownerProfileUrlLowerCase)) {
matched = true;
break;
}
}
}
if (matched) {
resultInfo.title = cfg.ownerChannelName;
}
}
}
onResulted(resultInfo);
onResulted = null;
}).catch(onError);
};
/**
*
* @param {string} channelId
* @param {Function} onDownloaded
* @param {Function} onResulted
* @param {Function} onError
*/
let fetchRSSFailed = false;
const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
let signal = timeoutSignal(4000);
fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
// YouTube RSS Response - public, max-age=900
"method": "GET",
"mode": "same-origin",
"credentials": "omit",
referrerPolicy: "no-referrer",
cache: "default",
// cache: "no-cache",
redirect: "error", // there shall be no redirection in this API request
integrity: "",
keepalive: false,
signal,
"headers": {
"Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
// refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
// seems YouTube RSS Feeds server insists its own Cache-Control.
// "Content-Type": "text/xml; charset=UTF-8",
"Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
// X-Youtube-Bootstrap-Logged-In: false,
// X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
// X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
"Accept": "text/xml",
}
}).then(res => {
signal && signal.clearTimeout && signal.clearTimeout();
signal = null;
if (res.ok === true && res.redirected === false && res.status === 200 && res.type === "basic") {
onDownloaded();
onDownloaded = null;
return res.text();
}
return null;
}).then(resText => {
if (resText && typeof resText === 'string' && resText.includes('<feed') && !resText.includes('<!DOCTYPE')) {
} else {
if (onDownloaded) {
onDownloaded();
onDownloaded = null;
}
onResulted(-1);
return;
}
// console.log(124, , resText)
let eIdx = resText.indexOf('<entry>');
let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
// simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
// standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
// long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
// special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
let name, uri, mt;
// ===============================================================
/* removed in 2023.06.30 */
// ===============================================================
const wIdx1 = mText.indexOf('<author>');
const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
if (wIdx1 > 0 && wIdx2 > 0) {
let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
const template = document.createElement('template');
template.innerHTML = createHTML(qText);
/** @type {HTMLElement | null} */
let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
const nodeName = authorChild.nodeName;
if (nodeName === 'NAME') name = authorChild.textContent;
else if (nodeName === 'URI') {
uri = authorChild.textContent;
mt = obtainChannelId(uri);
}
}
template.innerHTML = createHTML('');
}
if (!name && !uri) {
// fallback
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(mText, "text/xml");
// const author = xmlDoc.querySelector("author");
// https://extendsclass.com/xpath-tester.html
const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
let authorChild;
while ((authorChild = authorChilds.iterateNext()) !== null) {
if (authorChild.nodeName === 'name') name = authorChild.textContent;
else if (authorChild.nodeName === 'uri') {
uri = authorChild.textContent;
mt = obtainChannelId(uri);
}
}
try {
xmlDoc.firstChild.remove();
} catch (e) { }
}
let res = null;
if ((name || name === '') && uri && mt && mt === channelId) {
const handleObj = channelIdToHandle.get(mt);
if (handleObj) {
const handleText = handleObj.handleText;
if (handleText === name) channelIdToHandle.delete(mt);
else {
handleObj.justPossible = false; // ignore @handle checking
res = {
"title": name,
"externalId": mt,
"ownerUrls": [
`http://www.youtube.com/${handleText}`
],
"channelUrl": uri,
"vanityChannelUrl": `http://www.youtube.com/${handleText}`
};
if (USE_LANG_SPECIFIC_NAME) {
const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
}
}
}
}
onResulted(res);
onResulted = null;
// let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
// onResulted(resultInfo);
}).catch(onError);
}
sessionStorage.setItem('js-yt-usernames', '');
let isFirstStackNewRequestSuccess = true;
/**
*
* @param {string} channelId
*/
function stackNewRequest(channelId) {
mutex.add(lockResolve => {
let bResult = displayNameResStore.get(channelId);
if (!(bResult instanceof AsyncValue)) {
// resolved or removed
lockResolve(); lockResolve = null;
return;
}
let setResult = (result) => {
setResult = null;