Restore YouTube Username from Handle to Custom

将 YouTube 用户名从 Handle 恢复为自定义名称

当前为 2024-12-24 提交的版本,查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name Restore YouTube Username from Handle to Custom
  28. // @namespace http://tampermonkey.net/
  29. // @version 0.13.8
  30. // @license MIT License
  31.  
  32. // @author CY Fung
  33. // @match https://www.youtube.com/*
  34. // @match https://m.youtube.com/*
  35. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  36. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/general-icon.png
  37. // @supportURL https://github.com/cyfung1031/userscript-supports
  38. // @run-at document-start
  39. // @grant none
  40. // @unwrap
  41. // @allFrames true
  42. // @inject-into page
  43.  
  44. // @compatible firefox Violentmonkey
  45. // @compatible firefox Tampermonkey
  46. // @compatible firefox Firemonkey
  47. // @compatible chrome Violentmonkey
  48. // @compatible chrome Tampermonkey
  49. // @compatible opera Violentmonkey
  50. // @compatible opera Tampermonkey
  51. // @compatible safari Stay
  52. // @compatible edge Violentmonkey
  53. // @compatible edge Tampermonkey
  54. // @compatible brave Violentmonkey
  55. // @compatible brave Tampermonkey
  56.  
  57. // @description To restore YouTube Username to the traditional custom name
  58. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  59. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  60. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  61.  
  62. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  63. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  64. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  65. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  66. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  67. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  68. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  69. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  70. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  71. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  72. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  73. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  74. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  75. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  76. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  77. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  78. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  79. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  80. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  81. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  82. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  83. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  84. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  85. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  86. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  87. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  88. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  89. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  90. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  91. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  92. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  93. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  94. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  95. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  96. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  97. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  98. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  99. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  100. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  101. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  102. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  103. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  104. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  105. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  106. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  107. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  108. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  109. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  110. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  111. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  112. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  113. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  114. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  115. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  116. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  117. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  118. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  119. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  120. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  121. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  122. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  123. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  124. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  125. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  126. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  127. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  128. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  129. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  130. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  131.  
  132. // ==/UserScript==
  133.  
  134. !window.TTP && (()=>{
  135. // credit to Benjamin Philipp
  136. // original source: https://greasyfork.org/en/scripts/433051-trusted-types-helper
  137.  
  138. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  139.  
  140. const overwrite_default = false; // If a default policy already exists, it might be best not to overwrite it, but to try and set a custom policy and use it to manually generate trusted types. Try at your own risk
  141. const prefix = `TTP`;
  142. var passThroughFunc = function(string, sink){
  143. return string; // Anything passing through this function will be returned without change
  144. }
  145. var TTPName = "passthrough";
  146. var TTP_default, TTP = {createHTML: passThroughFunc, createScript: passThroughFunc, createScriptURL: passThroughFunc}; // We can use TTP.createHTML for all our assignments even if we don't need or even have Trusted Types; this should make fallbacks and polyfills easy
  147. var needsTrustedHTML = false;
  148. function doit(){
  149. try{
  150. if(typeof window.isSecureContext !== 'undefined' && window.isSecureContext){
  151. if (window.trustedTypes && window.trustedTypes.createPolicy){
  152. needsTrustedHTML = true;
  153. if(trustedTypes.defaultPolicy){
  154. log("TT Default Policy exists");
  155. if(overwrite_default)
  156. TTP = window.trustedTypes.createPolicy("default", TTP);
  157. else
  158. TTP = window.trustedTypes.createPolicy(TTPName, TTP); // Is the default policy permissive enough? If it already exists, best not to overwrite it
  159. TTP_default = trustedTypes.defaultPolicy;
  160.  
  161. log("Created custom passthrough policy, in case the default policy is too restrictive: Use Policy '" + TTPName + "' in var 'TTP':", TTP);
  162. }
  163. else{
  164. TTP_default = TTP = window.trustedTypes.createPolicy("default", TTP);
  165. }
  166. log("Trusted-Type Policies: TTP:", TTP, "TTP_default:", TTP_default);
  167. }
  168. }
  169. }catch(e){
  170. log(e);
  171. }
  172. }
  173.  
  174. function log(...args){
  175. if("undefined" != typeof(prefix) && !!prefix)
  176. args = [prefix + ":", ...args];
  177. if("undefined" != typeof(debugging) && !!debugging)
  178. args = [...args, new Error().stack.replace(/^\s*(Error|Stack trace):?\n/gi, "").replace(/^([^\n]*\n)/, "\n")];
  179. console.log(...args);
  180. }
  181.  
  182. doit();
  183.  
  184. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  185.  
  186. window.TTP = TTP;
  187.  
  188. })();
  189.  
  190. const NUM_CHANNEL_ID_MIN_LEN_old1 = 4; // 4 = @abc
  191. const NUM_CHANNEL_ID_MIN_LEN_1 = 2; // 4 = @abc -> 2 = @a
  192. const NUM_CHANNEL_ID_MIN_LEN_2 = 3; // 5 = /@abc -> 3 = /@a
  193.  
  194.  
  195. function createHTML(s) {
  196. if (typeof TTP !== 'undefined' && typeof TTP.createHTML === 'function') return TTP.createHTML(s);
  197. return s;
  198. }
  199.  
  200. let trustHTMLErr = null;
  201. try {
  202. document.createElement('div').innerHTML = createHTML('1');
  203. } catch (e) {
  204. trustHTMLErr = e;
  205. }
  206.  
  207. if (trustHTMLErr) {
  208. console.log(`trustHTMLErr`, trustHTMLErr);
  209. trustHTMLErr(); // exit userscript
  210. }
  211.  
  212.  
  213. // -----------------------------------------------------------------------------------------------------------------------------
  214.  
  215. /* jshint esversion:8 */
  216.  
  217. /**
  218. @typedef {string} HandleText
  219. * \@[-_a-zA-Z0-9.]{3,30} (before May 2024)
  220. * See isDisplayAsHandle
  221. */
  222.  
  223. /**
  224. @typedef {string} ChannelId
  225. * UC[-_a-zA-Z0-9+=.]{22}
  226. * https://support.google.com/youtube/answer/6070344?hl=en
  227. * The channel ID is the 24 character alphanumeric string that starts with 'UC' in the channel URL.
  228. */
  229.  
  230. /**
  231. @typedef {string} DisplayName
  232. * Display Name
  233. */
  234.  
  235. /**
  236. @typedef DisplayNameResultObject
  237. @type {Object}
  238. @property {DisplayName} title
  239. @property {DisplayName} langTitle
  240. @property {ChannelId?} externalId
  241. @property {string[]} ownerUrls
  242. @property {string} channelUrl
  243. @property {string} vanityChannelUrl
  244. @property {boolean|undefined} verified123
  245. */
  246.  
  247. /**
  248. @typedef ChannelIdToHandleResult
  249. @type {Object}
  250. @property {HandleText} handleText
  251. @property {boolean} justPossible
  252. */
  253.  
  254. (function (__CONTEXT__) {
  255. 'use strict';
  256.  
  257. // const JUST_REMOVE_AT_FOR_EXPANDED_LANG = true;
  258.  
  259. const USE_RSS_FETCHER = true; // might 404
  260. const USE_TIMEOUT_SIGNAL = false;
  261. const USE_CHANNEL_META = true;
  262. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  263. const USE_LANG_SPECIFIC_NAME = true;
  264. const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
  265. const FIX_RTL_ISSUE = true;
  266.  
  267. const IGNORE_NO_NAME = false;
  268.  
  269. /** @type {globalThis.PromiseConstructor} */
  270. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  271.  
  272. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  273.  
  274. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  275. let controller = new AbortController();
  276. const r = controller.signal;
  277. let cid = setTimeout(() => {
  278. if (cid >= 1) {
  279. cid = 0;
  280. controller && controller.abort();
  281. controller = null;
  282. }
  283. }, timeout);
  284. r.clearTimeout = () => {
  285. if (cid >= 1) {
  286. clearTimeout(cid);
  287. cid = 0;
  288. }
  289. }
  290. return r;
  291. } : () => { };
  292.  
  293. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  294.  
  295. const fxOperator = (proto, propertyName) => {
  296. let propertyDescriptorGetter = null;
  297. try {
  298. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  299. // https://github.com/cyfung1031/userscript-supports/issues/9
  300. // .parentNode becomes DocumentFragment
  301. /**
  302. *
  303. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  304. *
  305. * e.g. ytd-comment-renderer#comment > div#body
  306. *
  307. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  308. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  309. *
  310. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  311. *
  312. * Alternative way: ytCustomElement.$.xxxxxxx
  313. *
  314. */
  315. } catch (e) { }
  316. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  317. };
  318.  
  319. const fxAPI = (proto, propertyName) => {
  320. const methodFunc = proto[propertyName];
  321. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  322. };
  323.  
  324. /** @type { (node: Node)=>Node | null } */
  325. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  326. /** @type { (node: Node)=>Node | null } */
  327. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  328. /** @type { (node: Node)=>Node | null } */
  329. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  330.  
  331. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  332. const elementQS = fxAPI(Element.prototype, 'querySelector');
  333. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  334. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  335.  
  336. /*
  337.  
  338.  
  339. init
  340.  
  341. initialdata
  342. state-progress
  343. state-responsereceived
  344. player-autonav-pause
  345. state-change
  346. state-navigateend
  347. player-initialized
  348. renderer-module-load-start
  349. video-data-change
  350. player-state-change
  351. updateui
  352. renderer-module-load-end -> channel owner DOM available
  353. player-autonav-pause
  354. updateui
  355. renderer-module-load-start
  356. updateui
  357. renderer-module-load-end
  358.  
  359.  
  360. playing
  361.  
  362. h5player.video-progress
  363. h5player.video-progress
  364. h5player.video-progress
  365. h5player.video-progress
  366. ...
  367.  
  368.  
  369.  
  370.  
  371. navigate new video
  372.  
  373. state-navigatestart
  374. state-change => channel owener DOM vanished
  375. state-progress
  376. ...
  377. h5player.player-state-change
  378. h5player.video-data-change
  379. h5player.player-state-change
  380. h5player.muted-autoplay-change
  381. h5player.volume-change
  382. h5player.video-data-change
  383. h5player.volume-change
  384. ...
  385.  
  386. state-progress
  387. ...
  388.  
  389. state-progress => channel owner DOM appear [just before state-responsereceived]
  390. state-responsereceived
  391.  
  392. video-data-change
  393. state-change
  394. state-navigateend
  395.  
  396.  
  397.  
  398.  
  399. UX interaction
  400.  
  401. user-activity
  402. player-autonav-pause
  403.  
  404.  
  405.  
  406.  
  407.  
  408. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  409.  
  410. EventTarget.prototype.dispatchEvent = function (ev) {
  411. if (ev instanceof Event) {
  412. if (ev.type === 'video-progress') { } else {
  413. console.log(ev.type, this, ev.target)
  414. if (ev.target === null) {
  415. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  416. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  417. }
  418. }
  419. }
  420. return this.uhfsE.apply(this, arguments);
  421. }
  422.  
  423.  
  424.  
  425. */
  426.  
  427. const isMobile = location.hostname === 'm.youtube.com';
  428.  
  429. if (!isMobile && typeof AbortSignal !== 'undefined') {
  430. document.addEventListener('yt-action', () => {
  431. try {
  432. yt.config_.EXPERIMENT_FLAGS.enable_profile_cards_on_comments = true;
  433. } catch (e) { }
  434. }, { capture: true, passive: true, once: true })
  435. }
  436.  
  437.  
  438. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  439.  
  440. const { retrieveCE } = isMobile ? (() => {
  441.  
  442. const retrieveCE = () => {
  443. console.warn('retrieveCE is not supported');
  444. }
  445. return { retrieveCE };
  446.  
  447. })() : (() => {
  448.  
  449. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  450.  
  451. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  452. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  453. if (typeof customElements === 'undefined') {
  454. if (!('__CE_registry' in document)) {
  455. // https://github.com/webcomponents/polyfills/
  456. Object.defineProperty(document, '__CE_registry', {
  457. get() {
  458. // return undefined
  459. },
  460. set(nv) {
  461. if (typeof nv == 'object') {
  462. delete this.__CE_registry;
  463. this.__CE_registry = nv;
  464. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  465. }
  466. return true;
  467. },
  468. enumerable: false,
  469. configurable: true
  470. })
  471. }
  472. let eventHandler = (evt) => {
  473. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  474. const f = callback;
  475. callback = null;
  476. eventHandler = null;
  477. f();
  478. };
  479. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  480. } else {
  481. callback();
  482. }
  483. });
  484.  
  485. const retrieveCE = async (nodeName) => {
  486. try {
  487. isCustomElementsProvided || (await promiseForCustomYtElementsReady);
  488. await customElements.whenDefined(nodeName);
  489. const dummy = document.querySelector(nodeName) || document.createElement(nodeName);
  490. const cProto = insp(dummy).constructor.prototype;
  491. return cProto;
  492. } catch (e) {
  493. console.warn(e);
  494. }
  495. }
  496.  
  497. return { retrieveCE };
  498.  
  499. })();
  500.  
  501. const cfg = {};
  502. class Mutex {
  503.  
  504. constructor() {
  505. this.p = Promise.resolve()
  506. }
  507.  
  508. /**
  509. * @param {(lockResolve: () => void)} f
  510. */
  511. lockWith(f) {
  512. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  513. }
  514.  
  515. }
  516.  
  517. class OrderedMutex extends Mutex {
  518. constructor() {
  519. super();
  520. this.nextIndex = 0;
  521. this.arr = [];
  522. this.lockFunc = resolve => {
  523. if (this.arr.length >= 1) {
  524. let f = this.arr[0];
  525. if (typeof f === 'function') {
  526. this.arr.shift();
  527. if (this.nextIndex > 0) this.nextIndex--;
  528. f(resolve);
  529. return;
  530. } else {
  531. // reset if unknown error
  532. this.arr.length = 0;
  533. this.nextIndex = 0;
  534. }
  535. }
  536. resolve();
  537. };
  538. }
  539. /**
  540. * @param {(lockResolve: () => void)} f
  541. */
  542. add(f) {
  543. if (this.nextIndex === this.arr.length) {
  544. this.arr.push(f); this.nextIndex++;
  545. } else {
  546. this.arr.splice(this.nextIndex++, 0, f);
  547. }
  548. this.lockWith(this.lockFunc);
  549. }
  550. }
  551. // usage: run network request one by one
  552. const mutex = new OrderedMutex();
  553.  
  554. const createPipeline = () => {
  555. let pipelineMutex = Promise.resolve();
  556. const pipelineExecution = fn => {
  557. return new Promise((resolve, reject) => {
  558. pipelineMutex = pipelineMutex.then(async () => {
  559. let res;
  560. try {
  561. res = await fn();
  562. } catch (e) {
  563. console.log('error_F1', e);
  564. reject(e);
  565. }
  566. resolve(res);
  567. }).catch(console.warn);
  568. });
  569. };
  570. return pipelineExecution;
  571. };
  572.  
  573. /**
  574. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  575. * @template T */
  576.  
  577. /**
  578. * usage: cache the network result per web application instance.
  579. * @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  580. const displayNameResStore = new Map();
  581.  
  582. /**
  583. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  584. * @type {WeakMap<Function, Function>} */
  585. const dataChangedFuncStore = new WeakMap();
  586.  
  587. /**
  588. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  589. * @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
  590. const handleToChannelId = new Map();
  591.  
  592. /**
  593. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  594. * @type {Map<ChannelId, ChannelIdToHandleResult>} */
  595. const channelIdToHandle = new Map();
  596.  
  597. /**
  598. * usage: replace handle to lang-specific display name
  599. * @type {Map<HandleText, DisplayName>} */
  600. const langPreferredDisplayNameMap = new Map();
  601.  
  602. /**
  603. * AsyncValue
  604. * @class
  605. * @template T
  606. */
  607. class AsyncValue {
  608. constructor() {
  609. /** @type {T | null} */
  610. this.__value__ = null;
  611. /** @type {((value: any)=>void) | null} */
  612. this.__resolve__ = null;
  613. this.__promise__ = new Promise(resolve => {
  614. this.__resolve__ = resolve;
  615. });
  616. }
  617. /**
  618. *
  619. * @param {T} value
  620. */
  621. setValue(value) {
  622. const promise = this.__promise__;
  623. if (promise === null) throw 'Value has already been set.';
  624. this.__value__ = value;
  625. this.__promise__ = null;
  626. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  627. }
  628. /**
  629. *
  630. * @returns {Promise<T>}
  631. */
  632. async getValue() {
  633. const promise = this.__promise__;
  634. if (promise === null) return this.__value__;
  635. await promise; // promise become null
  636. this.__promise__ = null; // just in case
  637. this.__resolve__ = null;
  638. return this.__value__;
  639. }
  640. }
  641.  
  642. let isCSSAdded = false;
  643. const addCSSRulesIfRequired = () => {
  644. if (isCSSAdded) return;
  645. isCSSAdded = true;
  646. const style = document.createElement('style')
  647. let nonce = document.querySelector('head style[nonce]');
  648. nonce = nonce ? nonce.getAttribute('nonce') : null;
  649.  
  650. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (LTR, when mixed with LTR languages) */
  651. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (pure) */
  652.  
  653. const cssText01_FIX_RTL_ISSUE = FIX_RTL_ISSUE ? `
  654.  
  655. /* Left-to-Right (LTR) Languages */
  656. #contenteditable-root.yt-formatted-string:lang(en) /* English */,
  657. #contenteditable-root.yt-formatted-string:lang(es) /* Spanish */,
  658. #contenteditable-root.yt-formatted-string:lang(fr) /* French */,
  659. #contenteditable-root.yt-formatted-string:lang(de) /* German */,
  660. #contenteditable-root.yt-formatted-string:lang(it) /* Italian */,
  661. #contenteditable-root.yt-formatted-string:lang(pt) /* Portuguese */,
  662. #contenteditable-root.yt-formatted-string:lang(ru) /* Russian */,
  663. #contenteditable-root.yt-formatted-string:lang(zh) /* Chinese */,
  664. #contenteditable-root.yt-formatted-string:lang(ja) /* Japanese */,
  665. #contenteditable-root.yt-formatted-string:lang(ko) /* Korean */,
  666. #contenteditable-root.yt-formatted-string:lang(nl) /* Dutch */,
  667. #contenteditable-root.yt-formatted-string:lang(sv) /* Swedish */,
  668. #contenteditable-root.yt-formatted-string:lang(fi) /* Finnish */,
  669. #contenteditable-root.yt-formatted-string:lang(da) /* Danish */,
  670. #contenteditable-root.yt-formatted-string:lang(no) /* Norwegian */,
  671. #contenteditable-root.yt-formatted-string:lang(pl) /* Polish */,
  672. #contenteditable-root.yt-formatted-string:lang(cs) /* Czech */,
  673. #contenteditable-root.yt-formatted-string:lang(sk) /* Slovak */,
  674. #contenteditable-root.yt-formatted-string:lang(hu) /* Hungarian */,
  675. #contenteditable-root.yt-formatted-string:lang(tr) /* Turkish */,
  676. #contenteditable-root.yt-formatted-string:lang(el) /* Greek */,
  677. #contenteditable-root.yt-formatted-string:lang(id) /* Indonesian */,
  678. #contenteditable-root.yt-formatted-string:lang(ms) /* Malay */,
  679. #contenteditable-root.yt-formatted-string:lang(th) /* Thai */,
  680. #contenteditable-root.yt-formatted-string:lang(vi) /* Vietnamese */
  681. {
  682. direction: ltr;
  683. }
  684.  
  685. /* Right-to-Left (RTL) Languages */
  686. #contenteditable-root.yt-formatted-string:lang(ar) /* Arabic */,
  687. #contenteditable-root.yt-formatted-string:lang(fa) /* Persian */,
  688. #contenteditable-root.yt-formatted-string:lang(ur) /* Urdu */,
  689. #contenteditable-root.yt-formatted-string:lang(dv) /* Divehi */
  690. {
  691. direction: rtl;
  692. }
  693.  
  694. ` : '';
  695. style.textContent = `
  696. ${cssText01_FIX_RTL_ISSUE}
  697. `.trim();
  698. if (nonce) style.setAttribute('nonce', nonce);
  699. document.head.appendChild(style);
  700. }
  701.  
  702. /**
  703. *
  704. * @param {DisplayNameResultObject} resultInfo
  705. * @param {string} channelId
  706. */
  707. const cacheHandleToChannel = (resultInfo, channelId) => {
  708.  
  709. const { vanityChannelUrl, ownerUrls } = resultInfo;
  710.  
  711. let handleText = urlToHandle(vanityChannelUrl || '');
  712.  
  713. if (handleText) {
  714. // match = true;
  715. } else if ((ownerUrls || 0).length >= 1) {
  716. for (const ownerUrl of ownerUrls) {
  717. handleText = urlToHandle(ownerUrl || '');
  718.  
  719. if (handleText) {
  720. // match = true;
  721. break;
  722. }
  723. }
  724. }
  725. if (handleText) {
  726.  
  727. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  728. if (asyncValue instanceof AsyncValue) {
  729. asyncValue.setValue(channelId);
  730. }
  731. handleToChannelId.set(handleText, channelId);
  732. }
  733.  
  734.  
  735. }
  736.  
  737. /**
  738. *
  739. * @param {string} channelId
  740. * @param {Function} onDownloaded
  741. * @param {Function} onResulted
  742. * @param {Function} onError
  743. */
  744. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  745.  
  746. let signal = timeoutSignal(4000);
  747.  
  748. const requestBody = {
  749. "context": {
  750. "client": {
  751. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  752. "clientName": "MWEB", // "WEB", "MWEB"
  753. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  754. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  755. "playerType": "UNIPLAYER",
  756. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  757. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  758. "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",
  759. "mainAppWebInfo": {
  760. "graftUrl": `/channel/${channelId}`,
  761. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  762. "isWebNativeShareAvailable": true
  763. }
  764. },
  765. "user": {
  766. "lockedSafetyMode": false
  767. },
  768. "request": {
  769. "useSsl": true,
  770. "internalExperimentFlags": [],
  771. "consistencyTokenJars": []
  772. }
  773. },
  774. "browseId": `${channelId}`
  775. };
  776.  
  777. if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
  778. Object.assign(requestBody.context.client, {
  779. "hl": cfg.HL,
  780. "gl": cfg.GL,
  781. });
  782. }
  783.  
  784. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  785. "method": "POST",
  786. "mode": "same-origin",
  787. "credentials": "omit",
  788.  
  789. referrerPolicy: "no-referrer",
  790. cache: "default", // no effect on POST request
  791. // cache: "force-cache",
  792. redirect: "error", // there shall be no redirection in this API request
  793. integrity: "",
  794. keepalive: false,
  795. signal,
  796.  
  797. "headers": {
  798. "Content-Type": "application/json", // content type of the body data in POST request
  799. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  800. // X-Youtube-Bootstrap-Logged-In: false,
  801. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  802. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  803.  
  804. "Accept": "application/json",
  805. },
  806. "body": JSON.stringify(requestBody)
  807. })).then(res => {
  808. signal && signal.clearTimeout && signal.clearTimeout();
  809. signal = null;
  810. onDownloaded();
  811. onDownloaded = null;
  812. return res.json();
  813. }).then(resJson => {
  814. const resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  815. const title = resultInfo ? resultInfo.title : null;
  816. if (title || title === '') {
  817.  
  818. resultInfo.title = '';
  819. resultInfo.langTitle = title;
  820.  
  821. if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
  822. let matched = false;
  823.  
  824. const ownerProfileUrlLowerCase = cfg.ownerProfileUrl.toLowerCase();
  825. if (ownerProfileUrlLowerCase.endsWith(`/channel/${channelId.toLowerCase()}`)) matched = true;
  826. else {
  827.  
  828. for (const ownerUrl of resultInfo.ownerUrls) {
  829. if (ownerUrl.toLowerCase().endsWith(ownerProfileUrlLowerCase)) {
  830. matched = true;
  831. break;
  832. }
  833. }
  834.  
  835. }
  836.  
  837. if (matched) {
  838. resultInfo.title = cfg.ownerChannelName;
  839. }
  840. }
  841.  
  842. }
  843.  
  844. onResulted(resultInfo);
  845. onResulted = null;
  846. }).catch(onError);
  847.  
  848. };
  849.  
  850. /**
  851. *
  852. * @param {string} channelId
  853. * @param {Function} onDownloaded
  854. * @param {Function} onResulted
  855. * @param {Function} onError
  856. */
  857. let fetchRSSFailed = false;
  858. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  859.  
  860. let signal = timeoutSignal(4000);
  861. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  862. // YouTube RSS Response - public, max-age=900
  863.  
  864. "method": "GET",
  865. "mode": "same-origin",
  866. "credentials": "omit",
  867.  
  868. referrerPolicy: "no-referrer",
  869. cache: "default",
  870. // cache: "no-cache",
  871. redirect: "error", // there shall be no redirection in this API request
  872. integrity: "",
  873. keepalive: false,
  874. signal,
  875.  
  876. "headers": {
  877. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  878. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  879. // seems YouTube RSS Feeds server insists its own Cache-Control.
  880.  
  881. // "Content-Type": "text/xml; charset=UTF-8",
  882. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  883. // X-Youtube-Bootstrap-Logged-In: false,
  884. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  885. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  886.  
  887. "Accept": "text/xml",
  888. }
  889. }).then(res => {
  890.  
  891. signal && signal.clearTimeout && signal.clearTimeout();
  892. signal = null;
  893.  
  894. if (res.ok === true && res.redirected === false && res.status === 200 && res.type === "basic") {
  895.  
  896. onDownloaded();
  897. onDownloaded = null;
  898. return res.text();
  899.  
  900. }
  901. return null;
  902.  
  903. }).then(resText => {
  904. if (resText && typeof resText === 'string' && resText.includes('<feed') && !resText.includes('<!DOCTYPE')) {
  905.  
  906. } else {
  907. if (onDownloaded) {
  908.  
  909. onDownloaded();
  910. onDownloaded = null;
  911. }
  912. onResulted(-1);
  913. return;
  914.  
  915. }
  916.  
  917.  
  918. // console.log(124, , resText)
  919. let eIdx = resText.indexOf('<entry>');
  920. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  921.  
  922. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  923. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  924. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  925. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  926.  
  927.  
  928. let name, uri, mt;
  929.  
  930. // ===============================================================
  931.  
  932. /* removed in 2023.06.30 */
  933.  
  934.  
  935. // ===============================================================
  936.  
  937.  
  938. const wIdx1 = mText.indexOf('<author>');
  939. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  940.  
  941. if (wIdx1 > 0 && wIdx2 > 0) {
  942. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  943. const template = document.createElement('template');
  944. template.innerHTML = createHTML(qText);
  945. /** @type {HTMLElement | null} */
  946. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  947. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  948. const nodeName = authorChild.nodeName;
  949. if (nodeName === 'NAME') name = authorChild.textContent;
  950. else if (nodeName === 'URI') {
  951. uri = authorChild.textContent;
  952. mt = obtainChannelId(uri);
  953. }
  954. }
  955. template.innerHTML = createHTML('');
  956. }
  957.  
  958. if (!name && !uri) {
  959.  
  960. // fallback
  961.  
  962. const parser = new DOMParser();
  963. const xmlDoc = parser.parseFromString(mText, "text/xml");
  964.  
  965. // const author = xmlDoc.querySelector("author");
  966.  
  967. // https://extendsclass.com/xpath-tester.html
  968.  
  969. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  970.  
  971. let authorChild;
  972. while ((authorChild = authorChilds.iterateNext()) !== null) {
  973. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  974. else if (authorChild.nodeName === 'uri') {
  975. uri = authorChild.textContent;
  976. mt = obtainChannelId(uri);
  977. }
  978. }
  979.  
  980. try {
  981. xmlDoc.firstChild.remove();
  982. } catch (e) { }
  983.  
  984. }
  985.  
  986.  
  987.  
  988.  
  989. let res = null;
  990.  
  991. if ((name || name === '') && uri && mt && mt === channelId) {
  992.  
  993.  
  994. const handleObj = channelIdToHandle.get(mt);
  995.  
  996. if (handleObj) {
  997.  
  998. const handleText = handleObj.handleText;
  999.  
  1000. if (handleText === name) channelIdToHandle.delete(mt);
  1001. else {
  1002. handleObj.justPossible = false; // ignore @handle checking
  1003.  
  1004. res = {
  1005. "title": name,
  1006. "externalId": mt,
  1007. "ownerUrls": [
  1008. `http://www.youtube.com/${handleText}`
  1009. ],
  1010. "channelUrl": uri,
  1011. "vanityChannelUrl": `http://www.youtube.com/${handleText}`
  1012. };
  1013.  
  1014. if (USE_LANG_SPECIFIC_NAME) {
  1015. const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
  1016. if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
  1017. }
  1018.  
  1019. }
  1020. }
  1021. }
  1022.  
  1023. onResulted(res);
  1024. onResulted = null;
  1025.  
  1026. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  1027. // onResulted(resultInfo);
  1028. }).catch(onError);
  1029.  
  1030.  
  1031.  
  1032. }
  1033.  
  1034. sessionStorage.setItem('js-yt-usernames', '');
  1035. let isFirstStackNewRequestSuccess = true;
  1036. /**
  1037. *
  1038. * @param {string} channelId
  1039. */
  1040. function stackNewRequest(channelId) {
  1041.  
  1042. mutex.add(lockResolve => {
  1043.  
  1044. let bResult = displayNameResStore.get(channelId);
  1045. if (!(bResult instanceof AsyncValue)) {
  1046. // resolved or removed
  1047. lockResolve(); lockResolve = null;
  1048. return;
  1049. }
  1050.  
  1051. let setResult = (result) => {
  1052. setResult = null;
  1053. if (!result) {
  1054. bResult.fetchingState = 0;
  1055. bResult.setValue(null);
  1056. displayNameResStore.delete(channelId); // create another network response in the next request
  1057. } else {
  1058. bResult.fetchingState = 4;
  1059. bResult.setValue(result);
  1060. displayNameResStore.set(channelId, result); // update store result to resolved value
  1061. }
  1062. bResult = null;
  1063. }
  1064.  
  1065. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  1066. // request is already done. no need to stack any request
  1067. lockResolve(); lockResolve = null;
  1068. return;
  1069. }
  1070.  
  1071. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  1072. // element has already been removed
  1073. lockResolve(); lockResolve = null;
  1074. setResult(null);
  1075. return;
  1076. }
  1077.  
  1078. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  1079.  
  1080. bResult.fetchingState = 2;
  1081.  
  1082.  
  1083. const retry = () => {
  1084.  
  1085. fetchRSSFailed = true;
  1086.  
  1087. bResult.fetchingState = 2;
  1088.  
  1089. // Promise.resolve(channelId).then(stackNewRequest);
  1090. fetcherBrowseAPI(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  1091. }
  1092.  
  1093. const mobj = {
  1094. fetchOnDownload: () => {
  1095. bResult.fetchingState = 3;
  1096. },
  1097. fetchOnSuccess: resultInfo => {
  1098.  
  1099. if (resultInfo === -1) {
  1100. retry();
  1101. return;
  1102. }
  1103.  
  1104. lockResolve && lockResolve();
  1105. lockResolve = null;
  1106. // console.log(900)
  1107.  
  1108. if (!resultInfo) {
  1109. // invalid json format
  1110. setResult(null);
  1111. return;
  1112. }
  1113.  
  1114. const titleForDisplay = resultInfo.langTitle || resultInfo.title;
  1115. const handleObj = channelIdToHandle.get(channelId);
  1116. const handleId = handleObj ? handleObj.handleText : '';
  1117. if (IGNORE_NO_NAME && !titleForDisplay) {
  1118. if (handleId) {
  1119. resultInfo.langTitle = resultInfo.title = handleObj.handleText;
  1120. } else {
  1121. setResult(null);
  1122. return;
  1123. }
  1124. }
  1125.  
  1126. cacheHandleToChannel(resultInfo, channelId);
  1127.  
  1128. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  1129.  
  1130. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  1131.  
  1132. if (handleId) {
  1133. if (isFirstStackNewRequestSuccess) {
  1134. isFirstStackNewRequestSuccess = false;
  1135. sessionStorage.setItem('js-yt-usernames', `${handleId}\t${titleForDisplay}`);
  1136. } else {
  1137. let current = sessionStorage.getItem('js-yt-usernames') || '';
  1138. if (current.length > 900000) {
  1139. const na = current.split('\n');
  1140. const n3 = Math.floor(na.length / 3);
  1141. if (n3 > 2) {
  1142. const newText = na.slice(0, n3).concat(na.slice(na.length - n3)).join('\n');
  1143. if (newText.length < 720000) {
  1144. current = newText;
  1145. }
  1146. }
  1147. }
  1148. sessionStorage.setItem('js-yt-usernames', `${current}\n${handleId}\t${titleForDisplay}`);
  1149. }
  1150. }
  1151.  
  1152. setResult(displayNameRes);
  1153. },
  1154. fetchOnFail: e => {
  1155.  
  1156.  
  1157. console.warn(e);
  1158. if (mobj.fetcher === fetcherRSS) {
  1159. retry();
  1160.  
  1161. } else {
  1162.  
  1163. lockResolve && lockResolve();
  1164. lockResolve = null;
  1165. // console.warn(e);
  1166. setResult && setResult(null);
  1167. }
  1168. }
  1169. }
  1170.  
  1171.  
  1172. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  1173. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  1174. mobj.fetcher = USE_RSS_FETCHER && fetcherRSS && !fetchRSSFailed && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  1175. mobj.fetcher(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  1176.  
  1177. });
  1178.  
  1179. }
  1180.  
  1181. /**
  1182. *
  1183. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  1184. * @returns Example: _\@yr__kd_
  1185. */
  1186. function urlToHandle(url) {
  1187.  
  1188. if (typeof url !== 'string') return '';
  1189. let i = url.indexOf('.youtube.com/');
  1190. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  1191. else if (url.charAt(0) === '/') url = url.substring(1);
  1192. return isDisplayAsHandle(url) ? url : '';
  1193.  
  1194. }
  1195.  
  1196. /**
  1197. *
  1198. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  1199. * @returns {Promise<DisplayNameResultObject | null>}
  1200. */
  1201. async function getDisplayName(channelId) {
  1202.  
  1203. let cache = displayNameResStore.get(channelId);
  1204. let isStackNewRequest = false;
  1205.  
  1206. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  1207. let aResult;
  1208.  
  1209. if (cache instanceof AsyncValue) {
  1210. aResult = cache;
  1211. if (aResult.fetchingState >= 2) {
  1212. // aResult.fetchingState
  1213. // 2: network fetch started
  1214. // 3: network fetch ended
  1215. // isStackNewRequest = false;
  1216. } else {
  1217. // 0: invalid before
  1218. // 1: scheduled but not yet fetch
  1219. isStackNewRequest = true;
  1220. }
  1221. } else if (cache) {
  1222. // resolved result
  1223. return cache;
  1224. } else {
  1225. // else no cached value found
  1226. /** @type {AsyncValue<DisplayNameResultObject>} */
  1227. aResult = new AsyncValue();
  1228. displayNameResStore.set(channelId, aResult);
  1229. isStackNewRequest = true;
  1230. }
  1231.  
  1232. if (isStackNewRequest) {
  1233. aResult.fetchingState = 1;
  1234. stackNewRequest(channelId);
  1235. }
  1236. const result = await aResult.getValue();
  1237. return result;
  1238. }
  1239.  
  1240.  
  1241. /**
  1242. *
  1243. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  1244. * @returns
  1245. * * Outdated?
  1246. */
  1247. const obtainChannelId = (href) => {
  1248. const s = `/${href}`;
  1249. if (s.length >= 33) {
  1250. const m = /\/channel\/(UC[-_a-zA-Z0-9+=.]{22})(\/|$)/.exec(s);
  1251. return !m ? '' : (m[1] || '');
  1252. }
  1253. return '';
  1254. };
  1255.  
  1256. const isUCBrowserId = (browseId) => {
  1257. return typeof browseId === 'string' && browseId.length === 24 && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId);
  1258. }
  1259.  
  1260. const browseEndpointBaseUrlType = (browseEndpoint, displayText) => {
  1261. if (isDisplayAsHandle(displayText) && isUCBrowserId(browseEndpoint.browseId) && typeof browseEndpoint.canonicalBaseUrl === 'string') {
  1262. if (`/${displayText}` === browseEndpoint.canonicalBaseUrl) return 1 | 2;
  1263. if (`/channel/${browseEndpoint.browseId}` === browseEndpoint.canonicalBaseUrl) return 1 | 4;
  1264. if (browseEndpoint.canonicalBaseUrl.includes(`/${browseEndpoint.browseId}`)) return 1 | 8;
  1265. return 1;
  1266. }
  1267. return 0;
  1268. }
  1269.  
  1270. /**
  1271. *
  1272. * @param {Element} ytElm
  1273. */
  1274. const resetWhenDataChanged = (ths) => {
  1275. const cnt = insp(ths);
  1276. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1277. if (ytElm instanceof Element) {
  1278. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1279. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1280. if ((anchors || 0).length >= 1 && (insp(ytElm).data || 0).jkrgx !== 1) {
  1281. for (const anchor of anchors) {
  1282. anchor.removeAttribute('jkrgy');
  1283. }
  1284. }
  1285. }
  1286. }
  1287.  
  1288. /**
  1289. *
  1290. * @param {Element} ytElm
  1291. */
  1292. const resetWhenPropChanged = (ths) => {
  1293. const cnt = insp(ths);
  1294. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1295. if (ytElm instanceof Element) {
  1296. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1297. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1298. if ((anchors || 0).length >= 1 && ((insp(ytElm).commentEntity || 0).author || 0).jkrgx !== 1) {
  1299. for (const anchor of anchors) {
  1300. anchor.removeAttribute('jkrgy');
  1301. }
  1302. }
  1303. }
  1304. }
  1305.  
  1306. /**
  1307. *
  1308. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  1309. * @param {string} hrefAttribute Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ (old) 2024 Feb -> /@user-abc1234
  1310. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  1311. * @returns
  1312. */
  1313. const anchorIntegrityCheck = (anchor, hrefAttribute) => {
  1314.  
  1315. let currentHref = anchor.getAttribute('href');
  1316. if (currentHref === hrefAttribute) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  1317.  
  1318. return (currentHref + '/').indexOf(hrefAttribute + '/') >= 0;
  1319.  
  1320. };
  1321.  
  1322. /**
  1323. *
  1324. * @param {string} currentDisplayed
  1325. * @param {DisplayNameResultObject} fetchResult
  1326. * @returns
  1327. */
  1328. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  1329.  
  1330. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  1331.  
  1332. const currentDisplayTrimmed = currentDisplayed.trim(); // @IORIMATSUNAGA
  1333. const currentDisplayTrimmedLowerCase = currentDisplayTrimmed.toLowerCase(); // @iorimatsunaga
  1334. let match = false;
  1335. if (verified123) {
  1336. match = true;
  1337. } else if ((vanityChannelUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmedLowerCase}`)) {
  1338. match = true;
  1339. } else if ((ownerUrls || 0).length >= 1) {
  1340. for (const ownerUrl of ownerUrls) {
  1341. if ((ownerUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmed}`)) {
  1342. match = true;
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. if (match) {
  1348. return currentDisplayTrimmed;
  1349. }
  1350. return '';
  1351.  
  1352. };
  1353.  
  1354. /**
  1355. *
  1356. *
  1357.  
  1358. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  1359.  
  1360. - Is between 3-30 characters
  1361. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1362. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  1363. - Is not URL-like or phone number-like
  1364. - Is not already being used
  1365. - Follows YouTube's Community Guidelines
  1366.  
  1367. ### Handle automatically generated by YouTube
  1368. - `@user-XXXX`
  1369. - without dot (.)
  1370.  
  1371.  
  1372. ## Intl. Language Support
  1373. #### Since May~June 2024
  1374.  
  1375. - Before: Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1376.  
  1377. - After: Uses alphabet letters or numbers from one of our 75 supported languages
  1378. - Your handle can also include: underscores (_), hyphens (-), periods (.), Latin middle dots (·).
  1379. - Mixed scripts are only allowed in certain circumstances.
  1380. - Left-to-right scripts cannot be mixed with right-to-left scripts in a single handle except when numbers are added to the end of the handle.
  1381.  
  1382.  
  1383.  
  1384.  
  1385. *
  1386. * @param {string} text
  1387. * @returns
  1388. */
  1389. const isDisplayAsHandle = (text) => {
  1390. if (typeof text !== 'string') return false;
  1391. const n = text.length;
  1392. if (n <= NUM_CHANNEL_ID_MIN_LEN_old1) {
  1393. if (n < NUM_CHANNEL_ID_MIN_LEN_1) return false; // @
  1394. // @巡空 -> <1, 2>
  1395. // @abc -> <4, 0>
  1396. const textFullL = text.replace(/[\u20-\uFF]+/g, '').length;
  1397. const textHalfL = n - textFullL;
  1398. if (textHalfL < 1) return false;
  1399. if (textFullL === 0 && textHalfL < 4) return false;
  1400. }
  1401. if (text.indexOf('@') < 0) return false;
  1402. return exactHandleText(text.trim(), true);
  1403. };
  1404.  
  1405. const isValidMinSlashHandle = (text) => {
  1406. return text && typeof text === 'string' && text.length >= NUM_CHANNEL_ID_MIN_LEN_2 && text.startsWith('/@');
  1407. }
  1408.  
  1409.  
  1410. const languageMapR0 = [];
  1411.  
  1412. const languageMap = [
  1413. { range: [0x0041, 0x005A], langs: ['English', 'Afrikaans', 'Albanian', 'Bosnian', 'Catalan', 'Croatian', 'Czech', 'Danish', 'Dutch', 'Estonian', 'Filipino', 'Finnish', 'French', 'Galician', 'German', 'Hungarian', 'Icelandic', 'Indonesian', 'Italian', 'Latvian', 'Lithuanian', 'Macedonian', 'Malay', 'Norwegian', 'Polish', 'Portuguese', 'Romanian', 'Slovak', 'Slovenian', 'Spanish', 'Swedish', 'Swahili', 'Turkish', 'Zulu'] }, // Basic Latin (A-Z)
  1414. { range: [0x0061, 0x007A], langs: ['English', 'Afrikaans', 'Albanian', 'Bosnian', 'Catalan', 'Croatian', 'Czech', 'Danish', 'Dutch', 'Estonian', 'Filipino', 'Finnish', 'French', 'Galician', 'German', 'Hungarian', 'Icelandic', 'Indonesian', 'Italian', 'Latvian', 'Lithuanian', 'Macedonian', 'Malay', 'Norwegian', 'Polish', 'Portuguese', 'Romanian', 'Slovak', 'Slovenian', 'Spanish', 'Swedish', 'Swahili', 'Turkish', 'Zulu'] }, // Basic Latin (a-z)
  1415. { range: [0x00C0, 0x00FF], langs: ['French', 'Portuguese', 'Spanish', 'Afrikaans'] }, // Latin-1 Supplement
  1416. { range: [0x0100, 0x017F], langs: ['Latvian', 'Lithuanian', 'Polish', 'Czech', 'Slovak', 'Slovenian', 'Croatian', 'Bosnian', 'Serbian', 'Montenegrin'] }, // Latin Extended-A
  1417. { range: [0x0180, 0x024F], langs: ['African languages', 'Esperanto'] }, // Latin Extended-B
  1418. { range: [0x0370, 0x03FF], langs: ['Greek'] }, // Greek and Coptic
  1419. { range: [0x0400, 0x04FF], langs: ['Russian', 'Ukrainian', 'Bulgarian', 'Serbian', 'Macedonian', 'Belarusian', 'Kazakh', 'Kyrgyz', 'Uzbek'] }, // Cyrillic
  1420. { range: [0x0500, 0x052F], langs: ['Kazakh', 'Kyrgyz', 'Uzbek'] }, // Cyrillic Supplement
  1421. { range: [0x0530, 0x058F], langs: ['Armenian'] }, // Armenian
  1422. { range: [0x0590, 0x05FF], langs: ['Hebrew'] }, // Hebrew
  1423. { range: [0x0600, 0x06FF], langs: ['Arabic', 'Persian', 'Urdu'] }, // Arabic
  1424. { range: [0x0700, 0x074F], langs: ['Syriac'] }, // Syriac
  1425. { range: [0x0750, 0x077F], langs: ['Arabic Supplement'] }, // Arabic Supplement
  1426. { range: [0x0780, 0x07BF], langs: ['Thaana'] }, // Thaana
  1427. { range: [0x0900, 0x097F], langs: ['Hindi', 'Marathi', 'Sanskrit', 'Nepali'] }, // Devanagari
  1428. { range: [0x0980, 0x09FF], langs: ['Bengali', 'Assamese'] }, // Bengali
  1429. { range: [0x0A00, 0x0A7F], langs: ['Punjabi'] }, // Gurmukhi
  1430. { range: [0x0A80, 0x0AFF], langs: ['Gujarati'] }, // Gujarati
  1431. { range: [0x0B00, 0x0B7F], langs: ['Odia'] }, // Oriya
  1432. { range: [0x0B80, 0x0BFF], langs: ['Tamil'] }, // Tamil
  1433. { range: [0x0C00, 0x0C7F], langs: ['Telugu'] }, // Telugu
  1434. { range: [0x0C80, 0x0CFF], langs: ['Kannada'] }, // Kannada
  1435. { range: [0x0D00, 0x0D7F], langs: ['Malayalam'] }, // Malayalam
  1436. { range: [0x0D80, 0x0DFF], langs: ['Sinhala'] }, // Sinhala
  1437. { range: [0x0E00, 0x0E7F], langs: ['Thai'] }, // Thai
  1438. { range: [0x0E80, 0x0EFF], langs: ['Lao'] }, // Lao
  1439. { range: [0x0F00, 0x0FFF], langs: ['Tibetan'] }, // Tibetan
  1440. { range: [0x1000, 0x109F], langs: ['Burmese'] }, // Myanmar
  1441. { range: [0x10A0, 0x10FF], langs: ['Georgian'] }, // Georgian
  1442. { range: [0x1100, 0x11FF], langs: ['Korean'] }, // Hangul Jamo
  1443. { range: [0x1200, 0x137F], langs: ['Amharic', 'Tigrinya', 'Geez'] }, // Ethiopic
  1444. { range: [0x13A0, 0x13FF], langs: ['Cherokee'] }, // Cherokee
  1445. { range: [0x1400, 0x167F], langs: ['Canadian Aboriginal'] }, // Unified Canadian Aboriginal Syllabics
  1446. { range: [0x1680, 0x169F], langs: ['Ogham'] }, // Ogham
  1447. { range: [0x16A0, 0x16FF], langs: ['Runic'] }, // Runic
  1448. { range: [0x1700, 0x171F], langs: ['Tagalog'] }, // Tagalog
  1449. { range: [0x1720, 0x173F], langs: ['Hanunoo'] }, // Hanunoo
  1450. { range: [0x1740, 0x175F], langs: ['Buhid'] }, // Buhid
  1451. { range: [0x1760, 0x177F], langs: ['Tagbanwa'] }, // Tagbanwa
  1452. { range: [0x1780, 0x17FF], langs: ['Khmer'] }, // Khmer
  1453. { range: [0x1800, 0x18AF], langs: ['Mongolian'] }, // Mongolian
  1454. { range: [0x1E00, 0x1EFF], langs: ['Latin Extended Additional'] }, // Latin Extended Additional
  1455. { range: [0x1F00, 0x1FFF], langs: ['Greek Extended'] }, // Greek Extended
  1456. { range: [0x2000, 0x206F], langs: ['General Punctuation'] }, // General Punctuation
  1457. { range: [0x2070, 0x209F], langs: ['Superscripts and Subscripts'] }, // Superscripts and Subscripts
  1458. { range: [0x20A0, 0x20CF], langs: ['Currency Symbols'] }, // Currency Symbols
  1459. { range: [0x2100, 0x214F], langs: ['Letterlike Symbols'] }, // Letterlike Symbols
  1460. { range: [0x2150, 0x218F], langs: ['Number Forms'] }, // Number Forms
  1461. { range: [0x2190, 0x21FF], langs: ['Arrows'] }, // Arrows
  1462. { range: [0x2200, 0x22FF], langs: ['Mathematical Operators'] }, // Mathematical Operators
  1463. { range: [0x2300, 0x23FF], langs: ['Miscellaneous Technical'] }, // Miscellaneous Technical
  1464. { range: [0x2400, 0x243F], langs: ['Control Pictures'] }, // Control Pictures
  1465. { range: [0x2440, 0x245F], langs: ['Optical Character Recognition'] }, // Optical Character Recognition
  1466. { range: [0x2460, 0x24FF], langs: ['Enclosed Alphanumerics'] }, // Enclosed Alphanumerics
  1467. { range: [0x2500, 0x257F], langs: ['Box Drawing'] }, // Box Drawing
  1468. { range: [0x2580, 0x259F], langs: ['Block Elements'] }, // Block Elements
  1469. { range: [0x25A0, 0x25FF], langs: ['Geometric Shapes'] }, // Geometric Shapes
  1470. { range: [0x2600, 0x26FF], langs: ['Miscellaneous Symbols'] }, // Miscellaneous Symbols
  1471. { range: [0x2700, 0x27BF], langs: ['Dingbats'] }, // Dingbats
  1472.  
  1473. { range: [0x3000, 0x303F], langs: ['Chinese (Simplified)', 'Chinese (Traditional)', 'Japanese', 'Korean'] },
  1474.  
  1475. // { range: [0x3000, 0x303F], langs: ['CJK Symbols and Punctuation'] }, // CJK Symbols and Punctuation
  1476. { range: [0x3040, 0x309F], langs: ['Japanese'] }, // Hiragana
  1477. { range: [0x30A0, 0x30FF], langs: ['Japanese'] }, // Katakana
  1478. { range: [0x3100, 0x312F], langs: ['Bopomofo'] }, // Bopomofo
  1479. { range: [0x3130, 0x318F], langs: ['Korean'] }, // Hangul Compatibility Jamo
  1480. { range: [0x3190, 0x319F], langs: ['Kanbun'] }, // Kanbun
  1481. { range: [0x31A0, 0x31BF], langs: ['Bopomofo Extended'] }, // Bopomofo Extended
  1482. { range: [0x31F0, 0x31FF], langs: ['Katakana Phonetic Extensions'] }, // Katakana Phonetic Extensions
  1483. { range: [0x3200, 0x32FF], langs: ['Enclosed CJK Letters and Months'] }, // Enclosed CJK Letters and Months
  1484. { range: [0x3300, 0x33FF], langs: ['CJK Compatibility'] }, // CJK Compatibility
  1485. { range: [0x4E00, 0x9FFF], langs: ['Chinese (Simplified)', 'Chinese (Traditional)', 'Japanese', 'Korean'] }, // CJK Unified Ideographs
  1486. { range: [0xAC00, 0xD7AF], langs: ['Korean'] }, // Hangul Syllables
  1487. { range: [0xD800, 0xDBFF], langs: ['High Surrogates'] }, // High Surrogates
  1488. { range: [0xDC00, 0xDFFF], langs: ['Low Surrogates'] }, // Low Surrogates
  1489. { range: [0xF900, 0xFAFF], langs: ['CJK Compatibility Ideographs'] }, // CJK Compatibility Ideographs
  1490. { range: [0xFB00, 0xFB4F], langs: ['Alphabetic Presentation Forms'] }, // Alphabetic Presentation Forms
  1491. { range: [0xFB50, 0xFDFF], langs: ['Arabic Presentation Forms-A'] }, // Arabic Presentation Forms-A
  1492. { range: [0xFE20, 0xFE2F], langs: ['Combining Half Marks'] }, // Combining Half Marks
  1493. { range: [0xFE70, 0xFEFF], langs: ['Arabic Presentation Forms-B'] }, // Arabic Presentation Forms-B
  1494. { range: [0xFF00, 0xFFEF], langs: ['Halfwidth and Fullwidth Forms'] }, // Halfwidth and Fullwidth Forms
  1495. { range: [0xFFF0, 0xFFFF], langs: ['Specials'] }, // Specials
  1496. { range: [0x10000, 0x1007F], langs: ['Linear B Syllabary'] }, // Linear B Syllabary
  1497. { range: [0x10080, 0x100FF], langs: ['Linear B Ideograms'] }, // Linear B Ideograms
  1498. { range: [0x10100, 0x1013F], langs: ['Aegean Numbers'] }, // Aegean Numbers
  1499. { range: [0x10140, 0x1018F], langs: ['Ancient Greek Numbers'] }, // Ancient Greek Numbers
  1500. { range: [0x10190, 0x101CF], langs: ['Ancient Symbols'] }, // Ancient Symbols
  1501. { range: [0x101D0, 0x101FF], langs: ['Phaistos Disc'] }, // Phaistos Disc
  1502. { range: [0x10280, 0x1029F], langs: ['Lycian'] }, // Lycian
  1503. { range: [0x102A0, 0x102DF], langs: ['Carian'] }, // Carian
  1504. { range: [0x10300, 0x1032F], langs: ['Old Italic'] }, // Old Italic
  1505. { range: [0x10330, 0x1034F], langs: ['Gothic'] }, // Gothic
  1506. { range: [0x10380, 0x1039F], langs: ['Ugaritic'] }, // Ugaritic
  1507. { range: [0x103A0, 0x103DF], langs: ['Old Persian'] }, // Old Persian
  1508. { range: [0x10400, 0x1044F], langs: ['Deseret'] }, // Deseret
  1509. { range: [0x10450, 0x1047F], langs: ['Shavian'] }, // Shavian
  1510. { range: [0x10480, 0x104AF], langs: ['Osmanya'] }, // Osmanya
  1511. { range: [0x10800, 0x1083F], langs: ['Cypriot Syllabary'] }, // Cypriot Syllabary
  1512. { range: [0x10840, 0x1085F], langs: ['Imperial Aramaic'] }, // Imperial Aramaic
  1513. { range: [0x10900, 0x1091F], langs: ['Phoenician'] }, // Phoenician
  1514. { range: [0x10920, 0x1093F], langs: ['Lydian'] }, // Lydian
  1515. { range: [0x10A00, 0x10A5F], langs: ['Kharoshthi'] }, // Kharoshthi
  1516. { range: [0x10A60, 0x10A7F], langs: ['Old South Arabian'] }, // Old South Arabian
  1517. { range: [0x10B00, 0x10B3F], langs: ['Avestan'] }, // Avestan
  1518. { range: [0x10B40, 0x10B5F], langs: ['Inscriptional Parthian'] }, // Inscriptional Parthian
  1519. { range: [0x10B60, 0x10B7F], langs: ['Inscriptional Pahlavi'] }, // Inscriptional Pahlavi
  1520. { range: [0x10C00, 0x10C4F], langs: ['Old Turkic'] }, // Old Turkic
  1521. { range: [0x10E60, 0x10E7F], langs: ['Rumi Numeral Symbols'] }, // Rumi Numeral Symbols
  1522. { range: [0x11000, 0x1107F], langs: ['Brahmi'] }, // Brahmi
  1523. { range: [0x11080, 0x110CF], langs: ['Kaithi'] }, // Kaithi
  1524. { range: [0x12000, 0x123FF], langs: ['Cuneiform'] }, // Cuneiform
  1525. { range: [0x13000, 0x1342F], langs: ['Egyptian Hieroglyphs'] }, // Egyptian Hieroglyphs
  1526. { range: [0x16800, 0x16A3F], langs: ['Bamum'] }, // Bamum
  1527. { range: [0x1B000, 0x1B0FF], langs: ['Kana Supplement'] }, // Kana Supplement
  1528. { range: [0x1D000, 0x1D0FF], langs: ['Byzantine Musical Symbols'] }, // Byzantine Musical Symbols
  1529. { range: [0x1D100, 0x1D1FF], langs: ['Musical Symbols'] }, // Musical Symbols
  1530. { range: [0x1D200, 0x1D24F], langs: ['Ancient Greek Musical Notation'] }, // Ancient Greek Musical Notation
  1531. { range: [0x1D300, 0x1D35F], langs: ['Tai Xuan Jing Symbols'] }, // Tai Xuan Jing Symbols
  1532. { range: [0x1D360, 0x1D37F], langs: ['Counting Rod Numerals'] }, // Counting Rod Numerals
  1533. { range: [0x1D400, 0x1D7FF], langs: ['Mathematical Alphanumeric Symbols'] }, // Mathematical Alphanumeric Symbols
  1534. { range: [0x1F000, 0x1F02F], langs: ['Mahjong Tiles'] }, // Mahjong Tiles
  1535. { range: [0x1F030, 0x1F09F], langs: ['Domino Tiles'] }, // Domino Tiles
  1536. { range: [0x1F0A0, 0x1F0FF], langs: ['Playing Cards'] }, // Playing Cards
  1537. { range: [0x1F100, 0x1F1FF], langs: ['Enclosed Alphanumeric Supplement'] }, // Enclosed Alphanumeric Supplement
  1538. { range: [0x1F200, 0x1F2FF], langs: ['Enclosed Ideographic Supplement'] }, // Enclosed Ideographic Supplement
  1539. { range: [0x1F300, 0x1F5FF], langs: ['Miscellaneous Symbols and Pictographs'] }, // Miscellaneous Symbols and Pictographs
  1540. { range: [0x1F600, 0x1F64F], langs: ['Emoticons'] }, // Emoticons
  1541. { range: [0x1F680, 0x1F6FF], langs: ['Transport and Map Symbols'] }, // Transport and Map Symbols
  1542. { range: [0x1F700, 0x1F77F], langs: ['Alchemical Symbols'] }, // Alchemical Symbols
  1543. { range: [0x20000, 0x2A6DF], langs: ['CJK Unified Ideographs Extension B'] }, // CJK Unified Ideographs Extension B
  1544. { range: [0x2A700, 0x2B73F], langs: ['CJK Unified Ideographs Extension C'] }, // CJK Unified Ideographs Extension C
  1545. { range: [0x2B740, 0x2B81F], langs: ['CJK Unified Ideographs Extension D'] }, // CJK Unified Ideographs Extension D
  1546. { range: [0x2F800, 0x2FA1F], langs: ['CJK Compatibility Ideographs Supplement'] }, // CJK Compatibility Ideographs Supplement
  1547. ];
  1548.  
  1549.  
  1550.  
  1551. let lastLangEntry = null;
  1552.  
  1553. function getPossibleLanguages(unicodeChar) {
  1554. const unicode = typeof unicodeChar === 'number' ? unicodeChar : typeof unicodeChar === 'string' ? unicodeChar.codePointAt(0) : 0;
  1555.  
  1556. if (unicode >= 0x20) {
  1557. if (unicode >= 0x0370 && lastLangEntry && unicode >= lastLangEntry.range[0] && unicode <= lastLangEntry.range[1]) {
  1558. return lastLangEntry.langs;
  1559. }
  1560. for (const entry of languageMap) {
  1561. if (unicode >= entry.range[0] && unicode <= entry.range[1]) {
  1562. if (entry.range[0] >= 0x0370) lastLangEntry = entry;
  1563. return entry.langs;
  1564. }
  1565. if (entry.range[0] >= unicode && entry.range[1] >= unicode) break;
  1566. }
  1567. }
  1568.  
  1569. return languageMapR0;
  1570. }
  1571.  
  1572. const handleTextAllowSymbolsNChars = new Set('_-.·0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(e => e.codePointAt()));
  1573. const blacklistChars = new Set('@;:"\'!$#%^&*()[]<>,?/\\+{}|~`!'.split('').map(e => e.codePointAt()));
  1574.  
  1575. const _cache_isExactHandleText = new Map();
  1576. const isExactHandleText = (text, i = 0) => {
  1577. let cpCount = 0, cp = 0;
  1578. let cpMin = Number.MAX_VALUE
  1579. let cpMax = Number.MIN_VALUE
  1580. const suffixNumber = /\d+$/.exec(text);
  1581. const suffixNumberLen = `${suffixNumber || ''}`.length;
  1582. const textLen = text.length;
  1583. if (textLen - i > 30) return false;
  1584. let l = textLen - suffixNumberLen;
  1585. let maxCpCount = 30 - suffixNumberLen;
  1586. if (maxCpCount <= 0) return maxCpCount === 0;
  1587. const mtext = text.substring(i);
  1588. let res = _cache_isExactHandleText.get(mtext);
  1589. if (typeof res !== 'undefined') return res;
  1590.  
  1591. const retFn = (res) => {
  1592. _cache_isExactHandleText.set(mtext, res);
  1593. return res;
  1594. }
  1595.  
  1596. let uchars = [];
  1597. const uRanges = new Set();
  1598. for (; i < l; i++) {
  1599. cp = text.codePointAt(i);
  1600. if (!cp) break;
  1601. if (!handleTextAllowSymbolsNChars.has(cp)) {
  1602. // @[LANG]-c2w (found in Dec 2024)
  1603. if (blacklistChars.has(cp)) return retFn(false);
  1604. const uRange = getPossibleLanguages(cp);
  1605. uRanges.add(uRange);
  1606. uchars.push(cp);
  1607. if (cpMin > cp) cpMin = cp;
  1608. if (cpMax < cp) cpMax = cp;
  1609. }
  1610. if (cp < 0x7FFFFFFF) {
  1611. while (cp > 0xFFFF) {
  1612. cp = cp >> 16;
  1613. i++;
  1614. }
  1615. } else {
  1616. console.warn('cp >= 0x7FFFFFFF')
  1617. return retFn(false);
  1618. }
  1619. cpCount++;
  1620. if (cpCount > 30) {
  1621. return retFn(false);
  1622. }
  1623. }
  1624.  
  1625. // console.log(mtext, cpMin,cpMax, uRanges)
  1626. if (!uRanges.size || (cpMin >= 32 && cpMax <= 122)) {
  1627. return retFn(/^[-_a-zA-Z0-9.·]{3,30}$/.test(mtext));
  1628. }
  1629.  
  1630. let mm = {}, mi = 0;
  1631. for (const uRange of uRanges) {
  1632. if (uRange) {
  1633. for (const lang of uRange) {
  1634. if (lang) {
  1635. mm[lang] = (mm[lang] || 0) + 1;
  1636. }
  1637. }
  1638. }
  1639. mi++;
  1640. }
  1641. let unilang = "";
  1642. let dd = Object.entries(mm).filter(a => a[1] === mi);
  1643. if (dd.length === 1) {
  1644. unilang = dd[0];
  1645. } else if (dd.length === 3 && dd[0][0] === 'Arabic' && dd[1][0] === 'Persian' && dd[2][0] === 'Urdu') {
  1646. return retFn("Arabic");
  1647. }else if (dd.length === 4 && dd[0][0] === 'Chinese (Simplified)' && dd[1][0] === 'Chinese (Traditional)' && dd[2][0] === 'Japanese' && dd[3][0] === 'Korean') {
  1648. return retFn("CJK");
  1649. }
  1650.  
  1651.  
  1652.  
  1653. if (unilang[0] === "Japanese") {
  1654. return retFn("Japanese"); // japanese handle can mix with kanji
  1655. }
  1656.  
  1657.  
  1658. if (cpMin >= 0x1000) {
  1659. const ft = String.fromCodePoint(...uchars);
  1660. if (cpMin >= 0x4E00 && cpMax <= 0xD7AF) {
  1661. if (/^[\u4E00-\u9FFF\uAC00-\uD7AF]{1,10}$/.test(ft)) return retFn("Han|Hangul");
  1662. } else if (cpMin >= 0x1200 && cpMax <= 0x30FF) {
  1663. if (/^[\u1200-\u137F\u3040-\u30FF]{2,20}$/.test(ft)) return retFn("Ethiopic|Hiragana|Katakana");
  1664. }
  1665. }
  1666.  
  1667. return retFn(false);
  1668.  
  1669. }
  1670.  
  1671. const exactHandleText = (text, b) => {
  1672. return text.startsWith('@') && isExactHandleText(text, 1) ? (b ? true : text.substring(1)) : (b ? false : '');
  1673. }
  1674.  
  1675. const exactHandleUrl_ = (text, b, c) => {
  1676. if (c === 2) {
  1677. if (isValidMinSlashHandle(text)) {
  1678. text = urlHandleConversion(text) || text;
  1679. } else {
  1680. return b ? false : '';
  1681. }
  1682. } else if (c === 1 && (text.length < NUM_CHANNEL_ID_MIN_LEN_2 || text.length > 32)) { // 2+30
  1683. return false;
  1684. }
  1685. return text.startsWith('/@') && isExactHandleText(text, 2) ? (b ? true : text.substring(2)) : (b ? false : '');
  1686. }
  1687.  
  1688. const _cache_urlHandleConversion = new Map();
  1689. const urlHandleConversion = (text) => {
  1690.  
  1691. let converted = _cache_urlHandleConversion.get(text);
  1692.  
  1693. if (typeof converted === 'string') {
  1694.  
  1695. text = converted;
  1696.  
  1697. } else if (text.includes('%')) {
  1698. let text0 = text;
  1699.  
  1700. let text2 = text.substring(2);
  1701. if (/%[0-9A-Fa-f]{2}/.test(text2) && /^[-_a-zA-Z%0-9.·]+$/.test(text2)) {
  1702. try {
  1703. text2 = decodeURI(text2);
  1704. } catch (e) { }
  1705. text = `/@${text2}`
  1706. }
  1707. _cache_urlHandleConversion.set(text0, text);
  1708.  
  1709. }
  1710.  
  1711.  
  1712. if (exactHandleUrl_(text, true, 1)) {
  1713. return text;
  1714. }
  1715.  
  1716. }
  1717. const exactHandleUrl = (text, b) => {
  1718. return exactHandleUrl_(text, b, 2);
  1719. }
  1720.  
  1721. try {
  1722. // https://www.youtube.com/watch?v=hfopp1vLFmk
  1723. // https://www.youtube.com/watch?v=V-4PiHDX2Mg
  1724. let b = true
  1725.  
  1726.  
  1727. b = b && isDisplayAsHandle('@7r0n215 ');
  1728. b = b && isDisplayAsHandle('@user-ox5by7bw1m ');
  1729. b = b && isDisplayAsHandle('@Samsungfan2016 ');
  1730. b = b && isDisplayAsHandle('@김태래 ');
  1731. b = b && !isDisplayAsHandle('@%EA%B9%80%ED%83%9C%EB%9E%98 ');
  1732.  
  1733. b = b && !exactHandleText('@7r0n215 ', true);
  1734. b = b && !exactHandleText('@user-ox5by7bw1m ', true);
  1735. b = b && !exactHandleText('@Samsungfan2016 ', true);
  1736. b = b && !exactHandleText('@김태래 ', true);
  1737. b = b && !exactHandleText('@%EA%B9%80%ED%83%9C%EB%9E%98 ', true);
  1738.  
  1739.  
  1740. b = b && !exactHandleUrl('/@7r0n215 ', true);
  1741. b = b && !exactHandleUrl('/@user-ox5by7bw1m ', true);
  1742. b = b && !exactHandleUrl('/@Samsungfan2016 ', true);
  1743. b = b && !exactHandleUrl('/@김태래 ', true);
  1744. b = b && !exactHandleUrl('/@%EA%B9%80%ED%83%9C%EB%9E%98 ', true);
  1745.  
  1746.  
  1747. b = b && isDisplayAsHandle(' @7r0n215');
  1748. b = b && isDisplayAsHandle(' @user-ox5by7bw1m');
  1749. b = b && isDisplayAsHandle(' @Samsungfan2016');
  1750. b = b && isDisplayAsHandle(' @김태래');
  1751. b = b && !isDisplayAsHandle(' @%EA%B9%80%ED%83%9C%EB%9E%98');
  1752.  
  1753. b = b && !exactHandleText(' @7r0n215', true);
  1754. b = b && !exactHandleText(' @user-ox5by7bw1m', true);
  1755. b = b && !exactHandleText(' @Samsungfan2016', true);
  1756. b = b && !exactHandleText(' @김태래', true);
  1757. b = b && !exactHandleText(' @%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1758.  
  1759. b = b && !exactHandleUrl(' /@7r0n215', true);
  1760. b = b && !exactHandleUrl(' /@user-ox5by7bw1m', true);
  1761. b = b && !exactHandleUrl(' /@Samsungfan2016', true);
  1762. b = b && !exactHandleUrl(' /@김태래', true);
  1763. b = b && !exactHandleUrl(' /@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1764.  
  1765.  
  1766. b = b && isDisplayAsHandle('@7r0n215');
  1767. b = b && isDisplayAsHandle('@user-ox5by7bw1m');
  1768. b = b && isDisplayAsHandle('@Samsungfan2016');
  1769. b = b && isDisplayAsHandle('@김태래');
  1770. b = b && !isDisplayAsHandle('@%EA%B9%80%ED%83%9C%EB%9E%98');
  1771.  
  1772. b = b && exactHandleText('@7r0n215', true);
  1773. b = b && exactHandleText('@user-ox5by7bw1m', true);
  1774. b = b && exactHandleText('@Samsungfan2016', true);
  1775. b = b && exactHandleText('@김태래', true);
  1776. b = b && !exactHandleText('@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1777.  
  1778.  
  1779. b = b && exactHandleUrl('/@7r0n215', true);
  1780. b = b && exactHandleUrl('/@user-ox5by7bw1m', true);
  1781. b = b && exactHandleUrl('/@Samsungfan2016', true);
  1782. b = b && exactHandleUrl('/@김태래', true);
  1783. b = b && exactHandleUrl('/@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1784.  
  1785. b = b && isDisplayAsHandle('@Lions_joyfulpenda');
  1786. b = b && isDisplayAsHandle('@kowlsl12');
  1787. b = b && isDisplayAsHandle('@hyezzozzo_baseball_curtaincall');
  1788. b = b && isDisplayAsHandle('@blue-pink-love');
  1789.  
  1790.  
  1791. b = b && isDisplayAsHandle('@mr.memebear901');
  1792. b = b && isDisplayAsHandle('@すいちゃん可愛い');
  1793. b = b && exactHandleUrl('/@%E3%81%99%E3%81%84%E3%81%A1%E3%82%83%E3%82%93%E5%8F%AF%E6%84%9B%E3%81%84');
  1794. b = b && isDisplayAsHandle('@ハシビロ公');
  1795. b = b && exactHandleUrl('/@%E3%83%8F%E3%82%B7%E3%83%93%E3%83%AD%E5%85%AC');
  1796. b = b && isDisplayAsHandle('@ex1524')
  1797. b = b && isDisplayAsHandle('@K88571')
  1798. b = b && isDisplayAsHandle('@مجلةالرابالعربي')
  1799. b = b && !isDisplayAsHandle('@@مجلةالرابالعربي')
  1800.  
  1801. b = b && isDisplayAsHandle('@ともとも-e7d8b')
  1802. b = b && isDisplayAsHandle('@佐藤漣-x7i')
  1803. b = b && isDisplayAsHandle('@巡空')
  1804. b = b && isDisplayAsHandle('@abc')
  1805. b = b && isDisplayAsHandle('@巡')
  1806. b = b && !isDisplayAsHandle('@xy')
  1807. b = b && !isDisplayAsHandle('@z')
  1808. b = b && isDisplayAsHandle('@茶々-l9y')
  1809.  
  1810.  
  1811. if (!b) console.error('!!!! wrong coding !!!!');
  1812. } catch (e) {
  1813. console.error('!!!! wrong coding !!!!', e);
  1814. }
  1815. /**
  1816. *
  1817. * @param {Object[]} contentTexts
  1818. * @param {number} idx
  1819. * @returns
  1820. */
  1821. const contentTextProcess = (_md, contentTexts, idx) => {
  1822. const md = _md;
  1823. const contentText = contentTexts[idx];
  1824. const text = (contentText || 0).text;
  1825. const browseId = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1826. const canonicalBaseUrl = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1827. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1828. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1829.  
  1830. if (!isDisplayAsHandle(text)) return null;
  1831. const channelId = browseId;
  1832.  
  1833. return getDisplayName(channelId).then(fetchResult => {
  1834. let resolveResult = null;
  1835. if (fetchResult) {
  1836. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1837.  
  1838. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1839. if (textTrimmed) {
  1840. resolveResult = (() => {
  1841. let runs = ((md || 0).contentText || 0).runs;
  1842. if (!runs || !runs[idx]) return;
  1843. if (runs[idx].text !== text) return;
  1844. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1845. md.contentText = Object.assign({}, md.contentText);
  1846. })();
  1847. }
  1848. }
  1849. return resolveResult; // function as a Promise
  1850. });
  1851. }
  1852.  
  1853. return null;
  1854. };
  1855.  
  1856. const dynamicEditableTextByControllerResolve = isMobile ? 0 : (() => {
  1857. /**
  1858. *
  1859. *
  1860. f.showReplyDialog = function(a) {
  1861. if (a) {
  1862. var b = this.replyBox;
  1863. b || (b = document.createElement("ytd-comment-reply-dialog-renderer"),
  1864. b.id = "replybox",
  1865. qF(this.replyDialogDiv).appendChild(b));
  1866. b.data = a;
  1867. this.replyDialogDiv.hidden = !1;
  1868. b.openDialog()
  1869. }
  1870. }
  1871.  
  1872. // a = <ytd-comment-engagement-bar>...</ytd-comment-engagement-bar>
  1873. // b = "showReplyDialog"
  1874. // c = undefined
  1875. function Lpb(a, b, c) {
  1876. var d = a.polymerController;
  1877. a[b] = function() {
  1878. var e = va.apply(0, arguments);
  1879. a.loggingStatus.currentExternalCall = b;
  1880. a.loggingStatus.bypassProxyController = !0;
  1881. var g, k = ((g = a.is) != null ? g : a.tagName).toLowerCase();
  1882. ZE(k, b, "PROPERTY_ACCESS_CALL_EXTERNAL");
  1883. var m;
  1884. g = (m = c != null ? c : d[b]) == null ? void 0 : m.call.apply(m, [d].concat(ha(e)));
  1885. a.loggingStatus.currentExternalCall = void 0;
  1886. a.loggingStatus.bypassProxyController = !1;
  1887. return g
  1888. }
  1889. }
  1890.  
  1891. // a = {..., commandMetadata, createCommentReplyDialogEndpoint}
  1892. // b = {commandController: {onSuccess: ƒ, onServerError: ƒ} , forceClickLogging : true, form: {element, event} }
  1893. kQb.prototype.resolveCommand = function(a, b) {
  1894. var c, d, e, g, k, m, p, q;
  1895. return t(function(r) {
  1896. e = (c = G(a, n6a)) == null ? void 0 : (d = c.dialog) == null ? void 0 : d.commentReplyDialogRenderer;
  1897. if (!e)
  1898. throw new Em("No dialog in createCommentReplyDialogEndpoint");
  1899. k = (g = b.form) == null ? void 0 : g.event;
  1900. if (!k)
  1901. throw new Em("Event not passed in when resolving command");
  1902. m = h(k.composedPath());
  1903. for (p = m.next(); !p.done; p = m.next())
  1904. if (q = p.value,
  1905. q.tagName === "YTD-COMMENT-ACTION-BUTTONS-RENDERER" || q.tagName === "YTD-COMMENT-ENGAGEMENT-BAR")
  1906. return q.showReplyDialog(e),
  1907. r.return();
  1908. ma(r)
  1909. })
  1910. }
  1911.  
  1912.  
  1913. *
  1914. */
  1915.  
  1916.  
  1917. const setupForCommentReplyDialogRenderer = (cProto) => {
  1918. if (cProto && typeof cProto.showReplyDialog === 'function' && cProto.showReplyDialog.length === 1 && !cProto.showReplyDialog392) {
  1919. cProto.showReplyDialog392 = cProto.showReplyDialog;
  1920. cProto.showReplyDialog = function (a) {
  1921. let goDefault = true;
  1922. try {
  1923. if (a && a.editableText) {
  1924. const arr = [];
  1925. fixCommentReplyDialogRenderer(a, arr);
  1926. const pAll = Promise.all(arr).catch(e => console.warn);
  1927. Promise.race([pAll, delayPn(300)]).then(() => { // network request should be already done before
  1928. this.showReplyDialog392(a);
  1929. });
  1930. goDefault = false;
  1931. }
  1932. } catch (e) { }
  1933. if (goDefault) {
  1934. return this.showReplyDialog392(a);
  1935. }
  1936. };
  1937. }
  1938. };
  1939.  
  1940. retrieveCE('ytd-comment-action-buttons-renderer').then(cProto => {
  1941. setupForCommentReplyDialogRenderer(cProto);
  1942. });
  1943. retrieveCE('ytd-comment-engagement-bar').then(cProto => {
  1944. setupForCommentReplyDialogRenderer(cProto);
  1945. });
  1946.  
  1947. return 1;
  1948.  
  1949. })();
  1950.  
  1951. const editableTextProcess = (_commentReplyDialogRenderer, editableTexts, idx) => {
  1952. const commentReplyDialogRenderer = _commentReplyDialogRenderer;
  1953. const editableText = editableTexts[idx];
  1954. const text = (editableText || 0).text;
  1955.  
  1956. const browseId = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1957. const canonicalBaseUrl = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1958. const url = (((editableText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1959. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1960.  
  1961. if (!isDisplayAsHandle(text)) return null;
  1962. const channelId = browseId;
  1963.  
  1964. return getDisplayName(channelId).then(fetchResult => {
  1965. let resolveResult = null;
  1966. if (fetchResult) {
  1967. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1968.  
  1969. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1970. if (textTrimmed) {
  1971. resolveResult = (() => {
  1972. if (!commentReplyDialogRenderer) return;
  1973. const editableText = commentReplyDialogRenderer.editableText || 0;
  1974. let runs = (editableText || 0).runs;
  1975. if (!runs || !runs[idx]) return;
  1976. if (runs[idx].text !== text) return;
  1977. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1978. commentReplyDialogRenderer.editableText = Object.assign({}, commentReplyDialogRenderer.editableText);
  1979. })();
  1980. }
  1981. }
  1982. return resolveResult; // function as a Promise
  1983. });
  1984. }
  1985.  
  1986. return null;
  1987. };
  1988.  
  1989. const { contentTextProcessViewModel } = (() => {
  1990.  
  1991. const isIterable = (obj) => (obj && typeof obj[Symbol.iterator] === 'function');
  1992.  
  1993. /**
  1994. * Optimized version of expandIntervals.
  1995. * @param {Array} arr - Array of mapping objects with oIdx1, oIdx2, nIdx1, nIdx2.
  1996. * @returns {Array} - Expanded and sorted interval mappings.
  1997. */
  1998. function expandIntervals(arr) {
  1999. if (!arr || arr.length === 0) return [];
  2000.  
  2001. const n = arr.length; // n>=1
  2002.  
  2003. // Sort the mappings by oIdx1 if not already sorted
  2004. if (n > 1) arr.sort((a, b) => a.oIdx1 - b.oIdx1);
  2005.  
  2006. const result = new Array(n * 2 + 1); // max length
  2007. let j = 0;
  2008.  
  2009. // Handle the first gap if it exists
  2010. if (arr[0].oIdx1 > 0) {
  2011. result[j++] = {
  2012. oStart: 0,
  2013. oEnd: arr[0].oIdx1,
  2014. nStart: 0,
  2015. nEnd: arr[0].nIdx1
  2016. };
  2017. }
  2018.  
  2019. for (let i = 0, current; current = arr[i]; i++) {
  2020. result[j++] = {
  2021. oStart: current.oIdx1,
  2022. oEnd: current.oIdx2,
  2023. nStart: current.nIdx1,
  2024. nEnd: current.nIdx2
  2025. };
  2026.  
  2027. if (i >= n - 1) {
  2028. // Handle the final gap
  2029. result[j++] = {
  2030. oStart: current.oIdx2,
  2031. oEnd: null,
  2032. nStart: current.nIdx2,
  2033. nEnd: null
  2034. };
  2035. break;
  2036. }
  2037.  
  2038. // If not the last interval, handle the gap
  2039. const next = arr[i + 1];
  2040. const gapStart = current.oIdx2;
  2041. const gapEnd = next.oIdx1;
  2042.  
  2043. if (gapStart < gapEnd) {
  2044. const shift = next.nIdx1 - next.oIdx1;
  2045. result[j++] = {
  2046. oStart: gapStart,
  2047. oEnd: gapEnd,
  2048. nStart: gapStart + shift,
  2049. nEnd: gapEnd + shift
  2050. };
  2051. }
  2052. }
  2053.  
  2054.  
  2055. result.length = j;
  2056.  
  2057. return result;
  2058. }
  2059.  
  2060.  
  2061. // abcdef. [0,3][3,6]
  2062.  
  2063. /**
  2064. * Updates a target array in-place based on sorted interval mappings.
  2065. * Assumes both targetArray and intervalMappings are sorted by startIndex.
  2066. * @param {Array} uArr - Array of objects with startIndex and length.
  2067. * @param {Array} itMap - Expanded and sorted interval mappings.
  2068. */
  2069. function updateArrayInPlaceOptimized(uArr, itMap) {
  2070. let mapIdx = 0;
  2071. const itMapN = itMap.length;
  2072.  
  2073. const mapIndex = (qIndex) => {
  2074. while (
  2075. mapIdx < itMapN &&
  2076. itMap[mapIdx].oEnd !== null &&
  2077. qIndex > itMap[mapIdx].oEnd
  2078. ) {
  2079. mapIdx++;
  2080. }
  2081. // expect: qIndex>=[mapIdx].oStart && ([mapIdx].oEnd === null || qIndex<=[mapIdx].oEnd)
  2082.  
  2083. if (mapIdx >= itMapN) {
  2084. throw new Error(`No mapping found for index ${qIndex}`);
  2085. }
  2086.  
  2087. const { oStart, nStart, oEnd, nEnd } = itMap[mapIdx];
  2088.  
  2089. if (qIndex == oStart) {
  2090. return nStart;
  2091. } else if (qIndex === oEnd) {
  2092. return nEnd;
  2093. } else {
  2094. const size1 = oEnd - oStart;
  2095. const size2 = nEnd === null ? size1 : nEnd - nStart;
  2096. if (size1 !== size2) {
  2097. return Math.round(nStart + (qIndex - oStart) / size1 * size2);
  2098. } else {
  2099. return nStart + (qIndex - oStart);
  2100. }
  2101. }
  2102.  
  2103. };
  2104. for (const item of uArr) {
  2105.  
  2106. const {startIndex, length} = item;
  2107.  
  2108. if (typeof startIndex === 'number' && typeof length === 'number' && startIndex >= 0 && length >= 0) {
  2109.  
  2110. const newStart = mapIndex(startIndex);
  2111. const newEnd = mapIndex(startIndex + length);
  2112.  
  2113. if (newStart === undefined || newEnd === undefined) {
  2114. throw new Error(`Mapping failed for item: ${JSON.stringify(item)}`);
  2115. }
  2116.  
  2117. item.startIndex = newStart;
  2118. item.length = newEnd - newStart;
  2119. }
  2120. };
  2121. }
  2122.  
  2123. function replaceNamePN(o) {
  2124. return getDisplayName(o.channelId).then(fetchResult => {
  2125. let resolveResult = null;
  2126. if (fetchResult) {
  2127. const textTrimmed = verifyAndConvertHandle(o.handle, fetchResult);
  2128. if (textTrimmed) {
  2129. o.display = `@${fetchResult.title}`;
  2130. o.newText = o.oldText.replace(o.handle, o.display);
  2131. o.nLen = o.newText.length;
  2132. o.nOffset = o.nLen - o.oLen;
  2133. }
  2134. }
  2135. return resolveResult; // function as a Promise
  2136. });
  2137. }
  2138.  
  2139. const contentTextProcessViewModel = async (content, idx) => {
  2140. const { commandRuns, content: text } = content;
  2141. if (typeof text !== 'string' || !commandRuns) return;
  2142. let uBool = false;
  2143.  
  2144. const objList = [];
  2145. for (const [key, value] of Object.entries(content)) {
  2146. if ((value || 0).length >= 1 && typeof value === 'object' && isIterable(value)) {
  2147. objList.push(value);
  2148. if (key === 'commandRuns') uBool = true;
  2149. }
  2150. }
  2151.  
  2152. if (!uBool) return;
  2153.  
  2154. const names = [];
  2155.  
  2156. const promises = [];
  2157. for (const commandRun of commandRuns) {
  2158. let browseEndpoint = null;
  2159. if (commandRun.length >= 1 && commandRun.startIndex >= 0 && (browseEndpoint = ((commandRun.onTap || 0).innertubeCommand || 0).browseEndpoint)) {
  2160. const substr = text.substring(commandRun.startIndex, commandRun.startIndex + commandRun.length);
  2161. const substrTrimmed = substr.trim();
  2162. const valBrowseEndpointBaseUrlType = browseEndpointBaseUrlType(browseEndpoint, substrTrimmed);
  2163. if (valBrowseEndpointBaseUrlType > 1) {
  2164. const o = {
  2165. startIndex: commandRun.startIndex,
  2166. endIndex: commandRun.startIndex + commandRun.length,
  2167. handle: substrTrimmed,
  2168. oldText: substr,
  2169. newText: null,
  2170. channelId: browseEndpoint.browseId,
  2171. oLen: commandRun.length,
  2172. nLen: null,
  2173. nOffset: 0,
  2174. }
  2175. names.push(o);
  2176. promises.push(replaceNamePN(o));
  2177. }
  2178. }
  2179. }
  2180. await Promise.all(promises);
  2181.  
  2182. let text1 = text;
  2183.  
  2184. try {
  2185. const mapInput = new Array(names.length);
  2186. let ac = 0;
  2187.  
  2188. for (let k = 0; k < names.length; k++) {
  2189. const o = names[k];
  2190.  
  2191. mapInput[k] = {
  2192. oIdx1: o.startIndex,
  2193. oIdx2: o.endIndex,
  2194.  
  2195. nIdx1: o.startIndex + ac,
  2196. nIdx2: o.endIndex + ac + o.nOffset,
  2197.  
  2198. }
  2199. ac += o.nOffset;
  2200. }
  2201. // abcdef
  2202. // [0,3][3,6]
  2203.  
  2204. const mapOutput = expandIntervals(mapInput);
  2205. const u = new Array(mapOutput.length);
  2206.  
  2207. let k = 0;
  2208. for (let i = 0; i < mapOutput.length; i++) {
  2209. const { oStart, oEnd } = mapOutput[i];
  2210. if (k < names.length && oStart === names[k].startIndex && oEnd === names[k].endIndex) {
  2211. u[i] = names[k++].newText;
  2212. } else {
  2213. u[i] = text.substring(oStart, oEnd !== null ? oEnd : text.length);
  2214. }
  2215. }
  2216. text1 = u.join('');
  2217. u.length = 0;
  2218.  
  2219. for (const runs of objList) {
  2220. updateArrayInPlaceOptimized(runs, mapOutput)
  2221. }
  2222.  
  2223. content.content = text1;
  2224.  
  2225. } catch (e) {
  2226. console.warn(e);
  2227. }
  2228.  
  2229.  
  2230.  
  2231.  
  2232.  
  2233. };
  2234.  
  2235.  
  2236. // const contentTextProcessViewModel = async (content, idx) => {
  2237. // const { commandRuns, content: text, styleRuns } = content;
  2238. // if (typeof text !== 'string') return;
  2239. // const names = [];
  2240.  
  2241. // function replaceNamePN(o) {
  2242. // return getDisplayName(o.channelId).then(fetchResult => {
  2243. // let resolveResult = null;
  2244. // if (fetchResult) {
  2245. // const textTrimmed = verifyAndConvertHandle(o.handle, fetchResult);
  2246. // if (textTrimmed) {
  2247. // o.display = `@${fetchResult.title}`;
  2248. // o.newText = o.oldText.replace(o.handle, o.display);
  2249. // }
  2250. // }
  2251. // return resolveResult; // function as a Promise
  2252. // });
  2253. // }
  2254. // const promises = [];
  2255. // for (const commandRun of commandRuns) {
  2256. // let browseEndpoint = null;
  2257. // if (commandRun.length >= 1 && commandRun.startIndex >= 0 && (browseEndpoint = ((commandRun.onTap || 0).innertubeCommand || 0).browseEndpoint)) {
  2258. // let substr = text.substring(commandRun.startIndex, commandRun.startIndex + commandRun.length);
  2259. // const substrTrimmed = substr.trim();
  2260. // const valBrowseEndpointBaseUrlType = browseEndpointBaseUrlType(browseEndpoint, substrTrimmed);
  2261. // if (valBrowseEndpointBaseUrlType > 1) {
  2262. // const o = {
  2263. // startIndex: commandRun.startIndex,
  2264. // endIndex: commandRun.startIndex + commandRun.length,
  2265. // handle: substrTrimmed,
  2266. // oldText: substr,
  2267. // newText: null,
  2268. // channelId: browseEndpoint.browseId,
  2269. // nStartIndex: null,
  2270. // nEndIndex: null,
  2271. // nText: null
  2272. // }
  2273. // names.push(o);
  2274. // promises.push(replaceNamePN(o));
  2275. // }
  2276. // }
  2277. // }
  2278. // await Promise.all(promises);
  2279.  
  2280. // let offset = 0;
  2281. // for (const o of names) {
  2282. // o.nStartIndex = o.startIndex + offset;
  2283. // o.nText = o.newText === null ? o.oldText : o.newText;
  2284. // o.nEndIndex = o.nStartIndex + offset + o.nText.length;
  2285. // offset += o.nText.length - o.oldText.length;
  2286. // }
  2287.  
  2288. // let w1 = 0, w2 = 0;
  2289. // let s = [];
  2290. // let j = 0;
  2291. // for (let i = 0; i < text.length;) {
  2292. // while (w1 < commandRuns.length && commandRuns[w1].startIndex < i) w1++;
  2293. // while (w2 < styleRuns.length && styleRuns[w2].startIndex < i) w2++;
  2294.  
  2295. // if (j < names.length && i == names[j].startIndex) {
  2296.  
  2297. // if (w1 < commandRuns.length && commandRuns[w1].startIndex === names[j].startIndex) {
  2298. // const run = commandRuns[w1];
  2299. // const o = names[j];
  2300. // if (run.length === o.endIndex - o.startIndex) {
  2301. // run.startIndex = o.nStartIndex;
  2302. // run.length = o.nText.length;
  2303. // }
  2304. // w1++;
  2305. // }
  2306.  
  2307. // if (w2 < styleRuns.length && styleRuns[w2].startIndex === names[j].startIndex) {
  2308. // const run = styleRuns[w2];
  2309. // const o = names[j];
  2310. // if (run.length === o.endIndex - o.startIndex) {
  2311. // run.startIndex = o.nStartIndex;
  2312. // run.length = o.nText.length;
  2313. // }
  2314. // w2++;
  2315. // }
  2316.  
  2317.  
  2318. // // s.push(text.substring(names[j].startIndex, names[j].endIndex));
  2319. // s.push(names[j].nText);
  2320. // i = names[j].endIndex;
  2321. // j++;
  2322. // } else {
  2323. // if (j >= names.length) {
  2324. // s.push(text.substring(i));
  2325. // i = text.length;
  2326. // } else {
  2327. // if (j < names.length && names[j].startIndex > i + 1) {
  2328. // s.push(text.substring(i, names[j].startIndex));
  2329. // i = names[j].startIndex;
  2330. // } else {
  2331. // s.push(text.charAt(i));
  2332. // i++;
  2333. // }
  2334. // }
  2335. // }
  2336. // }
  2337.  
  2338. // content.content = s.join('');
  2339. // s.length = 0;
  2340.  
  2341.  
  2342. // };
  2343.  
  2344. return { contentTextProcessViewModel };
  2345. })();
  2346.  
  2347.  
  2348. /**
  2349. *
  2350. * @param {ParentNode & Element} parentNode
  2351. * @param {Function} callback
  2352. */
  2353. function findTextNodes(parentNode, callback) {
  2354. /**
  2355. *
  2356. * @param {Node} node
  2357. * @returns
  2358. */
  2359. function traverse(node) {
  2360. if (node.nodeType === Node.TEXT_NODE) {
  2361. let r = callback(node);
  2362. if (r === true) return true;
  2363. } else if (node.nodeType === Node.ELEMENT_NODE) {
  2364. for (let childNode = nodeFirstChild(node); childNode; childNode = nodeNextSibling(childNode)) {
  2365. const r = traverse(childNode);
  2366. if (r === true) return true;
  2367. }
  2368. }
  2369. }
  2370.  
  2371. traverse(parentNode);
  2372. }
  2373.  
  2374. function updatePinnedCommentBadge(md, title, langTitle) {
  2375. const titleForDisplay = langTitle || title;
  2376. if (typeof titleForDisplay !== 'string') return;
  2377. if (title === titleForDisplay) return;
  2378. const runs = ((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0); // can be 0
  2379. if (runs.length === 2) {
  2380. let idx = 0;
  2381. let jdx = -1;
  2382. for (const textRun of runs) {
  2383. if (textRun.text === title) {
  2384. jdx = idx;
  2385. break;
  2386. }
  2387. idx++;
  2388. }
  2389. if (jdx >= 0) {
  2390. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  2391. runs[jdx] = Object.assign({}, runs[jdx], { text: titleForDisplay });
  2392. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  2393. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  2394. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  2395. }
  2396. }
  2397. }
  2398.  
  2399. /**
  2400. *
  2401. * @param {ParentNode} parentNode
  2402. * @param {Object[]} contentTexts
  2403. * @param {number} aidx
  2404. * @returns
  2405. */
  2406. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  2407.  
  2408.  
  2409. let commentText = elementQS(parentNode, '.comment-text');
  2410. if (!commentText) return;
  2411. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  2412. let currentText = commentText.textContent;
  2413. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  2414. if (!textMatch) return;
  2415.  
  2416. const contentText = contentTexts[aidx];
  2417.  
  2418. /** @type {string} */
  2419. const handleText = contentText.text.trim();
  2420. /** @type {string | null | undefined} */
  2421. let channelId;
  2422.  
  2423. let cache = handleToChannelId.get(handleText);
  2424.  
  2425. if (typeof cache === 'string') {
  2426. channelId = cache;
  2427. } else if (cache instanceof AsyncValue) {
  2428. channelId = await cache.getValue();
  2429. } else {
  2430. /** @type {AsyncValue<string>} */
  2431. const asyncValue = new AsyncValue();
  2432. handleToChannelId.set(handleText, asyncValue);
  2433. channelId = await asyncValue.getValue(); // note: it could be never resolved
  2434. }
  2435.  
  2436. if (!channelId) return; // just in case
  2437.  
  2438. if (commentText.isConnected !== true) return; // already removed
  2439. if (commentText.textContent !== currentText) return; // already changed
  2440.  
  2441. const fetchResult = await getDisplayName(channelId);
  2442.  
  2443. if (fetchResult === null) return;
  2444.  
  2445. const { title, langTitle, externalId } = fetchResult;
  2446. const titleForDisplay = langTitle || title;
  2447. if (externalId !== channelId) return; // channel id must be the same
  2448.  
  2449. if (commentText.isConnected !== true) return; // already removed
  2450. if (commentText.textContent !== currentText) return; // already changed
  2451.  
  2452. let search = contentText.text;
  2453. if (typeof search === 'string') {
  2454.  
  2455. const searchTrimmed = search.trim();
  2456. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  2457. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  2458.  
  2459. findTextNodes(commentText, (textnode) => {
  2460. if (textnode.nodeValue.indexOf(search) >= 0) {
  2461. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  2462. return true;
  2463. }
  2464. });
  2465. }
  2466.  
  2467. }
  2468.  
  2469. }
  2470.  
  2471. /**
  2472. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  2473. * @type { (anchor: HTMLElement, anchorHref: string?, mt: string?) => Promise<void> }
  2474. */
  2475.  
  2476. const getDisplayTextDOMForCommentRenderer = (root) => { // mobile
  2477. let displayTextDOM = elementQS(root, '.comment-header .comment-title');
  2478. if (displayTextDOM) {
  2479. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  2480. }
  2481. return displayTextDOM;
  2482. }
  2483.  
  2484. const ytPathnameExtract = (href) => {
  2485.  
  2486. if (!href || typeof href !== 'string') return '';
  2487. let i = 0;
  2488. if (href.startsWith('/')) {
  2489.  
  2490. } else if ((i = href.indexOf('youtube.com/')) >= 0) {
  2491. href = href.substring(i + 11);
  2492. } else {
  2493. return '';
  2494. }
  2495. return href;
  2496.  
  2497. }
  2498.  
  2499. const getHrefType = (href) => {
  2500. if (href && typeof href === 'string') {
  2501. if (href.length === 33 && href.startsWith('/channel/') && /^\/channel\/UC[-_a-zA-Z0-9+=.]{22}$/.test(href)) {
  2502. return 1;
  2503. } else {
  2504. if (isValidMinSlashHandle(href)) {
  2505. href = urlHandleConversion(href) || href;
  2506. }
  2507. if (href && exactHandleUrl_(href, true, 1)) {
  2508. return 2;
  2509. }
  2510. }
  2511. }
  2512. return 0;
  2513. }
  2514.  
  2515. const getYTextType = (text) => {
  2516. // if (typeof text === 'string') return 1;
  2517. if (typeof text === 'object' && text) {
  2518. if (typeof text.simpleText === 'string') return 2;
  2519. const runs = text.runs;
  2520. if (runs && runs.length === 1) {
  2521. let r = runs[0];
  2522. return typeof r === 'string' ? 3 : typeof (r || 0).text === 'string' ? 4 : null;
  2523. }
  2524. }
  2525. return null;
  2526. }
  2527.  
  2528. const getYTextContent = (text) => {
  2529. // if (typeof text === 'string') return text;
  2530. if (typeof text === 'object' && text) {
  2531. const simpleText = text.simpleText;
  2532. if (typeof simpleText === 'string') return simpleText;
  2533. const runs = text.runs;
  2534. if (runs && runs.length === 1) {
  2535. let r = runs[0];
  2536. return typeof r === 'string' ? r : typeof (r || 0).text === 'string' ? r.text : null;
  2537. }
  2538. }
  2539. return null;
  2540. }
  2541.  
  2542. const setYTextContent = (text, fn) => {
  2543. // if (typeof text === 'string') {
  2544. // res=fn(text);
  2545. // }
  2546. if (typeof text === 'object' && text) {
  2547. const simpleText = text.simpleText;
  2548. if (typeof simpleText === 'string') {
  2549. return Object.assign({}, text, { simpleText: fn(simpleText) });
  2550. }
  2551. const runs = text.runs;
  2552. if (runs && runs.length === 1) {
  2553. let r = runs[0];
  2554. return typeof r === 'string' ? Object.assign({}, text, { runs: [fn(r)] }) : typeof (r || 0).text === 'string' ? Object.assign({}, text, { runs: [Object.assign({}, r, { text: fn(r.text) })] }) : null;
  2555. }
  2556. }
  2557. return null;
  2558. }
  2559.  
  2560. const fixCommentReplyDialogRenderer = (commentReplyDialogRenderer, funcPromises) => {
  2561. if (!commentReplyDialogRenderer) return;
  2562. const editableText = commentReplyDialogRenderer.editableText;
  2563. if (!editableText) return;
  2564. const editableTexts = editableText.runs;
  2565. if (editableTexts && editableTexts.length >= 1) {
  2566. for (let aidx = 0; aidx < editableTexts.length; aidx++) {
  2567. const r = editableTextProcess(commentReplyDialogRenderer, editableTexts, aidx);
  2568. if (r instanceof Promise) funcPromises.push(r);
  2569. }
  2570. }
  2571. // $0.polymerController.$['action-buttons'].polymerController.__data.replyButtonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer.editableText
  2572. }
  2573.  
  2574. const domCheckAsync = isMobile ? async (anchor, hrefAttribute, mt) => {
  2575.  
  2576. let sHandleName = null;
  2577. let sNodeValue = null;
  2578. try {
  2579. if (!hrefAttribute || !mt) return;
  2580. let parentNode = nodeParent(anchor);
  2581. while (parentNode instanceof Node) {
  2582. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  2583. parentNode = nodeParent(parentNode);
  2584. }
  2585. if (parentNode instanceof Node) { } else return;
  2586.  
  2587. const commentRendererAuthorTextDOM = getDisplayTextDOMForCommentRenderer(parentNode);
  2588. const anchorAiraLabel = anchor.getAttribute('aria-label');
  2589. const anchorHrefValue = ytPathnameExtract(anchor.getAttribute('href')); // guess (Feb 2024)
  2590.  
  2591. const cnt = insp(parentNode);
  2592. const parentNodeData = cnt._commentData || cnt.data || 0;
  2593. const authorTextData = (parentNodeData.authorText || 0);
  2594.  
  2595. let tHandleName = null;
  2596.  
  2597. if (commentRendererAuthorTextDOM && authorTextData) {
  2598. const hType = getHrefType(anchorHrefValue);
  2599. let ytext = null;
  2600. if (hType === 2) {
  2601. tHandleName = anchorHrefValue.substring(1); // guess
  2602. } else if (hType === 1) {
  2603. ytext = getYTextContent(authorTextData)
  2604. tHandleName = ytext; // authorTextData.runs[0].text
  2605. }
  2606. if (typeof tHandleName === 'string' && commentRendererAuthorTextDOM.textContent.trim() === tHandleName && isDisplayAsHandle(tHandleName)) {
  2607. ytext = ytext || getYTextContent(authorTextData)
  2608. if (ytext === tHandleName) {
  2609. sHandleName = tHandleName;
  2610. sNodeValue = tHandleName;
  2611. }
  2612. }
  2613. }
  2614.  
  2615. if (typeof sHandleName === 'string' && typeof sNodeValue === 'string') {
  2616.  
  2617. if (!channelIdToHandle.has(mt)) {
  2618. channelIdToHandle.set(mt, {
  2619. handleText: sHandleName,
  2620. justPossible: true
  2621. });
  2622. }
  2623.  
  2624. const fetchResult = await getDisplayName(mt);
  2625.  
  2626. if (fetchResult === null) return;
  2627.  
  2628. const { title, langTitle, externalId } = fetchResult;
  2629. const titleForDisplay = langTitle || title;
  2630. if (externalId !== mt) return; // channel id must be the same
  2631.  
  2632. // anchor href might be changed by external
  2633. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2634.  
  2635. if (commentRendererAuthorTextDOM.isConnected !== true) return; // already removed
  2636.  
  2637. let found = false;
  2638.  
  2639. findTextNodes(commentRendererAuthorTextDOM, (textnode) => {
  2640. if (textnode.nodeValue === sNodeValue) {
  2641. textnode.nodeValue = titleForDisplay;
  2642. found = true;
  2643. return true;
  2644. }
  2645. });
  2646.  
  2647. if (!found) return;
  2648. if (anchorAiraLabel && anchorAiraLabel.trim() === sHandleName) anchor.setAttribute('aria-label', anchorAiraLabel.replace(sHandleName, titleForDisplay));
  2649. const authorTextDataNew = setYTextContent(authorTextData, (t) => t.replace(t.trim(), titleForDisplay));
  2650. if (authorTextDataNew && parentNodeData.authorText === authorTextData) {
  2651. parentNodeData.authorText = authorTextDataNew;
  2652. }
  2653.  
  2654. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  2655. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  2656. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  2657. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  2658. const tc = spanText ? spanText.textContent : '';
  2659. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  2660. let idx;
  2661. if (tc && tc === spanText.textContent && (idx = tc.indexOf(title)) >= 0) {
  2662. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  2663. }
  2664. }
  2665.  
  2666. const contentTexts = (parentNodeData.contentText || 0).runs;
  2667. if (contentTexts && contentTexts.length >= 2) {
  2668. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  2669. const contentText = contentTexts[aidx] || 0;
  2670. if (contentText.italics !== true && isDisplayAsHandle(contentText.text)) {
  2671. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  2672. }
  2673. }
  2674. }
  2675.  
  2676. }
  2677.  
  2678. } catch (e) {
  2679. console.warn(e);
  2680. }
  2681.  
  2682. } : async (anchor, hrefAttribute, mt) => {
  2683.  
  2684. try {
  2685. if (!hrefAttribute || !mt) return;
  2686. let parentNode = nodeParent(anchor);
  2687. let isCommentViewModel = 0;
  2688. while (parentNode instanceof Node) {
  2689. const cnt = insp(parentNode);
  2690. if (typeof cnt.is === 'string') {
  2691. if (cnt.commentEntity && !cnt._propertiesChanged) { isCommentViewModel = 2; break; } // 2024.04.30: ytd-comment-view-model (v3)
  2692. if (cnt.commentEntity && typeof cnt._propertiesChanged === 'function') { isCommentViewModel = 1; break; } // Feb 2024: ytd-comment-view-model (v1 & v2)
  2693. else if (typeof cnt.dataChanged === 'function') break;
  2694. }
  2695. parentNode = nodeParent(parentNode);
  2696. }
  2697. if (parentNode instanceof Node) { } else return;
  2698. const parentNodeController = insp(parentNode);
  2699.  
  2700. if (isCommentViewModel > 0) {
  2701.  
  2702. const commentEntity = parentNodeController.commentEntity || 0;
  2703. const commentEntityAuthor = commentEntity.author || 0;
  2704. const currentDisplayed = commentEntityAuthor.displayName || 0;
  2705. if (typeof currentDisplayed !== 'string') return;
  2706. if (!isDisplayAsHandle(currentDisplayed)) return;
  2707. if (!channelIdToHandle.has(mt)) {
  2708. channelIdToHandle.set(mt, {
  2709. handleText: currentDisplayed.trim(),
  2710. justPossible: true
  2711. });
  2712. }
  2713.  
  2714. // not working for CommentViewModel v3
  2715. if (typeof parentNodeController._propertiesChanged === 'function' && !parentNodeController._propertiesChanged159) {
  2716. const cntp = parentNodeController.constructor.prototype;
  2717. const c = cntp._propertiesChanged === parentNodeController._propertiesChanged ? cntp : parentNodeController;
  2718. c._propertiesChanged159 = c._propertiesChanged;
  2719. c._propertiesChanged = function () {
  2720. resetWhenPropChanged(this);
  2721. return this._propertiesChanged159.apply(this, arguments);
  2722. };
  2723. }
  2724.  
  2725. const fetchResult = await getDisplayName(mt);
  2726.  
  2727. if (fetchResult === null) return;
  2728.  
  2729. const { title, langTitle, externalId } = fetchResult;
  2730. const titleForDisplay = langTitle || title;
  2731. if (externalId !== mt) return; // channel id must be the same
  2732.  
  2733. // anchor href might be changed by external
  2734. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2735.  
  2736. if (commentEntityAuthor.displayName === currentDisplayed && commentEntityAuthor.channelId === mt) {
  2737. commentEntityAuthor.displayName = titleForDisplay;
  2738.  
  2739. if (commentEntity.properties) {
  2740. if (commentEntity.properties.authorButtonA11y === currentDisplayed) {
  2741. commentEntity.properties.authorButtonA11y = titleForDisplay;
  2742. }
  2743.  
  2744. // the inside hyperlinks will be only converted if its parent author name is handle
  2745. const content = commentEntity.properties.content;
  2746. if (content && (content.commandRuns || 0).length >= 1) {
  2747. try {
  2748. await contentTextProcessViewModel(content);
  2749.  
  2750. // $0.polymerController.commentEntity = Object.assign({}, $0.polymerController.commentEntity , { properties: Object.assign({}, $0.polymerController.commentEntity.properties, { content: Object.assign({},$0.polymerController.commentEntity.properties.content) } )})
  2751.  
  2752. // parentNodeController.commentEntity.properties = Object.assign({}, parentNodeController.commentEntity.properties, {
  2753. // content: Object.assign({}, parentNodeController.commentEntity.properties.content)
  2754. // });
  2755.  
  2756. commentEntity.properties.content = Object.assign({}, content);
  2757. } catch (e) {
  2758. console.log(e);
  2759. }
  2760.  
  2761. }
  2762.  
  2763. }
  2764.  
  2765. if (commentEntityAuthor && parentNodeController.isAttached === true && parentNode.isConnected === true) {
  2766. commentEntityAuthor.jkrgx = 1;
  2767. addCSSRulesIfRequired();
  2768. }
  2769.  
  2770. let commentReplyDialogRenderer;
  2771.  
  2772. const actionButtonsCnt = insp((parentNodeController.$ || 0)['action-buttons'] || 0);
  2773. if (actionButtonsCnt) {
  2774.  
  2775. try {
  2776. commentReplyDialogRenderer = actionButtonsCnt.__data.replyButtonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  2777. } catch (e) { }
  2778. }
  2779. const funcPromises = [];
  2780. commentReplyDialogRenderer && fixCommentReplyDialogRenderer(commentReplyDialogRenderer, funcPromises);
  2781.  
  2782.  
  2783. if (funcPromises.length >= 1) {
  2784. await Promise.all(funcPromises);
  2785. }
  2786.  
  2787. parentNodeController.commentEntity = Object.assign({}, parentNodeController.commentEntity);
  2788.  
  2789. }
  2790. } else {
  2791.  
  2792. const authorText = (parentNodeController.data || 0).authorText;
  2793. const currentDisplayed = getYTextContent(authorText || 0); // authorText.simpleText
  2794. if (typeof currentDisplayed !== 'string') return;
  2795. if (!isDisplayAsHandle(currentDisplayed)) return;
  2796.  
  2797. if (!channelIdToHandle.has(mt)) {
  2798. channelIdToHandle.set(mt, {
  2799. handleText: currentDisplayed.trim(),
  2800. justPossible: true
  2801. });
  2802. }
  2803.  
  2804. if (typeof parentNodeController.dataChanged === 'function' && !parentNodeController.dataChanged159) {
  2805. const cntp = parentNodeController.constructor.prototype;
  2806. const c = cntp.dataChanged === parentNodeController.dataChanged ? cntp : parentNodeController;
  2807. c.dataChanged159 = c.dataChanged;
  2808. c.dataChanged = function () {
  2809. resetWhenDataChanged(this);
  2810. return this.dataChanged159.apply(this, arguments);
  2811. };
  2812. }
  2813.  
  2814. const fetchResult = await getDisplayName(mt);
  2815.  
  2816. if (fetchResult === null) return;
  2817.  
  2818. const { title, langTitle, externalId } = fetchResult;
  2819. const titleForDisplay = langTitle || title;
  2820. if (externalId !== mt) return; // channel id must be the same
  2821.  
  2822. // anchor href might be changed by external
  2823. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2824.  
  2825. const parentNodeData = parentNodeController.data;
  2826. const funcPromises = [];
  2827.  
  2828. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  2829.  
  2830. if (getYTextContent(authorText) !== currentDisplayed) return;
  2831. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  2832. const cSimpleText = (getYTextContent(parentNodeData.authorText || 0) || '');
  2833. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  2834.  
  2835. const md = Object.assign({}, parentNodeData);
  2836.  
  2837. // the inside hyperlinks will be only converted if its parent author name is handle
  2838. const contentTexts = (md.contentText || 0).runs;
  2839. if (contentTexts && contentTexts.length >= 1) {
  2840. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  2841. const r = contentTextProcess(md, contentTexts, aidx);
  2842. if (r instanceof Promise) funcPromises.push(r);
  2843. }
  2844. }
  2845.  
  2846. const authorCommentBadgeAuthorText = (((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0);
  2847.  
  2848. const authorCommentBadgeAuthorTextNew = authorCommentBadgeAuthorText ? setYTextContent(authorCommentBadgeAuthorText, (currentText) => {
  2849. if ((currentText || '').trim() === cSimpleText.trim()) {
  2850. return (currentText || '').replace((currentText || '').trim(), titleForDisplay);
  2851. } else {
  2852. return currentText;
  2853. }
  2854. }) : null;
  2855.  
  2856. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  2857. const authorTextNew = setYTextContent(md.authorText, (t) => t.replace(currentDisplayTrimmed, titleForDisplay))
  2858. md.authorText = authorTextNew;
  2859.  
  2860. if (authorCommentBadgeAuthorTextNew) {
  2861. const authorCommentBadgeRendererNew = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer, { authorText: authorCommentBadgeAuthorTextNew });
  2862. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge, { authorCommentBadgeRenderer: authorCommentBadgeRendererNew });
  2863. }
  2864.  
  2865. let setReplyEditableText = false;
  2866. if (((((((((parentNodeData.actionButtons || 0).commentActionButtonsRenderer || 0).replyButton || 0).buttonRenderer || 0).navigationEndpoint || 0).createCommentReplyDialogEndpoint || 0).dialog || 0).commentReplyDialogRenderer || 0).editableText) {
  2867. setReplyEditableText = true;
  2868. }
  2869. if (setReplyEditableText) {
  2870. const commentReplyDialogRenderer = parentNodeData.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  2871. fixCommentReplyDialogRenderer(commentReplyDialogRenderer, funcPromises);
  2872.  
  2873. }
  2874.  
  2875. if (UPDATE_PIN_NAME) {
  2876. updatePinnedCommentBadge(md, title, langTitle);
  2877. }
  2878.  
  2879. if (funcPromises.length >= 1) {
  2880. await Promise.all(funcPromises);
  2881. }
  2882.  
  2883. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  2884. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  2885. addCSSRulesIfRequired();
  2886. }
  2887.  
  2888.  
  2889. }
  2890.  
  2891. }
  2892. }
  2893. } catch (e) {
  2894. console.warn(e);
  2895. }
  2896.  
  2897. }
  2898.  
  2899. /**
  2900. *
  2901. * @param {string} url
  2902. * @returns
  2903. */
  2904. const channelUrlUnify = (url) => {
  2905.  
  2906. if (typeof url !== 'string') return url; // type unchanged
  2907. let c0 = url.charAt(0);
  2908. if (c0 === '/') return url;
  2909. let i = url.indexOf('.youtube.com/');
  2910. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  2911. else if (url.charAt(0) !== '/') url = '/' + url;
  2912. return url
  2913.  
  2914. }
  2915.  
  2916. const parentYtElement = (node, nodeName, maxN) => {
  2917. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  2918. if (pDom.nodeName === nodeName) {
  2919. return pDom;
  2920. }
  2921. }
  2922. return null;
  2923. }
  2924.  
  2925. const checkShortsChannelName = (rchannelNameDOM) => {
  2926. let browseId = '';
  2927. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  2928.  
  2929. if (pDom instanceof HTMLElement) {
  2930. const pDomController = insp(pDom);
  2931. const channelTitleText = (pDomController.data || 0).channelTitleText || 0;
  2932. const runs = ((channelTitleText || 0).runs || 0);
  2933. if (getYTextType(channelTitleText) === 4) {
  2934. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  2935. browseId = (browserEndpoint.browseId || '');
  2936. const currentDisplayText = runs[0].text || ''
  2937.  
  2938. if (isUCBrowserId(browseId) && isDisplayAsHandle(currentDisplayText)) {
  2939.  
  2940. if (!channelIdToHandle.has(browseId)) {
  2941. channelIdToHandle.set(browseId, {
  2942. handleText: currentDisplayText.trim(),
  2943. justPossible: true
  2944. });
  2945. }
  2946.  
  2947. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  2948. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  2949. // anchorNode &&
  2950. getDisplayName(browseId).then(fetchResult => {
  2951.  
  2952. if (fetchResult === null) return;
  2953.  
  2954. const { title, langTitle, externalId } = fetchResult;
  2955. const titleForDisplay = langTitle || title;
  2956. if (externalId !== browseId) return; // channel id must be the same
  2957.  
  2958. const hDom = pDom;
  2959. const hDomHostElement = hDom.hostElement || hDom;
  2960. const hDomController = insp(hDom);
  2961. const hData = (hDomController || 0).data || 0;
  2962. const hChannelTitleText = (hData || 0).channelTitleText || 0;
  2963. const runs = ((hChannelTitleText).runs || 0);
  2964. if (getYTextType(hChannelTitleText) === 4 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  2965.  
  2966. const channelTitleTextNew = { runs: [Object.assign({}, runs[0], { text: titleForDisplay })] }
  2967.  
  2968. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: channelTitleTextNew, rSk0e: 1 });
  2969. addCSSRulesIfRequired();
  2970.  
  2971. byPassCheckStore.delete(rchannelNameDOM);
  2972. }
  2973.  
  2974. })
  2975. }
  2976.  
  2977. }
  2978. }
  2979. return browseId
  2980. }
  2981.  
  2982. let firstDOMCheck = false;
  2983. const updateDisplayNameFn = (channelId, newName) => {
  2984. const cached = displayNameResStore.get(channelId);
  2985. if (typeof (cached || 0).title === 'string') {
  2986. cached.title = newName;
  2987. } else if (!cached) {
  2988. displayNameResStore.set(channelId, {
  2989. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  2990. externalId: `${channelId}`,
  2991. ownerUrls: [],
  2992. title: newName,
  2993. vanityChannelUrl: null,
  2994. verified123: true
  2995. });
  2996. } else {
  2997. console.warn('unexpected display name cache', cached);
  2998. }
  2999. };
  3000. const firstDOMChecker = isMobile ? () => {
  3001.  
  3002. let playerMicroformatRenderer = null;
  3003. try {
  3004. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  3005. } catch (e) { }
  3006. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  3007. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  3008. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  3009. }
  3010.  
  3011. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  3012. const channelNameCData = !channelNameDOM ? null : insp(channelNameDOM).data;
  3013.  
  3014. if (channelNameCData) {
  3015. let mainChannelUrl = null;
  3016. let mainFormattedNameUrl = null;
  3017. let mainChannelText = null;
  3018. let mainFormattedNameText = null;
  3019. let mainChannelBrowseId = null;
  3020.  
  3021. try {
  3022. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl) // channelUrlUnify("http://www.youtube.com/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  3023. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl) // channelUrlUnify("/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  3024. mainChannelText = channelNameCData.channelName
  3025. mainFormattedNameText = channelNameCData.title.runs[0].text
  3026. mainChannelBrowseId = channelNameCData.navigationEndpoint.browseEndpoint.browseId;
  3027. } catch (e) { }
  3028.  
  3029. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  3030.  
  3031. const channelId = mainChannelBrowseId;
  3032. if (channelId) {
  3033. if (mainChannelText.startsWith('@')) return;
  3034. if (mainChannelText.trim() !== mainChannelText) return;
  3035. updateDisplayNameFn(channelId, mainChannelText);
  3036. }
  3037.  
  3038.  
  3039. }
  3040. }
  3041.  
  3042. } : () => {
  3043.  
  3044. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  3045. const channelNameCnt = insp(channelNameDOM);
  3046. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  3047. if (channelNameCData) {
  3048. let mainChannelUrl = null;
  3049. let mainFormattedNameUrl = null;
  3050. let mainChannelText = null;
  3051. let mainFormattedNameText = null;
  3052. let mainChannelBrowseId = null;
  3053. try {
  3054. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  3055. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  3056. mainChannelText = channelNameCData.channelName.runs[0].text
  3057. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  3058. mainChannelBrowseId = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.browseId;
  3059. } catch (e) { }
  3060.  
  3061. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  3062.  
  3063. const m = exactHandleUrl(mainChannelUrl, false);
  3064.  
  3065. if (m && mainChannelText !== m) {
  3066.  
  3067. const channelHandle = m[1];
  3068. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  3069. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  3070. }
  3071.  
  3072. } else {
  3073.  
  3074. const channelId = mainChannelBrowseId;
  3075. if (channelId) {
  3076. if (mainChannelText.startsWith('@')) return;
  3077. if (mainChannelText.trim() !== mainChannelText) return;
  3078. updateDisplayNameFn(channelId, mainChannelText);
  3079. }
  3080.  
  3081. }
  3082. }
  3083. }
  3084.  
  3085. };
  3086.  
  3087. // let newAnchorAdded = false;
  3088. /*
  3089.  
  3090. const intersectionobserver = new IntersectionObserver((entries) => {
  3091. let anchorAppear = false;
  3092. for (const entry of entries) {
  3093. if (entry.isIntersecting === true) {
  3094. anchorAppear = true;
  3095. break;
  3096. }
  3097. }
  3098. if (anchorAppear && newAnchorAdded) {
  3099. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  3100. mutex.nextIndex = 0; // higher pirority for new elements being shown
  3101. }
  3102. }, {
  3103. rootMargin:"0px 0px 0px 0px",
  3104. threshold:1
  3105. })
  3106. */
  3107.  
  3108.  
  3109. /* globals WeakRef:false */
  3110.  
  3111. /** @type {(o: Object | null) => WeakRef | null} */
  3112. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  3113.  
  3114. /** @type {(wr: Object | null) => Object | null} */
  3115. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  3116.  
  3117. let doShortsChecking = false;
  3118. let doDescriptionChecking = true;
  3119.  
  3120. let lastNewAnchorLastWR = null;
  3121.  
  3122. const pipelineForDOMMutations = createPipeline();
  3123.  
  3124. const byPassCheckStore = new WeakSet();
  3125.  
  3126. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  3127. for (const mutation of mutations) {
  3128. const target = mutation.target;
  3129. if (!target) continue;
  3130. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  3131. if (!rchannelNameElm) continue;
  3132. const rchannelNameCnt = insp(rchannelNameElm);
  3133. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  3134. const channelId = rchannelNameElm.getAttribute('jkrgy');
  3135. if (channelId) {
  3136. if (byPassCheckStore.has(rchannelNameElm)) continue;
  3137. const handleObj = channelIdToHandle.get(channelId);
  3138. if (handleObj && handleObj.handleText && !handleObj.justPossible) {
  3139. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  3140. if (textDom) {
  3141. let t = textDom.textContent.trim()
  3142. if (t === handleObj.handleText || t === '') {
  3143. rchannelNameElm.removeAttribute('jkrgy');
  3144. // Promise.resolve().then(domChecker);
  3145. }
  3146. }
  3147. }
  3148. }
  3149. }
  3150. });
  3151.  
  3152. let domCheckScheduledForShorts = false;
  3153. const domCheckSelectorForShorts = [
  3154. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  3155. ].join(', ');
  3156.  
  3157.  
  3158. const domCheckerForShorts = async () => {
  3159.  
  3160. if (domCheckScheduledForShorts) return;
  3161. if (document.querySelector(domCheckSelectorForShorts) === null) {
  3162. return;
  3163. }
  3164. domCheckScheduledForShorts = true;
  3165.  
  3166. await pipelineForDOMMutations(async () => {
  3167.  
  3168. domCheckScheduledForShorts = false;
  3169. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  3170.  
  3171. try {
  3172.  
  3173. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  3174. if (nodes.length === 0) {
  3175. return;
  3176. }
  3177.  
  3178. for (const node of nodes) {
  3179.  
  3180. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  3181. if (rchannelNameElm) {
  3182. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  3183. childList: true,
  3184. subtree: true
  3185. });
  3186. byPassCheckStore.add(rchannelNameElm);
  3187. const channelId = checkShortsChannelName(rchannelNameElm);
  3188. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  3189. }
  3190.  
  3191. }
  3192.  
  3193. } catch (e) {
  3194. console.log('error occur', e);
  3195. }
  3196.  
  3197. });
  3198. domCheckScheduledForShorts = false;
  3199.  
  3200. };
  3201.  
  3202. /** @param {Element} s */
  3203. const domCheckerForDescriptionAnchor = (s) => {
  3204.  
  3205. findTextNodes(s, (textNode) => {
  3206. const p = textNode.nodeValue;
  3207. const index = p.indexOf('@');
  3208. if (index < 0) return;
  3209. const q = p.substring(index);
  3210. const b = isDisplayAsHandle(q);
  3211. if (b) {
  3212. const href = s.getAttribute('href')
  3213.  
  3214. const channelId = obtainChannelId(href);
  3215. if (channelId) {
  3216. const h = q.trim();
  3217.  
  3218. if (!firstDOMCheck) {
  3219. firstDOMCheck = true;
  3220. USE_CHANNEL_META && firstDOMChecker();
  3221. }
  3222.  
  3223. if (!channelIdToHandle.has(channelId)) {
  3224. channelIdToHandle.set(channelId, {
  3225. handleText: h,
  3226. justPossible: true
  3227. });
  3228. }
  3229.  
  3230. s.setAttribute('jkrgy', channelId);
  3231. getDisplayName(channelId).then(fetchResult => {
  3232.  
  3233. if (fetchResult === null) return;
  3234.  
  3235. const { title, langTitle, externalId } = fetchResult;
  3236. const titleForDisplay = langTitle || title;
  3237. if (externalId !== channelId) return; // channel id must be the same
  3238.  
  3239. const anchorElement = s;
  3240. const anchorTextNode = textNode;
  3241.  
  3242. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  3243.  
  3244. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  3245.  
  3246. }
  3247.  
  3248. });
  3249. }
  3250. }
  3251. return true;
  3252. });
  3253.  
  3254. }
  3255.  
  3256. // domCheckerForDescription: To be reviewed
  3257. // Example: https://www.youtube.com/watch?v=1NL-sIP9p_U
  3258. const domCheckerForDescription = isMobile ? () => {
  3259. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  3260. for (const s of document.querySelectorAll('span.yt-core-attributed-string a.yt-core-attributed-string__link.yt-core-attributed-string__link--display-type.yt-core-attributed-string__link--call-to-action-color[href*="channel/"]:not([dxcpj])')) {
  3261. s.setAttribute('dxcpj', '');
  3262. domCheckerForDescriptionAnchor(s);
  3263. }
  3264. } : () => {
  3265. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  3266. for (const s of document.querySelectorAll('yt-attributed-string a.yt-core-attributed-string__link.yt-core-attributed-string__link--display-type.yt-core-attributed-string__link--call-to-action-color[href*="channel/"]:not([dxcpj])')) {
  3267. s.setAttribute('dxcpj', '');
  3268. domCheckerForDescriptionAnchor(s);
  3269. }
  3270. };
  3271.  
  3272. const domCheckScheduledBools = [];
  3273. const domCheckScheduledSelectors = isMobile ? [
  3274. 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  3275. 'a.comment-icon-container[href*="/@"]:not([jkrgy])', // Feb 2024
  3276. 'a.comment-icon-container[href*="channel/"]:not([jkrgy])' // Mar 2024
  3277. ] : [
  3278. 'a[id][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  3279. 'a.yt-simple-endpoint.style-scope[id][href^="/@"]:not([jkrgy])', // Feb 2024
  3280. 'a.yt-simple-endpoint.style-scope[id][href^="http://www.youtube.com/@"]:not([jkrgy])' // Dec 2024
  3281. ];
  3282.  
  3283. const newAuthorAnchorsProceed = async (newAnchors) => {
  3284.  
  3285. const cNewAnchorFirst = newAnchors[0]; // non-null
  3286. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  3287. /** @type {HTMLElement | null} */
  3288. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  3289. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  3290.  
  3291. if (!firstDOMCheck) {
  3292. firstDOMCheck = true;
  3293. USE_CHANNEL_META && firstDOMChecker();
  3294. }
  3295.  
  3296. await Promise.resolve();
  3297.  
  3298. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  3299. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  3300. mutex.nextIndex = 0;
  3301. }
  3302. await Promise.resolve();
  3303. }
  3304.  
  3305. // newAnchorAdded = true;
  3306. for (const anchor of newAnchors) {
  3307. const hrefAttribute = anchor.getAttribute('href');
  3308. const hrefV = ytPathnameExtract(hrefAttribute);
  3309. let mChannelId = '';
  3310. const ytElm = isMobile ? closestYtmData(anchor) : closestYtParent(anchor);
  3311. if (ytElm) {
  3312. const cnt = insp(ytElm);
  3313. const { browseId, canonicalBaseUrl } = getAuthorBrowseEndpoint(cnt) || 0;
  3314. let wChannelId = '';
  3315. if (!browseId && !canonicalBaseUrl && cnt) {
  3316. // Dec 2024; no browserEndPoint -> urlEndpoint -> channelId not available
  3317. // comment view model -> commentEntity.author.channelId
  3318. const author = ((cnt.__data || cnt.data || 0).commentEntity || 0).author || 0;
  3319. if (author) {
  3320. const { channelId } = author;
  3321. const innertubeCommand = ((author || 0).channelPageEndpoint || 0).innertubeCommand || 0;
  3322. const endpoint = innertubeCommand.browseEndpoint || innertubeCommand.urlEndpoint || author.browseEndpoint || browseEndpoint.urlEndpoint || 0;
  3323. const url = endpoint.canonicalBaseUrl || endpoint.url || 0;
  3324. if (channelId && ytPathnameExtract(url) === hrefV && channelId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(channelId)) {
  3325. wChannelId = channelId;
  3326. }
  3327. }
  3328. } else if (browseId && ytPathnameExtract(canonicalBaseUrl) === hrefV && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId)) {
  3329. wChannelId = browseId;
  3330. }
  3331.  
  3332. if (wChannelId) {
  3333.  
  3334. const hrefType = getHrefType(hrefV);
  3335. // console.log(599, hrefV, hrefType)
  3336. if (hrefType === 1) {
  3337. if (hrefV === `/channel/${wChannelId}`) {
  3338. let authorText = null;
  3339. if (isMobile) { // mobile only
  3340. authorText = (cnt._commentData || cnt.data || ytElm._commentData || ytElm.data || 0).authorText || 0;
  3341. } else if (!isMobile) {
  3342. authorText = (cnt.data || 0).authorText || 0;
  3343. }
  3344. if (authorText) {
  3345. const text = getYTextContent(authorText);
  3346. if (typeof text === 'string' && text.startsWith('@') && exactHandleText(text, true)) {
  3347. channelIdToHandle.set(wChannelId, {
  3348. handleText: `${text}`,
  3349. justPossible: true
  3350. });
  3351. }
  3352. }
  3353. mChannelId = wChannelId;
  3354. }
  3355. } else if (hrefType === 2) {
  3356. const handle = hrefV.substring(2);
  3357. channelIdToHandle.set(wChannelId, {
  3358. handleText: `@${handle}`
  3359. });
  3360. mChannelId = wChannelId;
  3361. }
  3362.  
  3363. }
  3364.  
  3365. if (!mChannelId && hrefV) { // fallback
  3366.  
  3367. // author-text or name
  3368. // normal url: /channel/xxxxxxx
  3369. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  3370.  
  3371. const temp = obtainChannelId(hrefV); // string, can be empty
  3372. if (temp) {
  3373. mChannelId = temp;
  3374. }
  3375.  
  3376. }
  3377. }
  3378. anchor.setAttribute('jkrgy', mChannelId);
  3379. if (mChannelId) {
  3380. domCheckAsync(anchor, hrefAttribute, mChannelId);
  3381. }
  3382. }
  3383.  
  3384. }
  3385.  
  3386. const closestYtParent = (dom) => {
  3387. while (dom instanceof Element) {
  3388. if (typeof dom.is === 'string' && dom.is) return dom;
  3389. dom = dom.parentNode;
  3390. }
  3391. return null;
  3392. };
  3393. const closestYtmData = (dom) => {
  3394. while (dom instanceof Element) {
  3395. if (typeof (dom._commentData || dom.data || 0) === 'object') return dom;
  3396. dom = dom.parentNode;
  3397. }
  3398. return null;
  3399. };
  3400. /*
  3401. const cntWithParent = (cnt, parentSelector) => {
  3402. const hostElement = cnt.hostElement || cnt;
  3403. if (hostElement instanceof HTMLElement) {
  3404. return hostElement.closest(parentSelector);
  3405. }
  3406. return null;
  3407. }
  3408. */
  3409. const noAuthorDataSet = new Set();
  3410. const getAuthorBrowseEndpoint = (cnt) => {
  3411. let d;
  3412. let haveData = false;
  3413. if (isMobile) {
  3414. const data = ((cnt || 0).data || 0);
  3415. if (data) {
  3416. haveData = true;
  3417. if (d = (data.authorNameEndpoint || data.authorEndpoint)) return d.browseEndpoint || null;
  3418. }
  3419. } else {
  3420. const __data = ((cnt || 0).__data || 0);
  3421. if (__data) {
  3422. haveData = true;
  3423. if (d = __data.authorTextCommand) return d.browseEndpoint || null; // ytd-comment-renderer
  3424. if (d = (__data.authorNameEndpoint || __data.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (v1 & v2)
  3425. if ((d = (__data.data || 0)) && (d = (d.authorNameEndpoint || d.authorEndpoint))) return d.browseEndpoint || null; // ytd-author-comment-badge-renderer
  3426. // note: authorNameEndpoint instead of authorEndpoint for ytd-comment-view-model since 2024.04
  3427.  
  3428. } else {
  3429.  
  3430. if ((d = ((cnt || 0).data || 0)) && (d = (d.authorTextCommand || d.authorNameEndpoint || d.authorEndpoint))) return d.browseEndpoint || null; // ytd-comment-view-model (2024.05.25 ?)
  3431.  
  3432. if (d = (cnt.authorTextCommand || cnt.authorNameEndpoint || cnt.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (2024.04.30) (v3) (?)
  3433.  
  3434. }
  3435.  
  3436. }
  3437. if (haveData) {
  3438. const tag = cnt.is;
  3439. if (!noAuthorDataSet.has(tag)) {
  3440. noAuthorDataSet.add(tag);
  3441. if (tag === 'ytd-video-description-infocards-section-renderer') {
  3442. return null; // skip console logging
  3443. } else if (tag === 'ytd-thumbnail') {
  3444. return null;
  3445. } else if (tag === 'ytd-structured-description-channel-lockup-renderer') {
  3446. return null;
  3447. } else if (tag === 'ytd-rich-grid-media') {
  3448. return null;
  3449. } else if (tag === 'ytd-rich-metadata-renderer') {
  3450. return null;
  3451. } else if (tag === 'ytd-guide-entry-renderer') {
  3452. return null;
  3453. } else if (tag === 'ytd-grid-channel-renderer') {
  3454. return null;
  3455. } else if (tag === 'ytd-channel-renderer') {
  3456. return null;
  3457. }
  3458. console.log('no browseEndpoint can be found', tag);
  3459. }
  3460. } else {
  3461. console.log('no browseEndpoint can be found', (cnt || 0).is, 'NO DATA');
  3462. }
  3463. return null;
  3464. };
  3465.  
  3466. const domAuthorNameCheckN = async (kq) => {
  3467. if (domCheckScheduledBools[kq]) return;
  3468. const selector = domCheckScheduledSelectors[kq];
  3469. if (!selector || document.querySelector(selector) === null) return;
  3470. domCheckScheduledBools[kq] = true;
  3471. await pipelineForDOMMutations(async () => {
  3472. domCheckScheduledBools[kq] = false;
  3473. try {
  3474. const newAnchors = document.querySelectorAll(selector);
  3475. if (newAnchors.length === 0) return;
  3476. await newAuthorAnchorsProceed(newAnchors);
  3477. } catch (e) {
  3478. console.log('error occur', e);
  3479. }
  3480. });
  3481. domCheckScheduledBools[kq] = false;
  3482. };
  3483.  
  3484. let _lastAnchorCount = -1;
  3485. const anchorCollection = document.getElementsByTagName('A');
  3486.  
  3487. /*
  3488. const collectionChangeObserverFn = (collection)=>{
  3489. let _len = -1;
  3490. let ws = null;
  3491. ws = new WeakSet(collection);
  3492. return {check: ()=>{
  3493. const lastLen = _len;
  3494. const len = collection.length;
  3495. if(len !== lastLen){
  3496. ws = new WeakSet(collection);
  3497. return true;
  3498. }
  3499. for (const elm of collection) {
  3500. if (!ws.has(elm)){
  3501. ws = new WeakSet(collection);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. }}
  3507.  
  3508. }
  3509. */
  3510.  
  3511. const domChecker = (mutations) => {
  3512.  
  3513. const currAnchorCount = anchorCollection.length;
  3514. const lastAnchorCount = _lastAnchorCount;
  3515. _lastAnchorCount = currAnchorCount;
  3516. if (currAnchorCount === 0) return;
  3517.  
  3518. if (mutations && lastAnchorCount === currAnchorCount) {
  3519. // test to skip
  3520. let state = 0;
  3521. let addedNonElement = false;
  3522. for (const mutation of mutations) {
  3523. const addedNodes = mutation.addedNodes || 0;
  3524. const removedNodes = mutation.removedNodes || 0;
  3525. const target = mutation.target || 0;
  3526. if (target.nodeName === 'YT-FORMATTED-STRING') continue; // ignore changes in <yt-formatted-string>
  3527. if (addedNodes.length >= 1) {
  3528. state |= 1;
  3529. if (!addedNonElement) {
  3530. for (const addedNode of addedNodes) {
  3531. if (!(addedNode instanceof Element)) {
  3532. addedNonElement = true;
  3533. break;
  3534. }
  3535. }
  3536. }
  3537. if (state & 2) break;
  3538. } else if (removedNodes.length >= 1) {
  3539. state |= 2;
  3540. if (state & 1) break;
  3541. } else {
  3542. state |= 4;
  3543. break;
  3544. }
  3545. }
  3546. if (state === 1) {
  3547. if (!addedNonElement) return; // no change in anchor
  3548. } else if (state === 2) {
  3549. return; // only removal
  3550. } else if (state === 0) {
  3551. return; // no recognized mutation
  3552. }
  3553. }
  3554.  
  3555. doShortsChecking && domCheckerForShorts();
  3556. doDescriptionChecking && domCheckerForDescription();
  3557. for (let i = 0; i < domCheckScheduledSelectors.length; i++) domAuthorNameCheckN(i);
  3558.  
  3559. };
  3560.  
  3561.  
  3562. /** @type {MutationObserver | null} */
  3563. let domObserver = null;
  3564.  
  3565. /** @type {(callback: (event: Event)=>{})} */
  3566. const onPageFetched = isMobile ? (callback) => {
  3567.  
  3568. let state = 0;
  3569.  
  3570. window.addEventListener('state-change', function (evt) {
  3571. if (state === 1) return; // ignore intermediate events
  3572. state = 1; // before value: 0 or 2;
  3573. callback(evt);
  3574. }, false);
  3575.  
  3576. window.addEventListener('state-navigateend', function (evt) { // fallback
  3577. let inSeq = state === 1;
  3578. state = 2; // 2 when loaded
  3579. if (!inSeq) callback(evt);
  3580. }, false);
  3581.  
  3582. } : (callback) => {
  3583.  
  3584. let state = 0;
  3585.  
  3586. document.addEventListener('yt-page-data-fetched', function (evt) {
  3587. if (state === 1) return; // ignore intermediate events if any
  3588. state = 1; // before value: 0 or 2;
  3589. callback(evt);
  3590. }, false);
  3591.  
  3592. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  3593. let inSeq = state === 1;
  3594. state = 2; // 2 when loaded
  3595. if (!inSeq) callback(evt);
  3596. }, false);
  3597.  
  3598. };
  3599.  
  3600.  
  3601. // let mActive = false;
  3602. // let lastContent = '';
  3603. const removeAttrs = () => {
  3604. for (const s of document.querySelectorAll('a[href][dxcpj]')) {
  3605. s.removeAttribute('dxcpj');
  3606. }
  3607. for (const s of document.querySelectorAll('a[href][jkrgy]')) {
  3608. s.removeAttribute('jkrgy');
  3609. }
  3610. }
  3611.  
  3612. // setInterval(() => {
  3613. // if (!mActive) return;
  3614. // let content = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  3615. // if (content !== lastContent) {
  3616. // lastContent = content;
  3617. // removeAttrs();
  3618. // }
  3619. // }, 400);
  3620.  
  3621. /**
  3622. *
  3623. * @param {Node} app
  3624. * @returns
  3625. */
  3626. function setupOnPageFetched(app) {
  3627.  
  3628. firstDOMCheck = false;
  3629.  
  3630. if (!cfg['INNERTUBE_API_KEY']) {
  3631. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  3632. return;
  3633. }
  3634.  
  3635. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  3636. doShortsChecking = true;
  3637. } else {
  3638. doShortsChecking = false;
  3639. }
  3640.  
  3641. _lastAnchorCount = -1;
  3642.  
  3643. if (!domObserver) {
  3644. domObserver = new MutationObserver(domChecker);
  3645. } else {
  3646. domObserver.takeRecords();
  3647. domObserver.disconnect();
  3648. }
  3649.  
  3650. // lastContent = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  3651. // mActive = true;
  3652. removeAttrs();
  3653.  
  3654. domObserver.observe(app, { childList: true, subtree: true, attributes: true, attributeFilter: ['jkrgy', 'href', 'dxcpj'] });
  3655. domChecker();
  3656.  
  3657. }
  3658.  
  3659. /**
  3660. *
  3661. * @param {Object|null} dest
  3662. * @param {Object} ytcfg
  3663. * @param {string[]} keys
  3664. * @returns
  3665. */
  3666. function getYtConfig(dest, ytcfg, keys) {
  3667. dest = dest || {};
  3668. if (typeof ytcfg.get === 'function') { // mobile
  3669. for (const key of keys) {
  3670. dest[key] = ytcfg.get(key);
  3671. }
  3672. } else {
  3673. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  3674. for (const key of keys) {
  3675. dest[key] = cfgData[key];
  3676. }
  3677. }
  3678. return dest;
  3679. }
  3680.  
  3681. /** @type { (evt: Object) => Element | null } */
  3682. const getPageApp = isMobile
  3683. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  3684. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  3685.  
  3686. onPageFetched(async (evt) => {
  3687. const app = getPageApp(evt);
  3688. console.assert(app);
  3689. const ytcfg = ((window || 0).ytcfg || 0);
  3690. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  3691. setupOnPageFetched(app);
  3692. });
  3693.  
  3694. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });