Restore YouTube Username from Handle to Custom

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

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

  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.5
  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. function createHTML(s) {
  191. if (typeof TTP !== 'undefined' && typeof TTP.createHTML === 'function') return TTP.createHTML(s);
  192. return s;
  193. }
  194.  
  195. let trustHTMLErr = null;
  196. try {
  197. document.createElement('div').innerHTML = createHTML('1');
  198. } catch (e) {
  199. trustHTMLErr = e;
  200. }
  201.  
  202. if (trustHTMLErr) {
  203. console.log(`trustHTMLErr`, trustHTMLErr);
  204. trustHTMLErr(); // exit userscript
  205. }
  206.  
  207.  
  208. // -----------------------------------------------------------------------------------------------------------------------------
  209.  
  210. /* jshint esversion:8 */
  211.  
  212. /**
  213. @typedef {string} HandleText
  214. * \@[-_a-zA-Z0-9.]{3,30} (before May 2024)
  215. * See isDisplayAsHandle
  216. */
  217.  
  218. /**
  219. @typedef {string} ChannelId
  220. * UC[-_a-zA-Z0-9+=.]{22}
  221. * https://support.google.com/youtube/answer/6070344?hl=en
  222. * The channel ID is the 24 character alphanumeric string that starts with 'UC' in the channel URL.
  223. */
  224.  
  225. /**
  226. @typedef {string} DisplayName
  227. * Display Name
  228. */
  229.  
  230. /**
  231. @typedef DisplayNameResultObject
  232. @type {Object}
  233. @property {DisplayName} title
  234. @property {DisplayName} langTitle
  235. @property {ChannelId?} externalId
  236. @property {string[]} ownerUrls
  237. @property {string} channelUrl
  238. @property {string} vanityChannelUrl
  239. @property {boolean|undefined} verified123
  240. */
  241.  
  242. /**
  243. @typedef ChannelIdToHandleResult
  244. @type {Object}
  245. @property {HandleText} handleText
  246. @property {boolean} justPossible
  247. */
  248.  
  249. (function (__CONTEXT__) {
  250. 'use strict';
  251.  
  252. // const JUST_REMOVE_AT_FOR_EXPANDED_LANG = true;
  253.  
  254. const USE_RSS_FETCHER = true; // might 404
  255. const USE_TIMEOUT_SIGNAL = false;
  256. const USE_CHANNEL_META = true;
  257. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  258. const USE_LANG_SPECIFIC_NAME = true;
  259. const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
  260. const FIX_RTL_ISSUE = true;
  261.  
  262. const IGNORE_NO_NAME = false;
  263.  
  264. /** @type {globalThis.PromiseConstructor} */
  265. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  266.  
  267. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  268.  
  269. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  270. let controller = new AbortController();
  271. const r = controller.signal;
  272. let cid = setTimeout(() => {
  273. if (cid >= 1) {
  274. cid = 0;
  275. controller && controller.abort();
  276. controller = null;
  277. }
  278. }, timeout);
  279. r.clearTimeout = () => {
  280. if (cid >= 1) {
  281. clearTimeout(cid);
  282. cid = 0;
  283. }
  284. }
  285. return r;
  286. } : () => { };
  287.  
  288. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  289.  
  290. const fxOperator = (proto, propertyName) => {
  291. let propertyDescriptorGetter = null;
  292. try {
  293. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  294. // https://github.com/cyfung1031/userscript-supports/issues/9
  295. // .parentNode becomes DocumentFragment
  296. /**
  297. *
  298. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  299. *
  300. * e.g. ytd-comment-renderer#comment > div#body
  301. *
  302. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  303. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  304. *
  305. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  306. *
  307. * Alternative way: ytCustomElement.$.xxxxxxx
  308. *
  309. */
  310. } catch (e) { }
  311. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  312. };
  313.  
  314. const fxAPI = (proto, propertyName) => {
  315. const methodFunc = proto[propertyName];
  316. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  317. };
  318.  
  319. /** @type { (node: Node)=>Node | null } */
  320. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  321. /** @type { (node: Node)=>Node | null } */
  322. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  323. /** @type { (node: Node)=>Node | null } */
  324. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  325.  
  326. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  327. const elementQS = fxAPI(Element.prototype, 'querySelector');
  328. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  329. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  330.  
  331. /*
  332.  
  333.  
  334. init
  335.  
  336. initialdata
  337. state-progress
  338. state-responsereceived
  339. player-autonav-pause
  340. state-change
  341. state-navigateend
  342. player-initialized
  343. renderer-module-load-start
  344. video-data-change
  345. player-state-change
  346. updateui
  347. renderer-module-load-end -> channel owner DOM available
  348. player-autonav-pause
  349. updateui
  350. renderer-module-load-start
  351. updateui
  352. renderer-module-load-end
  353.  
  354.  
  355. playing
  356.  
  357. h5player.video-progress
  358. h5player.video-progress
  359. h5player.video-progress
  360. h5player.video-progress
  361. ...
  362.  
  363.  
  364.  
  365.  
  366. navigate new video
  367.  
  368. state-navigatestart
  369. state-change => channel owener DOM vanished
  370. state-progress
  371. ...
  372. h5player.player-state-change
  373. h5player.video-data-change
  374. h5player.player-state-change
  375. h5player.muted-autoplay-change
  376. h5player.volume-change
  377. h5player.video-data-change
  378. h5player.volume-change
  379. ...
  380.  
  381. state-progress
  382. ...
  383.  
  384. state-progress => channel owner DOM appear [just before state-responsereceived]
  385. state-responsereceived
  386.  
  387. video-data-change
  388. state-change
  389. state-navigateend
  390.  
  391.  
  392.  
  393.  
  394. UX interaction
  395.  
  396. user-activity
  397. player-autonav-pause
  398.  
  399.  
  400.  
  401.  
  402.  
  403. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  404.  
  405. EventTarget.prototype.dispatchEvent = function (ev) {
  406. if (ev instanceof Event) {
  407. if (ev.type === 'video-progress') { } else {
  408. console.log(ev.type, this, ev.target)
  409. if (ev.target === null) {
  410. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  411. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  412. }
  413. }
  414. }
  415. return this.uhfsE.apply(this, arguments);
  416. }
  417.  
  418.  
  419.  
  420. */
  421.  
  422. const isMobile = location.hostname === 'm.youtube.com';
  423.  
  424. if (!isMobile && typeof AbortSignal !== 'undefined') {
  425. document.addEventListener('yt-action', () => {
  426. try {
  427. yt.config_.EXPERIMENT_FLAGS.enable_profile_cards_on_comments = true;
  428. } catch (e) { }
  429. }, { capture: true, passive: true, once: true })
  430. }
  431.  
  432.  
  433. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  434.  
  435. const { retrieveCE } = isMobile ? (() => {
  436.  
  437. const retrieveCE = () => {
  438. console.warn('retrieveCE is not supported');
  439. }
  440. return { retrieveCE };
  441.  
  442. })() : (() => {
  443.  
  444. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  445.  
  446. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  447. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  448. if (typeof customElements === 'undefined') {
  449. if (!('__CE_registry' in document)) {
  450. // https://github.com/webcomponents/polyfills/
  451. Object.defineProperty(document, '__CE_registry', {
  452. get() {
  453. // return undefined
  454. },
  455. set(nv) {
  456. if (typeof nv == 'object') {
  457. delete this.__CE_registry;
  458. this.__CE_registry = nv;
  459. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  460. }
  461. return true;
  462. },
  463. enumerable: false,
  464. configurable: true
  465. })
  466. }
  467. let eventHandler = (evt) => {
  468. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  469. const f = callback;
  470. callback = null;
  471. eventHandler = null;
  472. f();
  473. };
  474. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  475. } else {
  476. callback();
  477. }
  478. });
  479.  
  480. const retrieveCE = async (nodeName) => {
  481. try {
  482. isCustomElementsProvided || (await promiseForCustomYtElementsReady);
  483. await customElements.whenDefined(nodeName);
  484. const dummy = document.querySelector(nodeName) || document.createElement(nodeName);
  485. const cProto = insp(dummy).constructor.prototype;
  486. return cProto;
  487. } catch (e) {
  488. console.warn(e);
  489. }
  490. }
  491.  
  492. return { retrieveCE };
  493.  
  494. })();
  495.  
  496. const cfg = {};
  497. class Mutex {
  498.  
  499. constructor() {
  500. this.p = Promise.resolve()
  501. }
  502.  
  503. /**
  504. * @param {(lockResolve: () => void)} f
  505. */
  506. lockWith(f) {
  507. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  508. }
  509.  
  510. }
  511.  
  512. class OrderedMutex extends Mutex {
  513. constructor() {
  514. super();
  515. this.nextIndex = 0;
  516. this.arr = [];
  517. this.lockFunc = resolve => {
  518. if (this.arr.length >= 1) {
  519. let f = this.arr[0];
  520. if (typeof f === 'function') {
  521. this.arr.shift();
  522. if (this.nextIndex > 0) this.nextIndex--;
  523. f(resolve);
  524. return;
  525. } else {
  526. // reset if unknown error
  527. this.arr.length = 0;
  528. this.nextIndex = 0;
  529. }
  530. }
  531. resolve();
  532. };
  533. }
  534. /**
  535. * @param {(lockResolve: () => void)} f
  536. */
  537. add(f) {
  538. if (this.nextIndex === this.arr.length) {
  539. this.arr.push(f); this.nextIndex++;
  540. } else {
  541. this.arr.splice(this.nextIndex++, 0, f);
  542. }
  543. this.lockWith(this.lockFunc);
  544. }
  545. }
  546. // usage: run network request one by one
  547. const mutex = new OrderedMutex();
  548.  
  549. const createPipeline = () => {
  550. let pipelineMutex = Promise.resolve();
  551. const pipelineExecution = fn => {
  552. return new Promise((resolve, reject) => {
  553. pipelineMutex = pipelineMutex.then(async () => {
  554. let res;
  555. try {
  556. res = await fn();
  557. } catch (e) {
  558. console.log('error_F1', e);
  559. reject(e);
  560. }
  561. resolve(res);
  562. }).catch(console.warn);
  563. });
  564. };
  565. return pipelineExecution;
  566. };
  567.  
  568. /**
  569. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  570. * @template T */
  571.  
  572. /**
  573. * usage: cache the network result per web application instance.
  574. * @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  575. const displayNameResStore = new Map();
  576.  
  577. /**
  578. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  579. * @type {WeakMap<Function, Function>} */
  580. const dataChangedFuncStore = new WeakMap();
  581.  
  582. /**
  583. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  584. * @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
  585. const handleToChannelId = new Map();
  586.  
  587. /**
  588. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  589. * @type {Map<ChannelId, ChannelIdToHandleResult>} */
  590. const channelIdToHandle = new Map();
  591.  
  592. /**
  593. * usage: replace handle to lang-specific display name
  594. * @type {Map<HandleText, DisplayName>} */
  595. const langPreferredDisplayNameMap = new Map();
  596.  
  597. /**
  598. * AsyncValue
  599. * @class
  600. * @template T
  601. */
  602. class AsyncValue {
  603. constructor() {
  604. /** @type {T | null} */
  605. this.__value__ = null;
  606. /** @type {((value: any)=>void) | null} */
  607. this.__resolve__ = null;
  608. this.__promise__ = new Promise(resolve => {
  609. this.__resolve__ = resolve;
  610. });
  611. }
  612. /**
  613. *
  614. * @param {T} value
  615. */
  616. setValue(value) {
  617. const promise = this.__promise__;
  618. if (promise === null) throw 'Value has already been set.';
  619. this.__value__ = value;
  620. this.__promise__ = null;
  621. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  622. }
  623. /**
  624. *
  625. * @returns {Promise<T>}
  626. */
  627. async getValue() {
  628. const promise = this.__promise__;
  629. if (promise === null) return this.__value__;
  630. await promise; // promise become null
  631. this.__promise__ = null; // just in case
  632. this.__resolve__ = null;
  633. return this.__value__;
  634. }
  635. }
  636.  
  637. let isCSSAdded = false;
  638. const addCSSRulesIfRequired = () => {
  639. if (isCSSAdded) return;
  640. isCSSAdded = true;
  641. const style = document.createElement('style')
  642. let nonce = document.querySelector('head style[nonce]');
  643. nonce = nonce ? nonce.getAttribute('nonce') : null;
  644.  
  645. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (LTR, when mixed with LTR languages) */
  646. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (pure) */
  647.  
  648. const cssText01_FIX_RTL_ISSUE = FIX_RTL_ISSUE ? `
  649.  
  650. /* Left-to-Right (LTR) Languages */
  651. #contenteditable-root.yt-formatted-string:lang(en) /* English */,
  652. #contenteditable-root.yt-formatted-string:lang(es) /* Spanish */,
  653. #contenteditable-root.yt-formatted-string:lang(fr) /* French */,
  654. #contenteditable-root.yt-formatted-string:lang(de) /* German */,
  655. #contenteditable-root.yt-formatted-string:lang(it) /* Italian */,
  656. #contenteditable-root.yt-formatted-string:lang(pt) /* Portuguese */,
  657. #contenteditable-root.yt-formatted-string:lang(ru) /* Russian */,
  658. #contenteditable-root.yt-formatted-string:lang(zh) /* Chinese */,
  659. #contenteditable-root.yt-formatted-string:lang(ja) /* Japanese */,
  660. #contenteditable-root.yt-formatted-string:lang(ko) /* Korean */,
  661. #contenteditable-root.yt-formatted-string:lang(nl) /* Dutch */,
  662. #contenteditable-root.yt-formatted-string:lang(sv) /* Swedish */,
  663. #contenteditable-root.yt-formatted-string:lang(fi) /* Finnish */,
  664. #contenteditable-root.yt-formatted-string:lang(da) /* Danish */,
  665. #contenteditable-root.yt-formatted-string:lang(no) /* Norwegian */,
  666. #contenteditable-root.yt-formatted-string:lang(pl) /* Polish */,
  667. #contenteditable-root.yt-formatted-string:lang(cs) /* Czech */,
  668. #contenteditable-root.yt-formatted-string:lang(sk) /* Slovak */,
  669. #contenteditable-root.yt-formatted-string:lang(hu) /* Hungarian */,
  670. #contenteditable-root.yt-formatted-string:lang(tr) /* Turkish */,
  671. #contenteditable-root.yt-formatted-string:lang(el) /* Greek */,
  672. #contenteditable-root.yt-formatted-string:lang(id) /* Indonesian */,
  673. #contenteditable-root.yt-formatted-string:lang(ms) /* Malay */,
  674. #contenteditable-root.yt-formatted-string:lang(th) /* Thai */,
  675. #contenteditable-root.yt-formatted-string:lang(vi) /* Vietnamese */
  676. {
  677. direction: ltr;
  678. }
  679.  
  680. /* Right-to-Left (RTL) Languages */
  681. #contenteditable-root.yt-formatted-string:lang(ar) /* Arabic */,
  682. #contenteditable-root.yt-formatted-string:lang(fa) /* Persian */,
  683. #contenteditable-root.yt-formatted-string:lang(ur) /* Urdu */,
  684. #contenteditable-root.yt-formatted-string:lang(dv) /* Divehi */
  685. {
  686. direction: rtl;
  687. }
  688.  
  689. ` : '';
  690. style.textContent = `
  691. ${cssText01_FIX_RTL_ISSUE}
  692. `.trim();
  693. if (nonce) style.setAttribute('nonce', nonce);
  694. document.head.appendChild(style);
  695. }
  696.  
  697. /**
  698. *
  699. * @param {DisplayNameResultObject} resultInfo
  700. * @param {string} channelId
  701. */
  702. const cacheHandleToChannel = (resultInfo, channelId) => {
  703.  
  704. const { vanityChannelUrl, ownerUrls } = resultInfo;
  705.  
  706. let handleText = urlToHandle(vanityChannelUrl || '');
  707.  
  708. if (handleText) {
  709. // match = true;
  710. } else if ((ownerUrls || 0).length >= 1) {
  711. for (const ownerUrl of ownerUrls) {
  712. handleText = urlToHandle(ownerUrl || '');
  713.  
  714. if (handleText) {
  715. // match = true;
  716. break;
  717. }
  718. }
  719. }
  720. if (handleText) {
  721.  
  722. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  723. if (asyncValue instanceof AsyncValue) {
  724. asyncValue.setValue(channelId);
  725. }
  726. handleToChannelId.set(handleText, channelId);
  727. }
  728.  
  729.  
  730. }
  731.  
  732. /**
  733. *
  734. * @param {string} channelId
  735. * @param {Function} onDownloaded
  736. * @param {Function} onResulted
  737. * @param {Function} onError
  738. */
  739. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  740.  
  741. let signal = timeoutSignal(4000);
  742.  
  743. const requestBody = {
  744. "context": {
  745. "client": {
  746. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  747. "clientName": "MWEB", // "WEB", "MWEB"
  748. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  749. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  750. "playerType": "UNIPLAYER",
  751. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  752. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  753. "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",
  754. "mainAppWebInfo": {
  755. "graftUrl": `/channel/${channelId}`,
  756. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  757. "isWebNativeShareAvailable": true
  758. }
  759. },
  760. "user": {
  761. "lockedSafetyMode": false
  762. },
  763. "request": {
  764. "useSsl": true,
  765. "internalExperimentFlags": [],
  766. "consistencyTokenJars": []
  767. }
  768. },
  769. "browseId": `${channelId}`
  770. };
  771.  
  772. if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
  773. Object.assign(requestBody.context.client, {
  774. "hl": cfg.HL,
  775. "gl": cfg.GL,
  776. });
  777. }
  778.  
  779. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  780. "method": "POST",
  781. "mode": "same-origin",
  782. "credentials": "omit",
  783.  
  784. referrerPolicy: "no-referrer",
  785. cache: "default", // no effect on POST request
  786. // cache: "force-cache",
  787. redirect: "error", // there shall be no redirection in this API request
  788. integrity: "",
  789. keepalive: false,
  790. signal,
  791.  
  792. "headers": {
  793. "Content-Type": "application/json", // content type of the body data in POST request
  794. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  795. // X-Youtube-Bootstrap-Logged-In: false,
  796. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  797. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  798.  
  799. "Accept": "application/json",
  800. },
  801. "body": JSON.stringify(requestBody)
  802. })).then(res => {
  803. signal && signal.clearTimeout && signal.clearTimeout();
  804. signal = null;
  805. onDownloaded();
  806. onDownloaded = null;
  807. return res.json();
  808. }).then(resJson => {
  809. const resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  810. const title = resultInfo ? resultInfo.title : null;
  811. if (title || title === '') {
  812.  
  813. resultInfo.title = '';
  814. resultInfo.langTitle = title;
  815.  
  816. if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
  817. let matched = false;
  818.  
  819. const ownerProfileUrlLowerCase = cfg.ownerProfileUrl.toLowerCase();
  820. if (ownerProfileUrlLowerCase.endsWith(`/channel/${channelId.toLowerCase()}`)) matched = true;
  821. else {
  822.  
  823. for (const ownerUrl of resultInfo.ownerUrls) {
  824. if (ownerUrl.toLowerCase().endsWith(ownerProfileUrlLowerCase)) {
  825. matched = true;
  826. break;
  827. }
  828. }
  829.  
  830. }
  831.  
  832. if (matched) {
  833. resultInfo.title = cfg.ownerChannelName;
  834. }
  835. }
  836.  
  837. }
  838.  
  839. onResulted(resultInfo);
  840. onResulted = null;
  841. }).catch(onError);
  842.  
  843. };
  844.  
  845. /**
  846. *
  847. * @param {string} channelId
  848. * @param {Function} onDownloaded
  849. * @param {Function} onResulted
  850. * @param {Function} onError
  851. */
  852. let fetchRSSFailed = false;
  853. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  854.  
  855. let signal = timeoutSignal(4000);
  856. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  857. // YouTube RSS Response - public, max-age=900
  858.  
  859. "method": "GET",
  860. "mode": "same-origin",
  861. "credentials": "omit",
  862.  
  863. referrerPolicy: "no-referrer",
  864. cache: "default",
  865. // cache: "no-cache",
  866. redirect: "error", // there shall be no redirection in this API request
  867. integrity: "",
  868. keepalive: false,
  869. signal,
  870.  
  871. "headers": {
  872. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  873. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  874. // seems YouTube RSS Feeds server insists its own Cache-Control.
  875.  
  876. // "Content-Type": "text/xml; charset=UTF-8",
  877. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  878. // X-Youtube-Bootstrap-Logged-In: false,
  879. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  880. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  881.  
  882. "Accept": "text/xml",
  883. }
  884. }).then(res => {
  885.  
  886. signal && signal.clearTimeout && signal.clearTimeout();
  887. signal = null;
  888.  
  889. if (res.ok === true && res.redirected === false && res.status === 200 && res.type === "basic") {
  890.  
  891. onDownloaded();
  892. onDownloaded = null;
  893. return res.text();
  894.  
  895. }
  896. return null;
  897.  
  898. }).then(resText => {
  899. if (resText && typeof resText === 'string' && resText.includes('<feed') && !resText.includes('<!DOCTYPE')) {
  900.  
  901. } else {
  902. if (onDownloaded) {
  903.  
  904. onDownloaded();
  905. onDownloaded = null;
  906. }
  907. onResulted(-1);
  908. return;
  909.  
  910. }
  911.  
  912.  
  913. // console.log(124, , resText)
  914. let eIdx = resText.indexOf('<entry>');
  915. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  916.  
  917. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  918. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  919. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  920. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  921.  
  922.  
  923. let name, uri, mt;
  924.  
  925. // ===============================================================
  926.  
  927. /* removed in 2023.06.30 */
  928.  
  929.  
  930. // ===============================================================
  931.  
  932.  
  933. const wIdx1 = mText.indexOf('<author>');
  934. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  935.  
  936. if (wIdx1 > 0 && wIdx2 > 0) {
  937. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  938. const template = document.createElement('template');
  939. template.innerHTML = createHTML(qText);
  940. /** @type {HTMLElement | null} */
  941. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  942. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  943. const nodeName = authorChild.nodeName;
  944. if (nodeName === 'NAME') name = authorChild.textContent;
  945. else if (nodeName === 'URI') {
  946. uri = authorChild.textContent;
  947. mt = obtainChannelId(uri);
  948. }
  949. }
  950. template.innerHTML = createHTML('');
  951. }
  952.  
  953. if (!name && !uri) {
  954.  
  955. // fallback
  956.  
  957. const parser = new DOMParser();
  958. const xmlDoc = parser.parseFromString(mText, "text/xml");
  959.  
  960. // const author = xmlDoc.querySelector("author");
  961.  
  962. // https://extendsclass.com/xpath-tester.html
  963.  
  964. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  965.  
  966. let authorChild;
  967. while ((authorChild = authorChilds.iterateNext()) !== null) {
  968. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  969. else if (authorChild.nodeName === 'uri') {
  970. uri = authorChild.textContent;
  971. mt = obtainChannelId(uri);
  972. }
  973. }
  974.  
  975. try {
  976. xmlDoc.firstChild.remove();
  977. } catch (e) { }
  978.  
  979. }
  980.  
  981.  
  982.  
  983.  
  984. let res = null;
  985.  
  986. if ((name || name === '') && uri && mt && mt === channelId) {
  987.  
  988.  
  989. const handleObj = channelIdToHandle.get(mt);
  990.  
  991. if (handleObj) {
  992.  
  993. const handleText = handleObj.handleText;
  994.  
  995. if (handleText === name) channelIdToHandle.delete(mt);
  996. else {
  997. handleObj.justPossible = false; // ignore @handle checking
  998.  
  999. res = {
  1000. "title": name,
  1001. "externalId": mt,
  1002. "ownerUrls": [
  1003. `http://www.youtube.com/${handleText}`
  1004. ],
  1005. "channelUrl": uri,
  1006. "vanityChannelUrl": `http://www.youtube.com/${handleText}`
  1007. };
  1008.  
  1009. if (USE_LANG_SPECIFIC_NAME) {
  1010. const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
  1011. if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
  1012. }
  1013.  
  1014. }
  1015. }
  1016. }
  1017.  
  1018. onResulted(res);
  1019. onResulted = null;
  1020.  
  1021. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  1022. // onResulted(resultInfo);
  1023. }).catch(onError);
  1024.  
  1025.  
  1026.  
  1027. }
  1028.  
  1029. sessionStorage.setItem('js-yt-usernames', '');
  1030. let isFirstStackNewRequestSuccess = true;
  1031. /**
  1032. *
  1033. * @param {string} channelId
  1034. */
  1035. function stackNewRequest(channelId) {
  1036.  
  1037. mutex.add(lockResolve => {
  1038.  
  1039. let bResult = displayNameResStore.get(channelId);
  1040. if (!(bResult instanceof AsyncValue)) {
  1041. // resolved or removed
  1042. lockResolve(); lockResolve = null;
  1043. return;
  1044. }
  1045.  
  1046. let setResult = (result) => {
  1047. setResult = null;
  1048. if (!result) {
  1049. bResult.fetchingState = 0;
  1050. bResult.setValue(null);
  1051. displayNameResStore.delete(channelId); // create another network response in the next request
  1052. } else {
  1053. bResult.fetchingState = 4;
  1054. bResult.setValue(result);
  1055. displayNameResStore.set(channelId, result); // update store result to resolved value
  1056. }
  1057. bResult = null;
  1058. }
  1059.  
  1060. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  1061. // request is already done. no need to stack any request
  1062. lockResolve(); lockResolve = null;
  1063. return;
  1064. }
  1065.  
  1066. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  1067. // element has already been removed
  1068. lockResolve(); lockResolve = null;
  1069. setResult(null);
  1070. return;
  1071. }
  1072.  
  1073. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  1074.  
  1075. bResult.fetchingState = 2;
  1076.  
  1077.  
  1078. const retry = () => {
  1079.  
  1080. fetchRSSFailed = true;
  1081.  
  1082. bResult.fetchingState = 2;
  1083.  
  1084. // Promise.resolve(channelId).then(stackNewRequest);
  1085. fetcherBrowseAPI(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  1086. }
  1087.  
  1088. const mobj = {
  1089. fetchOnDownload: () => {
  1090. bResult.fetchingState = 3;
  1091. },
  1092. fetchOnSuccess: resultInfo => {
  1093.  
  1094. if (resultInfo === -1) {
  1095. retry();
  1096. return;
  1097. }
  1098.  
  1099. lockResolve && lockResolve();
  1100. lockResolve = null;
  1101. // console.log(900)
  1102.  
  1103. if (!resultInfo) {
  1104. // invalid json format
  1105. setResult(null);
  1106. return;
  1107. }
  1108.  
  1109. const titleForDisplay = resultInfo.langTitle || resultInfo.title;
  1110. const handleObj = channelIdToHandle.get(channelId);
  1111. const handleId = handleObj ? handleObj.handleText : '';
  1112. if (IGNORE_NO_NAME && !titleForDisplay) {
  1113. if (handleId) {
  1114. resultInfo.langTitle = resultInfo.title = handleObj.handleText;
  1115. } else {
  1116. setResult(null);
  1117. return;
  1118. }
  1119. }
  1120.  
  1121. cacheHandleToChannel(resultInfo, channelId);
  1122.  
  1123. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  1124.  
  1125. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  1126.  
  1127. if (handleId) {
  1128. if (isFirstStackNewRequestSuccess) {
  1129. isFirstStackNewRequestSuccess = false;
  1130. sessionStorage.setItem('js-yt-usernames', `${handleId}\t${titleForDisplay}`);
  1131. } else {
  1132. let current = sessionStorage.getItem('js-yt-usernames') || '';
  1133. if (current.length > 900000) {
  1134. const na = current.split('\n');
  1135. const n3 = Math.floor(na.length / 3);
  1136. if (n3 > 2) {
  1137. const newText = na.slice(0, n3).concat(na.slice(na.length - n3)).join('\n');
  1138. if (newText.length < 720000) {
  1139. current = newText;
  1140. }
  1141. }
  1142. }
  1143. sessionStorage.setItem('js-yt-usernames', `${current}\n${handleId}\t${titleForDisplay}`);
  1144. }
  1145. }
  1146.  
  1147. setResult(displayNameRes);
  1148. },
  1149. fetchOnFail: e => {
  1150.  
  1151.  
  1152. console.warn(e);
  1153. if (mobj.fetcher === fetcherRSS) {
  1154. retry();
  1155.  
  1156. } else {
  1157.  
  1158. lockResolve && lockResolve();
  1159. lockResolve = null;
  1160. // console.warn(e);
  1161. setResult && setResult(null);
  1162. }
  1163. }
  1164. }
  1165.  
  1166.  
  1167. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  1168. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  1169. mobj.fetcher = USE_RSS_FETCHER && fetcherRSS && !fetchRSSFailed && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  1170. mobj.fetcher(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  1171.  
  1172. });
  1173.  
  1174. }
  1175.  
  1176. /**
  1177. *
  1178. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  1179. * @returns Example: _\@yr__kd_
  1180. */
  1181. function urlToHandle(url) {
  1182.  
  1183. if (typeof url !== 'string') return '';
  1184. let i = url.indexOf('.youtube.com/');
  1185. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  1186. else if (url.charAt(0) === '/') url = url.substring(1);
  1187. return isDisplayAsHandle(url) ? url : '';
  1188.  
  1189. }
  1190.  
  1191. /**
  1192. *
  1193. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  1194. * @returns {Promise<DisplayNameResultObject | null>}
  1195. */
  1196. async function getDisplayName(channelId) {
  1197.  
  1198. let cache = displayNameResStore.get(channelId);
  1199. let isStackNewRequest = false;
  1200.  
  1201. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  1202. let aResult;
  1203.  
  1204. if (cache instanceof AsyncValue) {
  1205. aResult = cache;
  1206. if (aResult.fetchingState >= 2) {
  1207. // aResult.fetchingState
  1208. // 2: network fetch started
  1209. // 3: network fetch ended
  1210. // isStackNewRequest = false;
  1211. } else {
  1212. // 0: invalid before
  1213. // 1: scheduled but not yet fetch
  1214. isStackNewRequest = true;
  1215. }
  1216. } else if (cache) {
  1217. // resolved result
  1218. return cache;
  1219. } else {
  1220. // else no cached value found
  1221. /** @type {AsyncValue<DisplayNameResultObject>} */
  1222. aResult = new AsyncValue();
  1223. displayNameResStore.set(channelId, aResult);
  1224. isStackNewRequest = true;
  1225. }
  1226.  
  1227. if (isStackNewRequest) {
  1228. aResult.fetchingState = 1;
  1229. stackNewRequest(channelId);
  1230. }
  1231. const result = await aResult.getValue();
  1232. return result;
  1233. }
  1234.  
  1235.  
  1236. /**
  1237. *
  1238. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  1239. * @returns
  1240. * * Outdated?
  1241. */
  1242. const obtainChannelId = (href) => {
  1243. const s = `/${href}`;
  1244. if (s.length >= 33) {
  1245. const m = /\/channel\/(UC[-_a-zA-Z0-9+=.]{22})(\/|$)/.exec(s);
  1246. return !m ? '' : (m[1] || '');
  1247. }
  1248. return '';
  1249. };
  1250.  
  1251. const isUCBrowserId = (browseId) => {
  1252. return typeof browseId === 'string' && browseId.length === 24 && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId);
  1253. }
  1254.  
  1255. const browseEndpointBaseUrlType = (browseEndpoint, displayText) => {
  1256. if (isDisplayAsHandle(displayText) && isUCBrowserId(browseEndpoint.browseId) && typeof browseEndpoint.canonicalBaseUrl === 'string') {
  1257. if (`/${displayText}` === browseEndpoint.canonicalBaseUrl) return 1 | 2;
  1258. if (`/channel/${browseEndpoint.browseId}` === browseEndpoint.canonicalBaseUrl) return 1 | 4;
  1259. if (browseEndpoint.canonicalBaseUrl.includes(`/${browseEndpoint.browseId}`)) return 1 | 8;
  1260. return 1;
  1261. }
  1262. return 0;
  1263. }
  1264.  
  1265. /**
  1266. *
  1267. * @param {Element} ytElm
  1268. */
  1269. const resetWhenDataChanged = (ths) => {
  1270. const cnt = insp(ths);
  1271. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1272. if (ytElm instanceof Element) {
  1273. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1274. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1275. if ((anchors || 0).length >= 1 && (insp(ytElm).data || 0).jkrgx !== 1) {
  1276. for (const anchor of anchors) {
  1277. anchor.removeAttribute('jkrgy');
  1278. }
  1279. }
  1280. }
  1281. }
  1282.  
  1283. /**
  1284. *
  1285. * @param {Element} ytElm
  1286. */
  1287. const resetWhenPropChanged = (ths) => {
  1288. const cnt = insp(ths);
  1289. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1290. if (ytElm instanceof Element) {
  1291. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1292. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1293. if ((anchors || 0).length >= 1 && ((insp(ytElm).commentEntity || 0).author || 0).jkrgx !== 1) {
  1294. for (const anchor of anchors) {
  1295. anchor.removeAttribute('jkrgy');
  1296. }
  1297. }
  1298. }
  1299. }
  1300.  
  1301. /**
  1302. *
  1303. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  1304. * @param {string} hrefAttribute Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ (old) 2024 Feb -> /@user-abc1234
  1305. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  1306. * @returns
  1307. */
  1308. const anchorIntegrityCheck = (anchor, hrefAttribute) => {
  1309.  
  1310. let currentHref = anchor.getAttribute('href');
  1311. if (currentHref === hrefAttribute) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  1312.  
  1313. return (currentHref + '/').indexOf(hrefAttribute + '/') >= 0;
  1314.  
  1315. };
  1316.  
  1317. /**
  1318. *
  1319. * @param {string} currentDisplayed
  1320. * @param {DisplayNameResultObject} fetchResult
  1321. * @returns
  1322. */
  1323. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  1324.  
  1325. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  1326.  
  1327. const currentDisplayTrimmed = currentDisplayed.trim(); // @IORIMATSUNAGA
  1328. const currentDisplayTrimmedLowerCase = currentDisplayTrimmed.toLowerCase(); // @iorimatsunaga
  1329. let match = false;
  1330. if (verified123) {
  1331. match = true;
  1332. } else if ((vanityChannelUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmedLowerCase}`)) {
  1333. match = true;
  1334. } else if ((ownerUrls || 0).length >= 1) {
  1335. for (const ownerUrl of ownerUrls) {
  1336. if ((ownerUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmed}`)) {
  1337. match = true;
  1338. break;
  1339. }
  1340. }
  1341. }
  1342. if (match) {
  1343. return currentDisplayTrimmed;
  1344. }
  1345. return '';
  1346.  
  1347. };
  1348.  
  1349. /**
  1350. *
  1351. *
  1352.  
  1353. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  1354.  
  1355. - Is between 3-30 characters
  1356. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1357. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  1358. - Is not URL-like or phone number-like
  1359. - Is not already being used
  1360. - Follows YouTube's Community Guidelines
  1361.  
  1362. ### Handle automatically generated by YouTube
  1363. - `@user-XXXX`
  1364. - without dot (.)
  1365.  
  1366.  
  1367. ## Intl. Language Support
  1368. #### Since May~June 2024
  1369.  
  1370. - Before: Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1371.  
  1372. - After: Uses alphabet letters or numbers from one of our 75 supported languages
  1373. - Your handle can also include: underscores (_), hyphens (-), periods (.), Latin middle dots (·).
  1374. - Mixed scripts are only allowed in certain circumstances.
  1375. - 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.
  1376.  
  1377.  
  1378.  
  1379.  
  1380. *
  1381. * @param {string} text
  1382. * @returns
  1383. */
  1384. const isDisplayAsHandle = (text) => {
  1385. if (typeof text !== 'string') return false;
  1386. if (text.length < 4) return false;
  1387. if (text.indexOf('@') < 0) return false;
  1388. return exactHandleText(text.trim(), true);
  1389. };
  1390.  
  1391.  
  1392. const languageMapR0 = [];
  1393.  
  1394. const languageMap = [
  1395. { 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)
  1396. { 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)
  1397. { range: [0x00C0, 0x00FF], langs: ['French', 'Portuguese', 'Spanish', 'Afrikaans'] }, // Latin-1 Supplement
  1398. { range: [0x0100, 0x017F], langs: ['Latvian', 'Lithuanian', 'Polish', 'Czech', 'Slovak', 'Slovenian', 'Croatian', 'Bosnian', 'Serbian', 'Montenegrin'] }, // Latin Extended-A
  1399. { range: [0x0180, 0x024F], langs: ['African languages', 'Esperanto'] }, // Latin Extended-B
  1400. { range: [0x0370, 0x03FF], langs: ['Greek'] }, // Greek and Coptic
  1401. { range: [0x0400, 0x04FF], langs: ['Russian', 'Ukrainian', 'Bulgarian', 'Serbian', 'Macedonian', 'Belarusian', 'Kazakh', 'Kyrgyz', 'Uzbek'] }, // Cyrillic
  1402. { range: [0x0500, 0x052F], langs: ['Kazakh', 'Kyrgyz', 'Uzbek'] }, // Cyrillic Supplement
  1403. { range: [0x0530, 0x058F], langs: ['Armenian'] }, // Armenian
  1404. { range: [0x0590, 0x05FF], langs: ['Hebrew'] }, // Hebrew
  1405. { range: [0x0600, 0x06FF], langs: ['Arabic', 'Persian', 'Urdu'] }, // Arabic
  1406. { range: [0x0700, 0x074F], langs: ['Syriac'] }, // Syriac
  1407. { range: [0x0750, 0x077F], langs: ['Arabic Supplement'] }, // Arabic Supplement
  1408. { range: [0x0780, 0x07BF], langs: ['Thaana'] }, // Thaana
  1409. { range: [0x0900, 0x097F], langs: ['Hindi', 'Marathi', 'Sanskrit', 'Nepali'] }, // Devanagari
  1410. { range: [0x0980, 0x09FF], langs: ['Bengali', 'Assamese'] }, // Bengali
  1411. { range: [0x0A00, 0x0A7F], langs: ['Punjabi'] }, // Gurmukhi
  1412. { range: [0x0A80, 0x0AFF], langs: ['Gujarati'] }, // Gujarati
  1413. { range: [0x0B00, 0x0B7F], langs: ['Odia'] }, // Oriya
  1414. { range: [0x0B80, 0x0BFF], langs: ['Tamil'] }, // Tamil
  1415. { range: [0x0C00, 0x0C7F], langs: ['Telugu'] }, // Telugu
  1416. { range: [0x0C80, 0x0CFF], langs: ['Kannada'] }, // Kannada
  1417. { range: [0x0D00, 0x0D7F], langs: ['Malayalam'] }, // Malayalam
  1418. { range: [0x0D80, 0x0DFF], langs: ['Sinhala'] }, // Sinhala
  1419. { range: [0x0E00, 0x0E7F], langs: ['Thai'] }, // Thai
  1420. { range: [0x0E80, 0x0EFF], langs: ['Lao'] }, // Lao
  1421. { range: [0x0F00, 0x0FFF], langs: ['Tibetan'] }, // Tibetan
  1422. { range: [0x1000, 0x109F], langs: ['Burmese'] }, // Myanmar
  1423. { range: [0x10A0, 0x10FF], langs: ['Georgian'] }, // Georgian
  1424. { range: [0x1100, 0x11FF], langs: ['Korean'] }, // Hangul Jamo
  1425. { range: [0x1200, 0x137F], langs: ['Amharic', 'Tigrinya', 'Geez'] }, // Ethiopic
  1426. { range: [0x13A0, 0x13FF], langs: ['Cherokee'] }, // Cherokee
  1427. { range: [0x1400, 0x167F], langs: ['Canadian Aboriginal'] }, // Unified Canadian Aboriginal Syllabics
  1428. { range: [0x1680, 0x169F], langs: ['Ogham'] }, // Ogham
  1429. { range: [0x16A0, 0x16FF], langs: ['Runic'] }, // Runic
  1430. { range: [0x1700, 0x171F], langs: ['Tagalog'] }, // Tagalog
  1431. { range: [0x1720, 0x173F], langs: ['Hanunoo'] }, // Hanunoo
  1432. { range: [0x1740, 0x175F], langs: ['Buhid'] }, // Buhid
  1433. { range: [0x1760, 0x177F], langs: ['Tagbanwa'] }, // Tagbanwa
  1434. { range: [0x1780, 0x17FF], langs: ['Khmer'] }, // Khmer
  1435. { range: [0x1800, 0x18AF], langs: ['Mongolian'] }, // Mongolian
  1436. { range: [0x1E00, 0x1EFF], langs: ['Latin Extended Additional'] }, // Latin Extended Additional
  1437. { range: [0x1F00, 0x1FFF], langs: ['Greek Extended'] }, // Greek Extended
  1438. { range: [0x2000, 0x206F], langs: ['General Punctuation'] }, // General Punctuation
  1439. { range: [0x2070, 0x209F], langs: ['Superscripts and Subscripts'] }, // Superscripts and Subscripts
  1440. { range: [0x20A0, 0x20CF], langs: ['Currency Symbols'] }, // Currency Symbols
  1441. { range: [0x2100, 0x214F], langs: ['Letterlike Symbols'] }, // Letterlike Symbols
  1442. { range: [0x2150, 0x218F], langs: ['Number Forms'] }, // Number Forms
  1443. { range: [0x2190, 0x21FF], langs: ['Arrows'] }, // Arrows
  1444. { range: [0x2200, 0x22FF], langs: ['Mathematical Operators'] }, // Mathematical Operators
  1445. { range: [0x2300, 0x23FF], langs: ['Miscellaneous Technical'] }, // Miscellaneous Technical
  1446. { range: [0x2400, 0x243F], langs: ['Control Pictures'] }, // Control Pictures
  1447. { range: [0x2440, 0x245F], langs: ['Optical Character Recognition'] }, // Optical Character Recognition
  1448. { range: [0x2460, 0x24FF], langs: ['Enclosed Alphanumerics'] }, // Enclosed Alphanumerics
  1449. { range: [0x2500, 0x257F], langs: ['Box Drawing'] }, // Box Drawing
  1450. { range: [0x2580, 0x259F], langs: ['Block Elements'] }, // Block Elements
  1451. { range: [0x25A0, 0x25FF], langs: ['Geometric Shapes'] }, // Geometric Shapes
  1452. { range: [0x2600, 0x26FF], langs: ['Miscellaneous Symbols'] }, // Miscellaneous Symbols
  1453. { range: [0x2700, 0x27BF], langs: ['Dingbats'] }, // Dingbats
  1454. { range: [0x3000, 0x303F], langs: ['CJK Symbols and Punctuation'] }, // CJK Symbols and Punctuation
  1455. { range: [0x3040, 0x309F], langs: ['Japanese'] }, // Hiragana
  1456. { range: [0x30A0, 0x30FF], langs: ['Japanese'] }, // Katakana
  1457. { range: [0x3100, 0x312F], langs: ['Bopomofo'] }, // Bopomofo
  1458. { range: [0x3130, 0x318F], langs: ['Korean'] }, // Hangul Compatibility Jamo
  1459. { range: [0x3190, 0x319F], langs: ['Kanbun'] }, // Kanbun
  1460. { range: [0x31A0, 0x31BF], langs: ['Bopomofo Extended'] }, // Bopomofo Extended
  1461. { range: [0x31F0, 0x31FF], langs: ['Katakana Phonetic Extensions'] }, // Katakana Phonetic Extensions
  1462. { range: [0x3200, 0x32FF], langs: ['Enclosed CJK Letters and Months'] }, // Enclosed CJK Letters and Months
  1463. { range: [0x3300, 0x33FF], langs: ['CJK Compatibility'] }, // CJK Compatibility
  1464. { range: [0x4E00, 0x9FFF], langs: ['Chinese (Simplified)', 'Chinese (Traditional)', 'Japanese', 'Korean'] }, // CJK Unified Ideographs
  1465. { range: [0xAC00, 0xD7AF], langs: ['Korean'] }, // Hangul Syllables
  1466. { range: [0xD800, 0xDBFF], langs: ['High Surrogates'] }, // High Surrogates
  1467. { range: [0xDC00, 0xDFFF], langs: ['Low Surrogates'] }, // Low Surrogates
  1468. { range: [0xF900, 0xFAFF], langs: ['CJK Compatibility Ideographs'] }, // CJK Compatibility Ideographs
  1469. { range: [0xFB00, 0xFB4F], langs: ['Alphabetic Presentation Forms'] }, // Alphabetic Presentation Forms
  1470. { range: [0xFB50, 0xFDFF], langs: ['Arabic Presentation Forms-A'] }, // Arabic Presentation Forms-A
  1471. { range: [0xFE20, 0xFE2F], langs: ['Combining Half Marks'] }, // Combining Half Marks
  1472. { range: [0xFE70, 0xFEFF], langs: ['Arabic Presentation Forms-B'] }, // Arabic Presentation Forms-B
  1473. { range: [0xFF00, 0xFFEF], langs: ['Halfwidth and Fullwidth Forms'] }, // Halfwidth and Fullwidth Forms
  1474. { range: [0xFFF0, 0xFFFF], langs: ['Specials'] }, // Specials
  1475. { range: [0x10000, 0x1007F], langs: ['Linear B Syllabary'] }, // Linear B Syllabary
  1476. { range: [0x10080, 0x100FF], langs: ['Linear B Ideograms'] }, // Linear B Ideograms
  1477. { range: [0x10100, 0x1013F], langs: ['Aegean Numbers'] }, // Aegean Numbers
  1478. { range: [0x10140, 0x1018F], langs: ['Ancient Greek Numbers'] }, // Ancient Greek Numbers
  1479. { range: [0x10190, 0x101CF], langs: ['Ancient Symbols'] }, // Ancient Symbols
  1480. { range: [0x101D0, 0x101FF], langs: ['Phaistos Disc'] }, // Phaistos Disc
  1481. { range: [0x10280, 0x1029F], langs: ['Lycian'] }, // Lycian
  1482. { range: [0x102A0, 0x102DF], langs: ['Carian'] }, // Carian
  1483. { range: [0x10300, 0x1032F], langs: ['Old Italic'] }, // Old Italic
  1484. { range: [0x10330, 0x1034F], langs: ['Gothic'] }, // Gothic
  1485. { range: [0x10380, 0x1039F], langs: ['Ugaritic'] }, // Ugaritic
  1486. { range: [0x103A0, 0x103DF], langs: ['Old Persian'] }, // Old Persian
  1487. { range: [0x10400, 0x1044F], langs: ['Deseret'] }, // Deseret
  1488. { range: [0x10450, 0x1047F], langs: ['Shavian'] }, // Shavian
  1489. { range: [0x10480, 0x104AF], langs: ['Osmanya'] }, // Osmanya
  1490. { range: [0x10800, 0x1083F], langs: ['Cypriot Syllabary'] }, // Cypriot Syllabary
  1491. { range: [0x10840, 0x1085F], langs: ['Imperial Aramaic'] }, // Imperial Aramaic
  1492. { range: [0x10900, 0x1091F], langs: ['Phoenician'] }, // Phoenician
  1493. { range: [0x10920, 0x1093F], langs: ['Lydian'] }, // Lydian
  1494. { range: [0x10A00, 0x10A5F], langs: ['Kharoshthi'] }, // Kharoshthi
  1495. { range: [0x10A60, 0x10A7F], langs: ['Old South Arabian'] }, // Old South Arabian
  1496. { range: [0x10B00, 0x10B3F], langs: ['Avestan'] }, // Avestan
  1497. { range: [0x10B40, 0x10B5F], langs: ['Inscriptional Parthian'] }, // Inscriptional Parthian
  1498. { range: [0x10B60, 0x10B7F], langs: ['Inscriptional Pahlavi'] }, // Inscriptional Pahlavi
  1499. { range: [0x10C00, 0x10C4F], langs: ['Old Turkic'] }, // Old Turkic
  1500. { range: [0x10E60, 0x10E7F], langs: ['Rumi Numeral Symbols'] }, // Rumi Numeral Symbols
  1501. { range: [0x11000, 0x1107F], langs: ['Brahmi'] }, // Brahmi
  1502. { range: [0x11080, 0x110CF], langs: ['Kaithi'] }, // Kaithi
  1503. { range: [0x12000, 0x123FF], langs: ['Cuneiform'] }, // Cuneiform
  1504. { range: [0x13000, 0x1342F], langs: ['Egyptian Hieroglyphs'] }, // Egyptian Hieroglyphs
  1505. { range: [0x16800, 0x16A3F], langs: ['Bamum'] }, // Bamum
  1506. { range: [0x1B000, 0x1B0FF], langs: ['Kana Supplement'] }, // Kana Supplement
  1507. { range: [0x1D000, 0x1D0FF], langs: ['Byzantine Musical Symbols'] }, // Byzantine Musical Symbols
  1508. { range: [0x1D100, 0x1D1FF], langs: ['Musical Symbols'] }, // Musical Symbols
  1509. { range: [0x1D200, 0x1D24F], langs: ['Ancient Greek Musical Notation'] }, // Ancient Greek Musical Notation
  1510. { range: [0x1D300, 0x1D35F], langs: ['Tai Xuan Jing Symbols'] }, // Tai Xuan Jing Symbols
  1511. { range: [0x1D360, 0x1D37F], langs: ['Counting Rod Numerals'] }, // Counting Rod Numerals
  1512. { range: [0x1D400, 0x1D7FF], langs: ['Mathematical Alphanumeric Symbols'] }, // Mathematical Alphanumeric Symbols
  1513. { range: [0x1F000, 0x1F02F], langs: ['Mahjong Tiles'] }, // Mahjong Tiles
  1514. { range: [0x1F030, 0x1F09F], langs: ['Domino Tiles'] }, // Domino Tiles
  1515. { range: [0x1F0A0, 0x1F0FF], langs: ['Playing Cards'] }, // Playing Cards
  1516. { range: [0x1F100, 0x1F1FF], langs: ['Enclosed Alphanumeric Supplement'] }, // Enclosed Alphanumeric Supplement
  1517. { range: [0x1F200, 0x1F2FF], langs: ['Enclosed Ideographic Supplement'] }, // Enclosed Ideographic Supplement
  1518. { range: [0x1F300, 0x1F5FF], langs: ['Miscellaneous Symbols and Pictographs'] }, // Miscellaneous Symbols and Pictographs
  1519. { range: [0x1F600, 0x1F64F], langs: ['Emoticons'] }, // Emoticons
  1520. { range: [0x1F680, 0x1F6FF], langs: ['Transport and Map Symbols'] }, // Transport and Map Symbols
  1521. { range: [0x1F700, 0x1F77F], langs: ['Alchemical Symbols'] }, // Alchemical Symbols
  1522. { range: [0x20000, 0x2A6DF], langs: ['CJK Unified Ideographs Extension B'] }, // CJK Unified Ideographs Extension B
  1523. { range: [0x2A700, 0x2B73F], langs: ['CJK Unified Ideographs Extension C'] }, // CJK Unified Ideographs Extension C
  1524. { range: [0x2B740, 0x2B81F], langs: ['CJK Unified Ideographs Extension D'] }, // CJK Unified Ideographs Extension D
  1525. { range: [0x2F800, 0x2FA1F], langs: ['CJK Compatibility Ideographs Supplement'] }, // CJK Compatibility Ideographs Supplement
  1526. ];
  1527.  
  1528.  
  1529.  
  1530. let lastLangEntry = null;
  1531.  
  1532. function getPossibleLanguages(unicodeChar) {
  1533. const unicode = typeof unicodeChar === 'number' ? unicodeChar : typeof unicodeChar === 'string' ? unicodeChar.codePointAt(0) : 0;
  1534.  
  1535. if (unicode >= 0x20) {
  1536. if (unicode >= 0x0370 && lastLangEntry && unicode >= lastLangEntry.range[0] && unicode <= lastLangEntry.range[1]) {
  1537. return lastLangEntry.langs;
  1538. }
  1539. for (const entry of languageMap) {
  1540. if (unicode >= entry.range[0] && unicode <= entry.range[1]) {
  1541. if (entry.range[0] >= 0x0370) lastLangEntry = entry;
  1542. return entry.langs;
  1543. }
  1544. if (entry.range[0] >= unicode && entry.range[1] >= unicode) break;
  1545. }
  1546. }
  1547.  
  1548. return languageMapR0;
  1549. }
  1550.  
  1551. const handleTextAllowSymbols = new Set('_-.·'.split('').map(e => e.codePointAt()));
  1552. const blacklistChars = new Set('@;:"\'!$#%^&*()[]<>,?/\\+{}|~`!'.split('').map(e => e.codePointAt()));
  1553.  
  1554. const _cache_isExactHandleText = new Map();
  1555. const isExactHandleText = (text, i = 0) => {
  1556. let cpCount = 0, cp = 0;
  1557. let cpMin = Number.MAX_VALUE
  1558. let cpMax = Number.MIN_VALUE
  1559. const suffixNumber = /\d+$/.exec(text);
  1560. const suffixNumberLen = `${suffixNumber || ''}`.length;
  1561. const textLen = text.length;
  1562. if (textLen - i > 30) return false;
  1563. let l = textLen - suffixNumberLen;
  1564. let maxCpCount = 30 - suffixNumberLen;
  1565. if (maxCpCount <= 0) return maxCpCount === 0;
  1566. const mtext = text.substring(i);
  1567. let res = _cache_isExactHandleText.get(mtext);
  1568. if (typeof res !== 'undefined') return res;
  1569.  
  1570. const retFn = (res) => {
  1571. _cache_isExactHandleText.set(mtext, res);
  1572. return res;
  1573. }
  1574.  
  1575. let uchars = [];
  1576. const uRanges = new Set();
  1577. for (; i < l; i++) {
  1578. cp = text.codePointAt(i);
  1579. if (!cp) break;
  1580. if (!handleTextAllowSymbols.has(cp) && !(cp >= 0x30 && cp <= 0x39) && !(cp >= 0x41 && cp <= 0x5A) && !(cp >= 0x61 && cp <= 0x7A)) {
  1581. // @[LANG]-c2w (found in Dec 2024)
  1582. if (blacklistChars.has(cp)) return retFn(false);
  1583. const uRange = getPossibleLanguages(cp);
  1584. uRanges.add(uRange);
  1585. uchars.push(cp);
  1586. if (cpMin > cp) cpMin = cp;
  1587. if (cpMax < cp) cpMax = cp;
  1588. }
  1589. if (cp < 0x7FFFFFFF) {
  1590. while (cp > 0xFFFF) {
  1591. cp = cp >> 16;
  1592. i++;
  1593. }
  1594. } else {
  1595. console.warn('cp >= 0x7FFFFFFF')
  1596. return retFn(false);
  1597. }
  1598. cpCount++;
  1599. if (cpCount > 30) {
  1600. return retFn(false);
  1601. }
  1602. }
  1603.  
  1604. // console.log(mtext, cpMin,cpMax, uRanges)
  1605. if (cpMin >= 32 && cpMax <= 122) {
  1606. return retFn(/^[-_a-zA-Z0-9.·]{3,30}$/.test(mtext));
  1607. }
  1608.  
  1609. let mm = {}, mi = 0;
  1610. for (const uRange of uRanges) {
  1611. if (uRange) {
  1612. for (const lang of uRange) {
  1613. if (lang) {
  1614. mm[lang] = (mm[lang] || 0) + 1;
  1615. }
  1616. }
  1617. }
  1618. mi++;
  1619. }
  1620. let unilang = "";
  1621. let dd = Object.entries(mm).filter(a => a[1] === mi);
  1622. if (dd.length === 1) {
  1623. unilang = dd[0];
  1624. } else if (dd.length === 3 && dd[0][0] === 'Arabic' && dd[1][0] === 'Persian' && dd[2][0] === 'Urdu') {
  1625. return retFn("Arabic");
  1626. }
  1627.  
  1628. if (unilang[0] === "Japanese") {
  1629. return retFn("Japanese"); // japanese handle can mix with kanji
  1630. }
  1631.  
  1632.  
  1633. if (cpMin >= 0x1000) {
  1634. const ft = String.fromCodePoint(...uchars);
  1635. if (cpMin >= 0x4E00 && cpMax <= 0xD7AF) {
  1636. if (/^[\u4E00-\u9FFF\uAC00-\uD7AF]{1,10}$/.test(ft)) return retFn("Han|Hangul");
  1637. } else if (cpMin >= 0x1200 && cpMax <= 0x30FF) {
  1638. if (/^[\u1200-\u137F\u3040-\u30FF]{2,20}$/.test(ft)) return retFn("Ethiopic|Hiragana|Katakana");
  1639. }
  1640. }
  1641.  
  1642. return retFn(false);
  1643.  
  1644. }
  1645.  
  1646. const exactHandleText = (text, b) => {
  1647. return text.startsWith('@') && isExactHandleText(text, 1) ? (b ? true : text.substring(1)) : (b ? false : '');
  1648. }
  1649.  
  1650. const exactHandleUrl_ = (text, b) => {
  1651. return text.startsWith('/@') && isExactHandleText(text, 2) ? (b ? true : text.substring(2)) : (b ? false : '');
  1652. }
  1653.  
  1654. const _cache_urlHandleConversion = new Map();
  1655. const urlHandleConversion = (text) => {
  1656.  
  1657. if (text && typeof text === 'string' && text.length >= 5 && text.startsWith('/@')) {
  1658. let converted = _cache_urlHandleConversion.get(text);
  1659.  
  1660. if (typeof converted === 'string') {
  1661.  
  1662. text = converted;
  1663.  
  1664. } else if (text.includes('%')) {
  1665. let text0 = text;
  1666.  
  1667. let text2 = text.substring(2);
  1668. if (/%[0-9A-Fa-f]{2}/.test(text2) && /^[-_a-zA-Z%0-9.·]+$/.test(text2)) {
  1669. try {
  1670. text2 = decodeURI(text2);
  1671. } catch (e) { }
  1672. text = `/@${text2}`
  1673. }
  1674. _cache_urlHandleConversion.set(text0, text);
  1675.  
  1676. }
  1677.  
  1678.  
  1679. if (text.length >= 5 && text.length <= 32 && exactHandleUrl_(text, true)) {
  1680. return text;
  1681. }
  1682. }
  1683.  
  1684. return '';
  1685.  
  1686. }
  1687. const exactHandleUrl = (text, b) => {
  1688. if (text && typeof text === 'string' && text.length >= 5 && text.startsWith('/@')) {
  1689. text = urlHandleConversion(text) || text;
  1690. return exactHandleUrl_(text, b);
  1691. }
  1692. return b ? false : '';
  1693. }
  1694.  
  1695. try {
  1696. // https://www.youtube.com/watch?v=hfopp1vLFmk
  1697. // https://www.youtube.com/watch?v=V-4PiHDX2Mg
  1698. let b = true
  1699.  
  1700.  
  1701. b = b && isDisplayAsHandle('@7r0n215 ');
  1702. b = b && isDisplayAsHandle('@user-ox5by7bw1m ');
  1703. b = b && isDisplayAsHandle('@Samsungfan2016 ');
  1704. b = b && isDisplayAsHandle('@김태래 ');
  1705. b = b && !isDisplayAsHandle('@%EA%B9%80%ED%83%9C%EB%9E%98 ');
  1706.  
  1707. b = b && !exactHandleText('@7r0n215 ', true);
  1708. b = b && !exactHandleText('@user-ox5by7bw1m ', true);
  1709. b = b && !exactHandleText('@Samsungfan2016 ', true);
  1710. b = b && !exactHandleText('@김태래 ', true);
  1711. b = b && !exactHandleText('@%EA%B9%80%ED%83%9C%EB%9E%98 ', true);
  1712.  
  1713.  
  1714. b = b && !exactHandleUrl('/@7r0n215 ', true);
  1715. b = b && !exactHandleUrl('/@user-ox5by7bw1m ', true);
  1716. b = b && !exactHandleUrl('/@Samsungfan2016 ', true);
  1717. b = b && !exactHandleUrl('/@김태래 ', true);
  1718. b = b && !exactHandleUrl('/@%EA%B9%80%ED%83%9C%EB%9E%98 ', true);
  1719.  
  1720.  
  1721. b = b && isDisplayAsHandle(' @7r0n215');
  1722. b = b && isDisplayAsHandle(' @user-ox5by7bw1m');
  1723. b = b && isDisplayAsHandle(' @Samsungfan2016');
  1724. b = b && isDisplayAsHandle(' @김태래');
  1725. b = b && !isDisplayAsHandle(' @%EA%B9%80%ED%83%9C%EB%9E%98');
  1726.  
  1727. b = b && !exactHandleText(' @7r0n215', true);
  1728. b = b && !exactHandleText(' @user-ox5by7bw1m', true);
  1729. b = b && !exactHandleText(' @Samsungfan2016', true);
  1730. b = b && !exactHandleText(' @김태래', true);
  1731. b = b && !exactHandleText(' @%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1732.  
  1733. b = b && !exactHandleUrl(' /@7r0n215', true);
  1734. b = b && !exactHandleUrl(' /@user-ox5by7bw1m', true);
  1735. b = b && !exactHandleUrl(' /@Samsungfan2016', true);
  1736. b = b && !exactHandleUrl(' /@김태래', true);
  1737. b = b && !exactHandleUrl(' /@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1738.  
  1739.  
  1740. b = b && isDisplayAsHandle('@7r0n215');
  1741. b = b && isDisplayAsHandle('@user-ox5by7bw1m');
  1742. b = b && isDisplayAsHandle('@Samsungfan2016');
  1743. b = b && isDisplayAsHandle('@김태래');
  1744. b = b && !isDisplayAsHandle('@%EA%B9%80%ED%83%9C%EB%9E%98');
  1745.  
  1746. b = b && exactHandleText('@7r0n215', true);
  1747. b = b && exactHandleText('@user-ox5by7bw1m', true);
  1748. b = b && exactHandleText('@Samsungfan2016', true);
  1749. b = b && exactHandleText('@김태래', true);
  1750. b = b && !exactHandleText('@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1751.  
  1752.  
  1753. b = b && exactHandleUrl('/@7r0n215', true);
  1754. b = b && exactHandleUrl('/@user-ox5by7bw1m', true);
  1755. b = b && exactHandleUrl('/@Samsungfan2016', true);
  1756. b = b && exactHandleUrl('/@김태래', true);
  1757. b = b && exactHandleUrl('/@%EA%B9%80%ED%83%9C%EB%9E%98', true);
  1758.  
  1759. b = b && isDisplayAsHandle('@Lions_joyfulpenda');
  1760. b = b && isDisplayAsHandle('@kowlsl12');
  1761. b = b && isDisplayAsHandle('@hyezzozzo_baseball_curtaincall');
  1762. b = b && isDisplayAsHandle('@blue-pink-love');
  1763.  
  1764.  
  1765. b = b && isDisplayAsHandle('@mr.memebear901');
  1766. b = b && isDisplayAsHandle('@すいちゃん可愛い');
  1767. 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');
  1768. b = b && isDisplayAsHandle('@ハシビロ公');
  1769. b = b && exactHandleUrl('/@%E3%83%8F%E3%82%B7%E3%83%93%E3%83%AD%E5%85%AC');
  1770. b = b && isDisplayAsHandle('@ex1524')
  1771. b = b && isDisplayAsHandle('@K88571')
  1772. b = b && isDisplayAsHandle('@مجلةالرابالعربي')
  1773. b = b && !isDisplayAsHandle('@@مجلةالرابالعربي')
  1774.  
  1775. b = b && isDisplayAsHandle('@ともとも-e7d8b')
  1776. b = b && isDisplayAsHandle('@佐藤漣-x7i')
  1777.  
  1778.  
  1779. if (!b) console.error('!!!! wrong coding !!!!');
  1780. } catch (e) {
  1781. console.error('!!!! wrong coding !!!!', e);
  1782. }
  1783. /**
  1784. *
  1785. * @param {Object[]} contentTexts
  1786. * @param {number} idx
  1787. * @returns
  1788. */
  1789. const contentTextProcess = (_md, contentTexts, idx) => {
  1790. const md = _md;
  1791. const contentText = contentTexts[idx];
  1792. const text = (contentText || 0).text;
  1793. const browseId = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1794. const canonicalBaseUrl = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1795. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1796. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1797.  
  1798. if (!isDisplayAsHandle(text)) return null;
  1799. const channelId = browseId;
  1800.  
  1801. return getDisplayName(channelId).then(fetchResult => {
  1802. let resolveResult = null;
  1803. if (fetchResult) {
  1804. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1805.  
  1806. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1807. if (textTrimmed) {
  1808. resolveResult = (() => {
  1809. let runs = ((md || 0).contentText || 0).runs;
  1810. if (!runs || !runs[idx]) return;
  1811. if (runs[idx].text !== text) return;
  1812. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1813. md.contentText = Object.assign({}, md.contentText);
  1814. })();
  1815. }
  1816. }
  1817. return resolveResult; // function as a Promise
  1818. });
  1819. }
  1820.  
  1821. return null;
  1822. };
  1823.  
  1824. const dynamicEditableTextByControllerResolve = isMobile ? 0 : (() => {
  1825. /**
  1826. *
  1827. *
  1828. f.showReplyDialog = function(a) {
  1829. if (a) {
  1830. var b = this.replyBox;
  1831. b || (b = document.createElement("ytd-comment-reply-dialog-renderer"),
  1832. b.id = "replybox",
  1833. qF(this.replyDialogDiv).appendChild(b));
  1834. b.data = a;
  1835. this.replyDialogDiv.hidden = !1;
  1836. b.openDialog()
  1837. }
  1838. }
  1839.  
  1840. // a = <ytd-comment-engagement-bar>...</ytd-comment-engagement-bar>
  1841. // b = "showReplyDialog"
  1842. // c = undefined
  1843. function Lpb(a, b, c) {
  1844. var d = a.polymerController;
  1845. a[b] = function() {
  1846. var e = va.apply(0, arguments);
  1847. a.loggingStatus.currentExternalCall = b;
  1848. a.loggingStatus.bypassProxyController = !0;
  1849. var g, k = ((g = a.is) != null ? g : a.tagName).toLowerCase();
  1850. ZE(k, b, "PROPERTY_ACCESS_CALL_EXTERNAL");
  1851. var m;
  1852. g = (m = c != null ? c : d[b]) == null ? void 0 : m.call.apply(m, [d].concat(ha(e)));
  1853. a.loggingStatus.currentExternalCall = void 0;
  1854. a.loggingStatus.bypassProxyController = !1;
  1855. return g
  1856. }
  1857. }
  1858.  
  1859. // a = {..., commandMetadata, createCommentReplyDialogEndpoint}
  1860. // b = {commandController: {onSuccess: ƒ, onServerError: ƒ} , forceClickLogging : true, form: {element, event} }
  1861. kQb.prototype.resolveCommand = function(a, b) {
  1862. var c, d, e, g, k, m, p, q;
  1863. return t(function(r) {
  1864. e = (c = G(a, n6a)) == null ? void 0 : (d = c.dialog) == null ? void 0 : d.commentReplyDialogRenderer;
  1865. if (!e)
  1866. throw new Em("No dialog in createCommentReplyDialogEndpoint");
  1867. k = (g = b.form) == null ? void 0 : g.event;
  1868. if (!k)
  1869. throw new Em("Event not passed in when resolving command");
  1870. m = h(k.composedPath());
  1871. for (p = m.next(); !p.done; p = m.next())
  1872. if (q = p.value,
  1873. q.tagName === "YTD-COMMENT-ACTION-BUTTONS-RENDERER" || q.tagName === "YTD-COMMENT-ENGAGEMENT-BAR")
  1874. return q.showReplyDialog(e),
  1875. r.return();
  1876. ma(r)
  1877. })
  1878. }
  1879.  
  1880.  
  1881. *
  1882. */
  1883.  
  1884.  
  1885. const setupForCommentReplyDialogRenderer = (cProto) => {
  1886. if (cProto && typeof cProto.showReplyDialog === 'function' && cProto.showReplyDialog.length === 1 && !cProto.showReplyDialog392) {
  1887. cProto.showReplyDialog392 = cProto.showReplyDialog;
  1888. cProto.showReplyDialog = function (a) {
  1889. let goDefault = true;
  1890. try {
  1891. if (a && a.editableText) {
  1892. const arr = [];
  1893. fixCommentReplyDialogRenderer(a, arr);
  1894. const pAll = Promise.all(arr).catch(e => console.warn);
  1895. Promise.race([pAll, delayPn(300)]).then(() => { // network request should be already done before
  1896. this.showReplyDialog392(a);
  1897. });
  1898. goDefault = false;
  1899. }
  1900. } catch (e) { }
  1901. if (goDefault) {
  1902. return this.showReplyDialog392(a);
  1903. }
  1904. };
  1905. }
  1906. };
  1907.  
  1908. retrieveCE('ytd-comment-action-buttons-renderer').then(cProto => {
  1909. setupForCommentReplyDialogRenderer(cProto);
  1910. });
  1911. retrieveCE('ytd-comment-engagement-bar').then(cProto => {
  1912. setupForCommentReplyDialogRenderer(cProto);
  1913. });
  1914.  
  1915. return 1;
  1916.  
  1917. })();
  1918.  
  1919. const editableTextProcess = (_commentReplyDialogRenderer, editableTexts, idx) => {
  1920. const commentReplyDialogRenderer = _commentReplyDialogRenderer;
  1921. const editableText = editableTexts[idx];
  1922. const text = (editableText || 0).text;
  1923.  
  1924. const browseId = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1925. const canonicalBaseUrl = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1926. const url = (((editableText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1927. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1928.  
  1929. if (!isDisplayAsHandle(text)) return null;
  1930. const channelId = browseId;
  1931.  
  1932. return getDisplayName(channelId).then(fetchResult => {
  1933. let resolveResult = null;
  1934. if (fetchResult) {
  1935. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1936.  
  1937. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1938. if (textTrimmed) {
  1939. resolveResult = (() => {
  1940. if (!commentReplyDialogRenderer) return;
  1941. const editableText = commentReplyDialogRenderer.editableText || 0;
  1942. let runs = (editableText || 0).runs;
  1943. if (!runs || !runs[idx]) return;
  1944. if (runs[idx].text !== text) return;
  1945. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1946. commentReplyDialogRenderer.editableText = Object.assign({}, commentReplyDialogRenderer.editableText);
  1947. })();
  1948. }
  1949. }
  1950. return resolveResult; // function as a Promise
  1951. });
  1952. }
  1953.  
  1954. return null;
  1955. };
  1956. const contentTextProcessViewModel = async (content, idx) => {
  1957. const { commandRuns, content: text, styleRuns } = content;
  1958. if (typeof text !== 'string') return;
  1959. const names = [];
  1960.  
  1961. function replaceNamePN(o) {
  1962. return getDisplayName(o.channelId).then(fetchResult => {
  1963. let resolveResult = null;
  1964. if (fetchResult) {
  1965. const textTrimmed = verifyAndConvertHandle(o.handle, fetchResult);
  1966. if (textTrimmed) {
  1967. o.display = `@${fetchResult.title}`;
  1968. o.newText = o.oldText.replace(o.handle, o.display);
  1969. }
  1970. }
  1971. return resolveResult; // function as a Promise
  1972. });
  1973. }
  1974. const promises = [];
  1975. for (const commandRun of commandRuns) {
  1976. let browseEndpoint = null;
  1977. if (commandRun.length >= 1 && commandRun.startIndex >= 0 && (browseEndpoint = ((commandRun.onTap || 0).innertubeCommand || 0).browseEndpoint)) {
  1978. let substr = text.substring(commandRun.startIndex, commandRun.startIndex + commandRun.length);
  1979. const substrTrimmed = substr.trim();
  1980. const valBrowseEndpointBaseUrlType = browseEndpointBaseUrlType(browseEndpoint, substrTrimmed);
  1981. if (valBrowseEndpointBaseUrlType > 1) {
  1982. const o = {
  1983. startIndex: commandRun.startIndex,
  1984. endIndex: commandRun.startIndex + commandRun.length,
  1985. handle: substrTrimmed,
  1986. oldText: substr,
  1987. newText: null,
  1988. channelId: browseEndpoint.browseId,
  1989. nStartIndex: null,
  1990. nEndIndex: null,
  1991. nText: null
  1992. }
  1993. names.push(o);
  1994. promises.push(replaceNamePN(o));
  1995. }
  1996. }
  1997. }
  1998. await Promise.all(promises);
  1999.  
  2000. let offset = 0;
  2001. for (const o of names) {
  2002. o.nStartIndex = o.startIndex + offset;
  2003. o.nText = o.newText === null ? o.oldText : o.newText;
  2004. o.nEndIndex = o.nStartIndex + offset + o.nText.length;
  2005. offset += o.nText.length - o.oldText.length;
  2006. }
  2007.  
  2008. let w1 = 0, w2 = 0;
  2009. let s = [];
  2010. let j = 0;
  2011. for (let i = 0; i < text.length;) {
  2012. while (w1 < commandRuns.length && commandRuns[w1].startIndex < i) w1++;
  2013. while (w2 < styleRuns.length && styleRuns[w2].startIndex < i) w2++;
  2014.  
  2015. if (j < names.length && i == names[j].startIndex) {
  2016.  
  2017. if (w1 < commandRuns.length && commandRuns[w1].startIndex === names[j].startIndex) {
  2018. const run = commandRuns[w1];
  2019. const o = names[j];
  2020. if (run.length === o.endIndex - o.startIndex) {
  2021. run.startIndex = o.nStartIndex;
  2022. run.length = o.nText.length;
  2023. }
  2024. w1++;
  2025. }
  2026.  
  2027. if (w2 < styleRuns.length && styleRuns[w2].startIndex === names[j].startIndex) {
  2028. const run = styleRuns[w2];
  2029. const o = names[j];
  2030. if (run.length === o.endIndex - o.startIndex) {
  2031. run.startIndex = o.nStartIndex;
  2032. run.length = o.nText.length;
  2033. }
  2034. w2++;
  2035. }
  2036.  
  2037.  
  2038. // s.push(text.substring(names[j].startIndex, names[j].endIndex));
  2039. s.push(names[j].nText);
  2040. i = names[j].endIndex;
  2041. j++;
  2042. } else {
  2043. if (j >= names.length) {
  2044. s.push(text.substring(i));
  2045. i = text.length;
  2046. } else {
  2047. if (j < names.length && names[j].startIndex > i + 1) {
  2048. s.push(text.substring(i, names[j].startIndex));
  2049. i = names[j].startIndex;
  2050. } else {
  2051. s.push(text.charAt(i));
  2052. i++;
  2053. }
  2054. }
  2055. }
  2056. }
  2057.  
  2058. content.content = s.join('');
  2059. s.length = 0;
  2060.  
  2061.  
  2062. };
  2063.  
  2064. /**
  2065. *
  2066. * @param {ParentNode & Element} parentNode
  2067. * @param {Function} callback
  2068. */
  2069. function findTextNodes(parentNode, callback) {
  2070. /**
  2071. *
  2072. * @param {Node} node
  2073. * @returns
  2074. */
  2075. function traverse(node) {
  2076. if (node.nodeType === Node.TEXT_NODE) {
  2077. let r = callback(node);
  2078. if (r === true) return true;
  2079. } else if (node.nodeType === Node.ELEMENT_NODE) {
  2080. for (let childNode = nodeFirstChild(node); childNode; childNode = nodeNextSibling(childNode)) {
  2081. const r = traverse(childNode);
  2082. if (r === true) return true;
  2083. }
  2084. }
  2085. }
  2086.  
  2087. traverse(parentNode);
  2088. }
  2089.  
  2090. function updatePinnedCommentBadge(md, title, langTitle) {
  2091. const titleForDisplay = langTitle || title;
  2092. if (typeof titleForDisplay !== 'string') return;
  2093. if (title === titleForDisplay) return;
  2094. const runs = ((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0); // can be 0
  2095. if (runs.length === 2) {
  2096. let idx = 0;
  2097. let jdx = -1;
  2098. for (const textRun of runs) {
  2099. if (textRun.text === title) {
  2100. jdx = idx;
  2101. break;
  2102. }
  2103. idx++;
  2104. }
  2105. if (jdx >= 0) {
  2106. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  2107. runs[jdx] = Object.assign({}, runs[jdx], { text: titleForDisplay });
  2108. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  2109. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  2110. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  2111. }
  2112. }
  2113. }
  2114.  
  2115. /**
  2116. *
  2117. * @param {ParentNode} parentNode
  2118. * @param {Object[]} contentTexts
  2119. * @param {number} aidx
  2120. * @returns
  2121. */
  2122. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  2123.  
  2124.  
  2125. let commentText = elementQS(parentNode, '.comment-text');
  2126. if (!commentText) return;
  2127. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  2128. let currentText = commentText.textContent;
  2129. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  2130. if (!textMatch) return;
  2131.  
  2132. const contentText = contentTexts[aidx];
  2133.  
  2134. /** @type {string} */
  2135. const handleText = contentText.text.trim();
  2136. /** @type {string | null | undefined} */
  2137. let channelId;
  2138.  
  2139. let cache = handleToChannelId.get(handleText);
  2140.  
  2141. if (typeof cache === 'string') {
  2142. channelId = cache;
  2143. } else if (cache instanceof AsyncValue) {
  2144. channelId = await cache.getValue();
  2145. } else {
  2146. /** @type {AsyncValue<string>} */
  2147. const asyncValue = new AsyncValue();
  2148. handleToChannelId.set(handleText, asyncValue);
  2149. channelId = await asyncValue.getValue(); // note: it could be never resolved
  2150. }
  2151.  
  2152. if (!channelId) return; // just in case
  2153.  
  2154. if (commentText.isConnected !== true) return; // already removed
  2155. if (commentText.textContent !== currentText) return; // already changed
  2156.  
  2157. const fetchResult = await getDisplayName(channelId);
  2158.  
  2159. if (fetchResult === null) return;
  2160.  
  2161. const { title, langTitle, externalId } = fetchResult;
  2162. const titleForDisplay = langTitle || title;
  2163. if (externalId !== channelId) return; // channel id must be the same
  2164.  
  2165. if (commentText.isConnected !== true) return; // already removed
  2166. if (commentText.textContent !== currentText) return; // already changed
  2167.  
  2168. let search = contentText.text;
  2169. if (typeof search === 'string') {
  2170.  
  2171. const searchTrimmed = search.trim();
  2172. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  2173. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  2174.  
  2175. findTextNodes(commentText, (textnode) => {
  2176. if (textnode.nodeValue.indexOf(search) >= 0) {
  2177. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  2178. return true;
  2179. }
  2180. });
  2181. }
  2182.  
  2183. }
  2184.  
  2185. }
  2186.  
  2187. /**
  2188. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  2189. * @type { (anchor: HTMLElement, anchorHref: string?, mt: string?) => Promise<void> }
  2190. */
  2191.  
  2192. const getDisplayTextDOMForCommentRenderer = (root) => { // mobile
  2193. let displayTextDOM = elementQS(root, '.comment-header .comment-title');
  2194. if (displayTextDOM) {
  2195. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  2196. }
  2197. return displayTextDOM;
  2198. }
  2199.  
  2200. const ytPathnameExtract = (href) => {
  2201.  
  2202. if (!href || typeof href !== 'string') return '';
  2203. let i = 0;
  2204. if (href.startsWith('/')) {
  2205.  
  2206. } else if ((i = href.indexOf('youtube.com/')) >= 0) {
  2207. href = href.substring(i + 11);
  2208. } else {
  2209. return '';
  2210. }
  2211. return href;
  2212.  
  2213. }
  2214.  
  2215. const getHrefType = (href) => {
  2216. if (href && typeof href === 'string') {
  2217. if (href.length === 33 && href.startsWith('/channel/') && /^\/channel\/UC[-_a-zA-Z0-9+=.]{22}$/.test(href)) {
  2218. return 1;
  2219. } else {
  2220. href = urlHandleConversion(href) || href;
  2221. if (href && href.length >= 5 && href.length <= 32 && exactHandleUrl_(href, true)) {
  2222. return 2;
  2223. }
  2224. }
  2225. }
  2226. return 0;
  2227. }
  2228.  
  2229. const getYTextType = (text) => {
  2230. // if (typeof text === 'string') return 1;
  2231. if (typeof text === 'object' && text) {
  2232. if (typeof text.simpleText === 'string') return 2;
  2233. const runs = text.runs;
  2234. if (runs && runs.length === 1) {
  2235. let r = runs[0];
  2236. return typeof r === 'string' ? 3 : typeof (r || 0).text === 'string' ? 4 : null;
  2237. }
  2238. }
  2239. return null;
  2240. }
  2241.  
  2242. const getYTextContent = (text) => {
  2243. // if (typeof text === 'string') return text;
  2244. if (typeof text === 'object' && text) {
  2245. const simpleText = text.simpleText;
  2246. if (typeof simpleText === 'string') return simpleText;
  2247. const runs = text.runs;
  2248. if (runs && runs.length === 1) {
  2249. let r = runs[0];
  2250. return typeof r === 'string' ? r : typeof (r || 0).text === 'string' ? r.text : null;
  2251. }
  2252. }
  2253. return null;
  2254. }
  2255.  
  2256. const setYTextContent = (text, fn) => {
  2257. // if (typeof text === 'string') {
  2258. // res=fn(text);
  2259. // }
  2260. if (typeof text === 'object' && text) {
  2261. const simpleText = text.simpleText;
  2262. if (typeof simpleText === 'string') {
  2263. return Object.assign({}, text, { simpleText: fn(simpleText) });
  2264. }
  2265. const runs = text.runs;
  2266. if (runs && runs.length === 1) {
  2267. let r = runs[0];
  2268. 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;
  2269. }
  2270. }
  2271. return null;
  2272. }
  2273.  
  2274. const fixCommentReplyDialogRenderer = (commentReplyDialogRenderer, funcPromises) => {
  2275. if (!commentReplyDialogRenderer) return;
  2276. const editableText = commentReplyDialogRenderer.editableText;
  2277. if (!editableText) return;
  2278. const editableTexts = editableText.runs;
  2279. if (editableTexts && editableTexts.length >= 1) {
  2280. for (let aidx = 0; aidx < editableTexts.length; aidx++) {
  2281. const r = editableTextProcess(commentReplyDialogRenderer, editableTexts, aidx);
  2282. if (r instanceof Promise) funcPromises.push(r);
  2283. }
  2284. }
  2285. // $0.polymerController.$['action-buttons'].polymerController.__data.replyButtonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer.editableText
  2286. }
  2287.  
  2288. const domCheckAsync = isMobile ? async (anchor, hrefAttribute, mt) => {
  2289.  
  2290. let sHandleName = null;
  2291. let sNodeValue = null;
  2292. try {
  2293. if (!hrefAttribute || !mt) return;
  2294. let parentNode = nodeParent(anchor);
  2295. while (parentNode instanceof Node) {
  2296. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  2297. parentNode = nodeParent(parentNode);
  2298. }
  2299. if (parentNode instanceof Node) { } else return;
  2300.  
  2301. const commentRendererAuthorTextDOM = getDisplayTextDOMForCommentRenderer(parentNode);
  2302. const anchorAiraLabel = anchor.getAttribute('aria-label');
  2303. const anchorHrefValue = ytPathnameExtract(anchor.getAttribute('href')); // guess (Feb 2024)
  2304.  
  2305. const cnt = insp(parentNode);
  2306. const parentNodeData = cnt._commentData || cnt.data || 0;
  2307. const authorTextData = (parentNodeData.authorText || 0);
  2308.  
  2309. let tHandleName = null;
  2310.  
  2311. if (commentRendererAuthorTextDOM && authorTextData) {
  2312. const hType = getHrefType(anchorHrefValue);
  2313. let ytext = null;
  2314. if (hType === 2) {
  2315. tHandleName = anchorHrefValue.substring(1); // guess
  2316. } else if (hType === 1) {
  2317. ytext = getYTextContent(authorTextData)
  2318. tHandleName = ytext; // authorTextData.runs[0].text
  2319. }
  2320. if (typeof tHandleName === 'string' && commentRendererAuthorTextDOM.textContent.trim() === tHandleName && isDisplayAsHandle(tHandleName)) {
  2321. ytext = ytext || getYTextContent(authorTextData)
  2322. if (ytext === tHandleName) {
  2323. sHandleName = tHandleName;
  2324. sNodeValue = tHandleName;
  2325. }
  2326. }
  2327. }
  2328.  
  2329. if (typeof sHandleName === 'string' && typeof sNodeValue === 'string') {
  2330.  
  2331. if (!channelIdToHandle.has(mt)) {
  2332. channelIdToHandle.set(mt, {
  2333. handleText: sHandleName,
  2334. justPossible: true
  2335. });
  2336. }
  2337.  
  2338. const fetchResult = await getDisplayName(mt);
  2339.  
  2340. if (fetchResult === null) return;
  2341.  
  2342. const { title, langTitle, externalId } = fetchResult;
  2343. const titleForDisplay = langTitle || title;
  2344. if (externalId !== mt) return; // channel id must be the same
  2345.  
  2346. // anchor href might be changed by external
  2347. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2348.  
  2349. if (commentRendererAuthorTextDOM.isConnected !== true) return; // already removed
  2350.  
  2351. let found = false;
  2352.  
  2353. findTextNodes(commentRendererAuthorTextDOM, (textnode) => {
  2354. if (textnode.nodeValue === sNodeValue) {
  2355. textnode.nodeValue = titleForDisplay;
  2356. found = true;
  2357. return true;
  2358. }
  2359. });
  2360.  
  2361. if (!found) return;
  2362. if (anchorAiraLabel && anchorAiraLabel.trim() === sHandleName) anchor.setAttribute('aria-label', anchorAiraLabel.replace(sHandleName, titleForDisplay));
  2363. const authorTextDataNew = setYTextContent(authorTextData, (t) => t.replace(t.trim(), titleForDisplay));
  2364. if (authorTextDataNew && parentNodeData.authorText === authorTextData) {
  2365. parentNodeData.authorText = authorTextDataNew;
  2366. }
  2367.  
  2368. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  2369. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  2370. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  2371. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  2372. const tc = spanText ? spanText.textContent : '';
  2373. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  2374. let idx;
  2375. if (tc && tc === spanText.textContent && (idx = tc.indexOf(title)) >= 0) {
  2376. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  2377. }
  2378. }
  2379.  
  2380. const contentTexts = (parentNodeData.contentText || 0).runs;
  2381. if (contentTexts && contentTexts.length >= 2) {
  2382. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  2383. const contentText = contentTexts[aidx] || 0;
  2384. if (contentText.italics !== true && isDisplayAsHandle(contentText.text)) {
  2385. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  2386. }
  2387. }
  2388. }
  2389.  
  2390. }
  2391.  
  2392. } catch (e) {
  2393. console.warn(e);
  2394. }
  2395.  
  2396. } : async (anchor, hrefAttribute, mt) => {
  2397.  
  2398. try {
  2399. if (!hrefAttribute || !mt) return;
  2400. let parentNode = nodeParent(anchor);
  2401. let isCommentViewModel = 0;
  2402. while (parentNode instanceof Node) {
  2403. const cnt = insp(parentNode);
  2404. if (typeof cnt.is === 'string') {
  2405. if (cnt.commentEntity && !cnt._propertiesChanged) { isCommentViewModel = 2; break; } // 2024.04.30: ytd-comment-view-model (v3)
  2406. if (cnt.commentEntity && typeof cnt._propertiesChanged === 'function') { isCommentViewModel = 1; break; } // Feb 2024: ytd-comment-view-model (v1 & v2)
  2407. else if (typeof cnt.dataChanged === 'function') break;
  2408. }
  2409. parentNode = nodeParent(parentNode);
  2410. }
  2411. if (parentNode instanceof Node) { } else return;
  2412. const parentNodeController = insp(parentNode);
  2413.  
  2414. if (isCommentViewModel > 0) {
  2415.  
  2416. const commentEntity = parentNodeController.commentEntity || 0;
  2417. const commentEntityAuthor = commentEntity.author || 0;
  2418. const currentDisplayed = commentEntityAuthor.displayName || 0;
  2419. if (typeof currentDisplayed !== 'string') return;
  2420. if (!isDisplayAsHandle(currentDisplayed)) return;
  2421. if (!channelIdToHandle.has(mt)) {
  2422. channelIdToHandle.set(mt, {
  2423. handleText: currentDisplayed.trim(),
  2424. justPossible: true
  2425. });
  2426. }
  2427.  
  2428. // not working for CommentViewModel v3
  2429. if (typeof parentNodeController._propertiesChanged === 'function' && !parentNodeController._propertiesChanged159) {
  2430. const cntp = parentNodeController.constructor.prototype;
  2431. const c = cntp._propertiesChanged === parentNodeController._propertiesChanged ? cntp : parentNodeController;
  2432. c._propertiesChanged159 = c._propertiesChanged;
  2433. c._propertiesChanged = function () {
  2434. resetWhenPropChanged(this);
  2435. return this._propertiesChanged159.apply(this, arguments);
  2436. };
  2437. }
  2438.  
  2439. const fetchResult = await getDisplayName(mt);
  2440.  
  2441. if (fetchResult === null) return;
  2442.  
  2443. const { title, langTitle, externalId } = fetchResult;
  2444. const titleForDisplay = langTitle || title;
  2445. if (externalId !== mt) return; // channel id must be the same
  2446.  
  2447. // anchor href might be changed by external
  2448. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2449.  
  2450. if (commentEntityAuthor.displayName === currentDisplayed && commentEntityAuthor.channelId === mt) {
  2451. commentEntityAuthor.displayName = titleForDisplay;
  2452.  
  2453. if (commentEntity.properties) {
  2454. if (commentEntity.properties.authorButtonA11y === currentDisplayed) {
  2455. commentEntity.properties.authorButtonA11y = titleForDisplay;
  2456. }
  2457.  
  2458. // the inside hyperlinks will be only converted if its parent author name is handle
  2459. const content = commentEntity.properties.content;
  2460. if (content && (content.commandRuns || 0).length >= 1) {
  2461. try {
  2462. await contentTextProcessViewModel(content);
  2463.  
  2464. // $0.polymerController.commentEntity = Object.assign({}, $0.polymerController.commentEntity , { properties: Object.assign({}, $0.polymerController.commentEntity.properties, { content: Object.assign({},$0.polymerController.commentEntity.properties.content) } )})
  2465.  
  2466. // parentNodeController.commentEntity.properties = Object.assign({}, parentNodeController.commentEntity.properties, {
  2467. // content: Object.assign({}, parentNodeController.commentEntity.properties.content)
  2468. // });
  2469.  
  2470. commentEntity.properties.content = Object.assign({}, content);
  2471. } catch (e) {
  2472. console.log(e);
  2473. }
  2474.  
  2475. }
  2476.  
  2477. }
  2478.  
  2479. if (commentEntityAuthor && parentNodeController.isAttached === true && parentNode.isConnected === true) {
  2480. commentEntityAuthor.jkrgx = 1;
  2481. addCSSRulesIfRequired();
  2482. }
  2483.  
  2484. let commentReplyDialogRenderer;
  2485.  
  2486. const actionButtonsCnt = insp((parentNodeController.$ || 0)['action-buttons'] || 0);
  2487. if (actionButtonsCnt) {
  2488.  
  2489. try {
  2490. commentReplyDialogRenderer = actionButtonsCnt.__data.replyButtonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  2491. } catch (e) { }
  2492. }
  2493. const funcPromises = [];
  2494. commentReplyDialogRenderer && fixCommentReplyDialogRenderer(commentReplyDialogRenderer, funcPromises);
  2495.  
  2496.  
  2497. if (funcPromises.length >= 1) {
  2498. await Promise.all(funcPromises);
  2499. }
  2500.  
  2501. parentNodeController.commentEntity = Object.assign({}, parentNodeController.commentEntity);
  2502.  
  2503. }
  2504. } else {
  2505.  
  2506. const authorText = (parentNodeController.data || 0).authorText;
  2507. const currentDisplayed = getYTextContent(authorText || 0); // authorText.simpleText
  2508. if (typeof currentDisplayed !== 'string') return;
  2509. if (!isDisplayAsHandle(currentDisplayed)) return;
  2510.  
  2511. if (!channelIdToHandle.has(mt)) {
  2512. channelIdToHandle.set(mt, {
  2513. handleText: currentDisplayed.trim(),
  2514. justPossible: true
  2515. });
  2516. }
  2517.  
  2518. if (typeof parentNodeController.dataChanged === 'function' && !parentNodeController.dataChanged159) {
  2519. const cntp = parentNodeController.constructor.prototype;
  2520. const c = cntp.dataChanged === parentNodeController.dataChanged ? cntp : parentNodeController;
  2521. c.dataChanged159 = c.dataChanged;
  2522. c.dataChanged = function () {
  2523. resetWhenDataChanged(this);
  2524. return this.dataChanged159.apply(this, arguments);
  2525. };
  2526. }
  2527.  
  2528. const fetchResult = await getDisplayName(mt);
  2529.  
  2530. if (fetchResult === null) return;
  2531.  
  2532. const { title, langTitle, externalId } = fetchResult;
  2533. const titleForDisplay = langTitle || title;
  2534. if (externalId !== mt) return; // channel id must be the same
  2535.  
  2536. // anchor href might be changed by external
  2537. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  2538.  
  2539. const parentNodeData = parentNodeController.data;
  2540. const funcPromises = [];
  2541.  
  2542. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  2543.  
  2544. if (getYTextContent(authorText) !== currentDisplayed) return;
  2545. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  2546. const cSimpleText = (getYTextContent(parentNodeData.authorText || 0) || '');
  2547. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  2548.  
  2549. const md = Object.assign({}, parentNodeData);
  2550.  
  2551. // the inside hyperlinks will be only converted if its parent author name is handle
  2552. const contentTexts = (md.contentText || 0).runs;
  2553. if (contentTexts && contentTexts.length >= 1) {
  2554. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  2555. const r = contentTextProcess(md, contentTexts, aidx);
  2556. if (r instanceof Promise) funcPromises.push(r);
  2557. }
  2558. }
  2559.  
  2560. const authorCommentBadgeAuthorText = (((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0);
  2561.  
  2562. const authorCommentBadgeAuthorTextNew = authorCommentBadgeAuthorText ? setYTextContent(authorCommentBadgeAuthorText, (currentText) => {
  2563. if ((currentText || '').trim() === cSimpleText.trim()) {
  2564. return (currentText || '').replace((currentText || '').trim(), titleForDisplay);
  2565. } else {
  2566. return currentText;
  2567. }
  2568. }) : null;
  2569.  
  2570. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  2571. const authorTextNew = setYTextContent(md.authorText, (t) => t.replace(currentDisplayTrimmed, titleForDisplay))
  2572. md.authorText = authorTextNew;
  2573.  
  2574. if (authorCommentBadgeAuthorTextNew) {
  2575. const authorCommentBadgeRendererNew = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer, { authorText: authorCommentBadgeAuthorTextNew });
  2576. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge, { authorCommentBadgeRenderer: authorCommentBadgeRendererNew });
  2577. }
  2578.  
  2579. let setReplyEditableText = false;
  2580. if (((((((((parentNodeData.actionButtons || 0).commentActionButtonsRenderer || 0).replyButton || 0).buttonRenderer || 0).navigationEndpoint || 0).createCommentReplyDialogEndpoint || 0).dialog || 0).commentReplyDialogRenderer || 0).editableText) {
  2581. setReplyEditableText = true;
  2582. }
  2583. if (setReplyEditableText) {
  2584. const commentReplyDialogRenderer = parentNodeData.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  2585. fixCommentReplyDialogRenderer(commentReplyDialogRenderer, funcPromises);
  2586.  
  2587. }
  2588.  
  2589. if (UPDATE_PIN_NAME) {
  2590. updatePinnedCommentBadge(md, title, langTitle);
  2591. }
  2592.  
  2593. if (funcPromises.length >= 1) {
  2594. await Promise.all(funcPromises);
  2595. }
  2596.  
  2597. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  2598. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  2599. addCSSRulesIfRequired();
  2600. }
  2601.  
  2602.  
  2603. }
  2604.  
  2605. }
  2606. }
  2607. } catch (e) {
  2608. console.warn(e);
  2609. }
  2610.  
  2611. }
  2612.  
  2613. /**
  2614. *
  2615. * @param {string} url
  2616. * @returns
  2617. */
  2618. const channelUrlUnify = (url) => {
  2619.  
  2620. if (typeof url !== 'string') return url; // type unchanged
  2621. let c0 = url.charAt(0);
  2622. if (c0 === '/') return url;
  2623. let i = url.indexOf('.youtube.com/');
  2624. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  2625. else if (url.charAt(0) !== '/') url = '/' + url;
  2626. return url
  2627.  
  2628. }
  2629.  
  2630. const parentYtElement = (node, nodeName, maxN) => {
  2631. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  2632. if (pDom.nodeName === nodeName) {
  2633. return pDom;
  2634. }
  2635. }
  2636. return null;
  2637. }
  2638.  
  2639. const checkShortsChannelName = (rchannelNameDOM) => {
  2640. let browseId = '';
  2641. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  2642.  
  2643. if (pDom instanceof HTMLElement) {
  2644. const pDomController = insp(pDom);
  2645. const channelTitleText = (pDomController.data || 0).channelTitleText || 0;
  2646. const runs = ((channelTitleText || 0).runs || 0);
  2647. if (getYTextType(channelTitleText) === 4) {
  2648. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  2649. browseId = (browserEndpoint.browseId || '');
  2650. const currentDisplayText = runs[0].text || ''
  2651.  
  2652. if (isUCBrowserId(browseId) && isDisplayAsHandle(currentDisplayText)) {
  2653.  
  2654. if (!channelIdToHandle.has(browseId)) {
  2655. channelIdToHandle.set(browseId, {
  2656. handleText: currentDisplayText.trim(),
  2657. justPossible: true
  2658. });
  2659. }
  2660.  
  2661. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  2662. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  2663. // anchorNode &&
  2664. getDisplayName(browseId).then(fetchResult => {
  2665.  
  2666. if (fetchResult === null) return;
  2667.  
  2668. const { title, langTitle, externalId } = fetchResult;
  2669. const titleForDisplay = langTitle || title;
  2670. if (externalId !== browseId) return; // channel id must be the same
  2671.  
  2672. const hDom = pDom;
  2673. const hDomHostElement = hDom.hostElement || hDom;
  2674. const hDomController = insp(hDom);
  2675. const hData = (hDomController || 0).data || 0;
  2676. const hChannelTitleText = (hData || 0).channelTitleText || 0;
  2677. const runs = ((hChannelTitleText).runs || 0);
  2678. if (getYTextType(hChannelTitleText) === 4 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  2679.  
  2680. const channelTitleTextNew = { runs: [Object.assign({}, runs[0], { text: titleForDisplay })] }
  2681.  
  2682. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: channelTitleTextNew, rSk0e: 1 });
  2683. addCSSRulesIfRequired();
  2684.  
  2685. byPassCheckStore.delete(rchannelNameDOM);
  2686. }
  2687.  
  2688. })
  2689. }
  2690.  
  2691. }
  2692. }
  2693. return browseId
  2694. }
  2695.  
  2696. let firstDOMCheck = false;
  2697. const updateDisplayNameFn = (channelId, newName) => {
  2698. const cached = displayNameResStore.get(channelId);
  2699. if (typeof (cached || 0).title === 'string') {
  2700. cached.title = newName;
  2701. } else if (!cached) {
  2702. displayNameResStore.set(channelId, {
  2703. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  2704. externalId: `${channelId}`,
  2705. ownerUrls: [],
  2706. title: newName,
  2707. vanityChannelUrl: null,
  2708. verified123: true
  2709. });
  2710. } else {
  2711. console.warn('unexpected display name cache', cached);
  2712. }
  2713. };
  2714. const firstDOMChecker = isMobile ? () => {
  2715.  
  2716. let playerMicroformatRenderer = null;
  2717. try {
  2718. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  2719. } catch (e) { }
  2720. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  2721. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  2722. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  2723. }
  2724.  
  2725. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  2726. const channelNameCData = !channelNameDOM ? null : insp(channelNameDOM).data;
  2727.  
  2728. if (channelNameCData) {
  2729. let mainChannelUrl = null;
  2730. let mainFormattedNameUrl = null;
  2731. let mainChannelText = null;
  2732. let mainFormattedNameText = null;
  2733. let mainChannelBrowseId = null;
  2734.  
  2735. try {
  2736. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl) // channelUrlUnify("http://www.youtube.com/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2737. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl) // channelUrlUnify("/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2738. mainChannelText = channelNameCData.channelName
  2739. mainFormattedNameText = channelNameCData.title.runs[0].text
  2740. mainChannelBrowseId = channelNameCData.navigationEndpoint.browseEndpoint.browseId;
  2741. } catch (e) { }
  2742.  
  2743. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2744.  
  2745. const channelId = mainChannelBrowseId;
  2746. if (channelId) {
  2747. if (mainChannelText.startsWith('@')) return;
  2748. if (mainChannelText.trim() !== mainChannelText) return;
  2749. updateDisplayNameFn(channelId, mainChannelText);
  2750. }
  2751.  
  2752.  
  2753. }
  2754. }
  2755.  
  2756. } : () => {
  2757.  
  2758. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  2759. const channelNameCnt = insp(channelNameDOM);
  2760. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  2761. if (channelNameCData) {
  2762. let mainChannelUrl = null;
  2763. let mainFormattedNameUrl = null;
  2764. let mainChannelText = null;
  2765. let mainFormattedNameText = null;
  2766. let mainChannelBrowseId = null;
  2767. try {
  2768. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2769. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2770. mainChannelText = channelNameCData.channelName.runs[0].text
  2771. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  2772. mainChannelBrowseId = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.browseId;
  2773. } catch (e) { }
  2774.  
  2775. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2776.  
  2777. const m = exactHandleUrl(mainChannelUrl, false);
  2778.  
  2779. if (m && mainChannelText !== m) {
  2780.  
  2781. const channelHandle = m[1];
  2782. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  2783. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  2784. }
  2785.  
  2786. } else {
  2787.  
  2788. const channelId = mainChannelBrowseId;
  2789. if (channelId) {
  2790. if (mainChannelText.startsWith('@')) return;
  2791. if (mainChannelText.trim() !== mainChannelText) return;
  2792. updateDisplayNameFn(channelId, mainChannelText);
  2793. }
  2794.  
  2795. }
  2796. }
  2797. }
  2798.  
  2799. };
  2800.  
  2801. // let newAnchorAdded = false;
  2802. /*
  2803.  
  2804. const intersectionobserver = new IntersectionObserver((entries) => {
  2805. let anchorAppear = false;
  2806. for (const entry of entries) {
  2807. if (entry.isIntersecting === true) {
  2808. anchorAppear = true;
  2809. break;
  2810. }
  2811. }
  2812. if (anchorAppear && newAnchorAdded) {
  2813. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  2814. mutex.nextIndex = 0; // higher pirority for new elements being shown
  2815. }
  2816. }, {
  2817. rootMargin:"0px 0px 0px 0px",
  2818. threshold:1
  2819. })
  2820. */
  2821.  
  2822.  
  2823. /* globals WeakRef:false */
  2824.  
  2825. /** @type {(o: Object | null) => WeakRef | null} */
  2826. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  2827.  
  2828. /** @type {(wr: Object | null) => Object | null} */
  2829. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  2830.  
  2831. let doShortsChecking = false;
  2832. let doDescriptionChecking = true;
  2833.  
  2834. let lastNewAnchorLastWR = null;
  2835.  
  2836. const pipelineForDOMMutations = createPipeline();
  2837.  
  2838. const byPassCheckStore = new WeakSet();
  2839.  
  2840. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  2841. for (const mutation of mutations) {
  2842. const target = mutation.target;
  2843. if (!target) continue;
  2844. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  2845. if (!rchannelNameElm) continue;
  2846. const rchannelNameCnt = insp(rchannelNameElm);
  2847. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  2848. const channelId = rchannelNameElm.getAttribute('jkrgy');
  2849. if (channelId) {
  2850. if (byPassCheckStore.has(rchannelNameElm)) continue;
  2851. const handleObj = channelIdToHandle.get(channelId);
  2852. if (handleObj && handleObj.handleText && !handleObj.justPossible) {
  2853. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  2854. if (textDom) {
  2855. let t = textDom.textContent.trim()
  2856. if (t === handleObj.handleText || t === '') {
  2857. rchannelNameElm.removeAttribute('jkrgy');
  2858. // Promise.resolve().then(domChecker);
  2859. }
  2860. }
  2861. }
  2862. }
  2863. }
  2864. });
  2865.  
  2866. let domCheckScheduledForShorts = false;
  2867. const domCheckSelectorForShorts = [
  2868. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  2869. ].join(', ');
  2870.  
  2871.  
  2872. const domCheckerForShorts = async () => {
  2873.  
  2874. if (domCheckScheduledForShorts) return;
  2875. if (document.querySelector(domCheckSelectorForShorts) === null) {
  2876. return;
  2877. }
  2878. domCheckScheduledForShorts = true;
  2879.  
  2880. await pipelineForDOMMutations(async () => {
  2881.  
  2882. domCheckScheduledForShorts = false;
  2883. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  2884.  
  2885. try {
  2886.  
  2887. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  2888. if (nodes.length === 0) {
  2889. return;
  2890. }
  2891.  
  2892. for (const node of nodes) {
  2893.  
  2894. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  2895. if (rchannelNameElm) {
  2896. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  2897. childList: true,
  2898. subtree: true
  2899. });
  2900. byPassCheckStore.add(rchannelNameElm);
  2901. const channelId = checkShortsChannelName(rchannelNameElm);
  2902. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  2903. }
  2904.  
  2905. }
  2906.  
  2907. } catch (e) {
  2908. console.log('error occur', e);
  2909. }
  2910.  
  2911. });
  2912. domCheckScheduledForShorts = false;
  2913.  
  2914. };
  2915.  
  2916. /** @param {Element} s */
  2917. const domCheckerForDescriptionAnchor = (s) => {
  2918.  
  2919. findTextNodes(s, (textNode) => {
  2920. const p = textNode.nodeValue;
  2921. const index = p.indexOf('@');
  2922. if (index < 0) return;
  2923. const q = p.substring(index);
  2924. const b = isDisplayAsHandle(q);
  2925. if (b) {
  2926. const href = s.getAttribute('href')
  2927.  
  2928. const channelId = obtainChannelId(href);
  2929. if (channelId) {
  2930. const h = q.trim();
  2931.  
  2932. if (!firstDOMCheck) {
  2933. firstDOMCheck = true;
  2934. USE_CHANNEL_META && firstDOMChecker();
  2935. }
  2936.  
  2937. if (!channelIdToHandle.has(channelId)) {
  2938. channelIdToHandle.set(channelId, {
  2939. handleText: h,
  2940. justPossible: true
  2941. });
  2942. }
  2943.  
  2944. s.setAttribute('jkrgy', channelId);
  2945. getDisplayName(channelId).then(fetchResult => {
  2946.  
  2947. if (fetchResult === null) return;
  2948.  
  2949. const { title, langTitle, externalId } = fetchResult;
  2950. const titleForDisplay = langTitle || title;
  2951. if (externalId !== channelId) return; // channel id must be the same
  2952.  
  2953. const anchorElement = s;
  2954. const anchorTextNode = textNode;
  2955.  
  2956. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  2957.  
  2958. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  2959.  
  2960. }
  2961.  
  2962. });
  2963. }
  2964. }
  2965. return true;
  2966. });
  2967.  
  2968. }
  2969.  
  2970. // domCheckerForDescription: To be reviewed
  2971. // Example: https://www.youtube.com/watch?v=1NL-sIP9p_U
  2972. const domCheckerForDescription = isMobile ? () => {
  2973. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  2974. 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])')) {
  2975. s.setAttribute('dxcpj', '');
  2976. domCheckerForDescriptionAnchor(s);
  2977. }
  2978. } : () => {
  2979. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  2980. 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])')) {
  2981. s.setAttribute('dxcpj', '');
  2982. domCheckerForDescriptionAnchor(s);
  2983. }
  2984. };
  2985.  
  2986. const domCheckScheduledBools = [];
  2987. const domCheckScheduledSelectors = isMobile ? [
  2988. 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2989. 'a.comment-icon-container[href*="/@"]:not([jkrgy])', // Feb 2024
  2990. 'a.comment-icon-container[href*="channel/"]:not([jkrgy])' // Mar 2024
  2991. ] : [
  2992. 'a[id][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2993. 'a.yt-simple-endpoint.style-scope[id][href^="/@"]:not([jkrgy])', // Feb 2024
  2994. 'a.yt-simple-endpoint.style-scope[id][href^="http://www.youtube.com/@"]:not([jkrgy])' // Dec 2024
  2995. ];
  2996.  
  2997. const newAuthorAnchorsProceed = async (newAnchors) => {
  2998.  
  2999. const cNewAnchorFirst = newAnchors[0]; // non-null
  3000. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  3001. /** @type {HTMLElement | null} */
  3002. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  3003. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  3004.  
  3005. if (!firstDOMCheck) {
  3006. firstDOMCheck = true;
  3007. USE_CHANNEL_META && firstDOMChecker();
  3008. }
  3009.  
  3010. await Promise.resolve();
  3011.  
  3012. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  3013. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  3014. mutex.nextIndex = 0;
  3015. }
  3016. await Promise.resolve();
  3017. }
  3018.  
  3019. // newAnchorAdded = true;
  3020. for (const anchor of newAnchors) {
  3021. const hrefAttribute = anchor.getAttribute('href');
  3022. const hrefV = ytPathnameExtract(hrefAttribute);
  3023. let mChannelId = '';
  3024. const ytElm = isMobile ? closestYtmData(anchor) : closestYtParent(anchor);
  3025. if (ytElm) {
  3026. const cnt = insp(ytElm);
  3027. const { browseId, canonicalBaseUrl } = getAuthorBrowseEndpoint(cnt) || 0;
  3028. let wChannelId = '';
  3029. if (!browseId && !canonicalBaseUrl && cnt) {
  3030. // Dec 2024; no browserEndPoint -> urlEndpoint -> channelId not available
  3031. // comment view model -> commentEntity.author.channelId
  3032. const author = ((cnt.__data || cnt.data || 0).commentEntity || 0).author || 0;
  3033. if (author) {
  3034. const { channelId } = author;
  3035. const innertubeCommand = ((author || 0).channelPageEndpoint || 0).innertubeCommand || 0;
  3036. const endpoint = innertubeCommand.browseEndpoint || innertubeCommand.urlEndpoint || author.browseEndpoint || browseEndpoint.urlEndpoint || 0;
  3037. const url = endpoint.canonicalBaseUrl || endpoint.url || 0;
  3038. if (channelId && ytPathnameExtract(url) === hrefV && channelId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(channelId)) {
  3039. wChannelId = channelId;
  3040. }
  3041. }
  3042. } else if (browseId && ytPathnameExtract(canonicalBaseUrl) === hrefV && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId)) {
  3043. wChannelId = browseId;
  3044. }
  3045.  
  3046. if (wChannelId) {
  3047.  
  3048. const hrefType = getHrefType(hrefV);
  3049. // console.log(599, hrefV, hrefType)
  3050. if (hrefType === 1) {
  3051. if (hrefV === `/channel/${wChannelId}`) {
  3052. let authorText = null;
  3053. if (isMobile) { // mobile only
  3054. authorText = (cnt._commentData || cnt.data || ytElm._commentData || ytElm.data || 0).authorText || 0;
  3055. } else if (!isMobile) {
  3056. authorText = (cnt.data || 0).authorText || 0;
  3057. }
  3058. if (authorText) {
  3059. const text = getYTextContent(authorText);
  3060. if (typeof text === 'string' && text.startsWith('@') && exactHandleText(text, true)) {
  3061. channelIdToHandle.set(wChannelId, {
  3062. handleText: `${text}`,
  3063. justPossible: true
  3064. });
  3065. }
  3066. }
  3067. mChannelId = wChannelId;
  3068. }
  3069. } else if (hrefType === 2) {
  3070. const handle = hrefV.substring(2);
  3071. channelIdToHandle.set(wChannelId, {
  3072. handleText: `@${handle}`
  3073. });
  3074. mChannelId = wChannelId;
  3075. }
  3076.  
  3077. }
  3078.  
  3079. if (!mChannelId && hrefV) { // fallback
  3080.  
  3081. // author-text or name
  3082. // normal url: /channel/xxxxxxx
  3083. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  3084.  
  3085. const temp = obtainChannelId(hrefV); // string, can be empty
  3086. if (temp) {
  3087. mChannelId = temp;
  3088. }
  3089.  
  3090. }
  3091. }
  3092. anchor.setAttribute('jkrgy', mChannelId);
  3093. if (mChannelId) {
  3094. domCheckAsync(anchor, hrefAttribute, mChannelId);
  3095. }
  3096. }
  3097.  
  3098. }
  3099.  
  3100. const closestYtParent = (dom) => {
  3101. while (dom instanceof Element) {
  3102. if (typeof dom.is === 'string' && dom.is) return dom;
  3103. dom = dom.parentNode;
  3104. }
  3105. return null;
  3106. };
  3107. const closestYtmData = (dom) => {
  3108. while (dom instanceof Element) {
  3109. if (typeof (dom._commentData || dom.data || 0) === 'object') return dom;
  3110. dom = dom.parentNode;
  3111. }
  3112. return null;
  3113. };
  3114. /*
  3115. const cntWithParent = (cnt, parentSelector) => {
  3116. const hostElement = cnt.hostElement || cnt;
  3117. if (hostElement instanceof HTMLElement) {
  3118. return hostElement.closest(parentSelector);
  3119. }
  3120. return null;
  3121. }
  3122. */
  3123. const noAuthorDataSet = new Set();
  3124. const getAuthorBrowseEndpoint = (cnt) => {
  3125. let d;
  3126. let haveData = false;
  3127. if (isMobile) {
  3128. const data = ((cnt || 0).data || 0);
  3129. if (data) {
  3130. haveData = true;
  3131. if (d = (data.authorNameEndpoint || data.authorEndpoint)) return d.browseEndpoint || null;
  3132. }
  3133. } else {
  3134. const __data = ((cnt || 0).__data || 0);
  3135. if (__data) {
  3136. haveData = true;
  3137. if (d = __data.authorTextCommand) return d.browseEndpoint || null; // ytd-comment-renderer
  3138. if (d = (__data.authorNameEndpoint || __data.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (v1 & v2)
  3139. if ((d = (__data.data || 0)) && (d = (d.authorNameEndpoint || d.authorEndpoint))) return d.browseEndpoint || null; // ytd-author-comment-badge-renderer
  3140. // note: authorNameEndpoint instead of authorEndpoint for ytd-comment-view-model since 2024.04
  3141.  
  3142. } else {
  3143.  
  3144. if ((d = ((cnt || 0).data || 0)) && (d = (d.authorTextCommand || d.authorNameEndpoint || d.authorEndpoint))) return d.browseEndpoint || null; // ytd-comment-view-model (2024.05.25 ?)
  3145.  
  3146. if (d = (cnt.authorTextCommand || cnt.authorNameEndpoint || cnt.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (2024.04.30) (v3) (?)
  3147.  
  3148. }
  3149.  
  3150. }
  3151. if (haveData) {
  3152. const tag = cnt.is;
  3153. if (!noAuthorDataSet.has(tag)) {
  3154. noAuthorDataSet.add(tag);
  3155. if (tag === 'ytd-video-description-infocards-section-renderer') {
  3156. return null; // skip console logging
  3157. } else if (tag === 'ytd-thumbnail') {
  3158. return null;
  3159. } else if (tag === 'ytd-structured-description-channel-lockup-renderer') {
  3160. return null;
  3161. } else if (tag === 'ytd-rich-grid-media') {
  3162. return null;
  3163. } else if (tag === 'ytd-rich-metadata-renderer') {
  3164. return null;
  3165. } else if (tag === 'ytd-guide-entry-renderer') {
  3166. return null;
  3167. } else if (tag === 'ytd-grid-channel-renderer') {
  3168. return null;
  3169. } else if (tag === 'ytd-channel-renderer') {
  3170. return null;
  3171. }
  3172. console.log('no browseEndpoint can be found', tag);
  3173. }
  3174. } else {
  3175. console.log('no browseEndpoint can be found', (cnt || 0).is, 'NO DATA');
  3176. }
  3177. return null;
  3178. };
  3179.  
  3180. const domAuthorNameCheckN = async (kq) => {
  3181. if (domCheckScheduledBools[kq]) return;
  3182. const selector = domCheckScheduledSelectors[kq];
  3183. if (!selector || document.querySelector(selector) === null) return;
  3184. domCheckScheduledBools[kq] = true;
  3185. await pipelineForDOMMutations(async () => {
  3186. domCheckScheduledBools[kq] = false;
  3187. try {
  3188. const newAnchors = document.querySelectorAll(selector);
  3189. if (newAnchors.length === 0) return;
  3190. await newAuthorAnchorsProceed(newAnchors);
  3191. } catch (e) {
  3192. console.log('error occur', e);
  3193. }
  3194. });
  3195. domCheckScheduledBools[kq] = false;
  3196. };
  3197.  
  3198. let _lastAnchorCount = -1;
  3199. const anchorCollection = document.getElementsByTagName('A');
  3200.  
  3201. /*
  3202. const collectionChangeObserverFn = (collection)=>{
  3203. let _len = -1;
  3204. let ws = null;
  3205. ws = new WeakSet(collection);
  3206. return {check: ()=>{
  3207. const lastLen = _len;
  3208. const len = collection.length;
  3209. if(len !== lastLen){
  3210. ws = new WeakSet(collection);
  3211. return true;
  3212. }
  3213. for (const elm of collection) {
  3214. if (!ws.has(elm)){
  3215. ws = new WeakSet(collection);
  3216. return true;
  3217. }
  3218. }
  3219. return false;
  3220. }}
  3221.  
  3222. }
  3223. */
  3224.  
  3225. const domChecker = (mutations) => {
  3226.  
  3227. const currAnchorCount = anchorCollection.length;
  3228. const lastAnchorCount = _lastAnchorCount;
  3229. _lastAnchorCount = currAnchorCount;
  3230. if (currAnchorCount === 0) return;
  3231.  
  3232. if (mutations && lastAnchorCount === currAnchorCount) {
  3233. // test to skip
  3234. let state = 0;
  3235. let addedNonElement = false;
  3236. for (const mutation of mutations) {
  3237. const addedNodes = mutation.addedNodes || 0;
  3238. const removedNodes = mutation.removedNodes || 0;
  3239. const target = mutation.target || 0;
  3240. if (target.nodeName === 'YT-FORMATTED-STRING') continue; // ignore changes in <yt-formatted-string>
  3241. if (addedNodes.length >= 1) {
  3242. state |= 1;
  3243. if (!addedNonElement) {
  3244. for (const addedNode of addedNodes) {
  3245. if (!(addedNode instanceof Element)) {
  3246. addedNonElement = true;
  3247. break;
  3248. }
  3249. }
  3250. }
  3251. if (state & 2) break;
  3252. } else if (removedNodes.length >= 1) {
  3253. state |= 2;
  3254. if (state & 1) break;
  3255. } else {
  3256. state |= 4;
  3257. break;
  3258. }
  3259. }
  3260. if (state === 1) {
  3261. if (!addedNonElement) return; // no change in anchor
  3262. } else if (state === 2) {
  3263. return; // only removal
  3264. } else if (state === 0) {
  3265. return; // no recognized mutation
  3266. }
  3267. }
  3268.  
  3269. doShortsChecking && domCheckerForShorts();
  3270. doDescriptionChecking && domCheckerForDescription();
  3271. for (let i = 0; i < domCheckScheduledSelectors.length; i++) domAuthorNameCheckN(i);
  3272.  
  3273. };
  3274.  
  3275.  
  3276. /** @type {MutationObserver | null} */
  3277. let domObserver = null;
  3278.  
  3279. /** @type {(callback: (event: Event)=>{})} */
  3280. const onPageFetched = isMobile ? (callback) => {
  3281.  
  3282. let state = 0;
  3283.  
  3284. window.addEventListener('state-change', function (evt) {
  3285. if (state === 1) return; // ignore intermediate events
  3286. state = 1; // before value: 0 or 2;
  3287. callback(evt);
  3288. }, false);
  3289.  
  3290. window.addEventListener('state-navigateend', function (evt) { // fallback
  3291. let inSeq = state === 1;
  3292. state = 2; // 2 when loaded
  3293. if (!inSeq) callback(evt);
  3294. }, false);
  3295.  
  3296. } : (callback) => {
  3297.  
  3298. let state = 0;
  3299.  
  3300. document.addEventListener('yt-page-data-fetched', function (evt) {
  3301. if (state === 1) return; // ignore intermediate events if any
  3302. state = 1; // before value: 0 or 2;
  3303. callback(evt);
  3304. }, false);
  3305.  
  3306. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  3307. let inSeq = state === 1;
  3308. state = 2; // 2 when loaded
  3309. if (!inSeq) callback(evt);
  3310. }, false);
  3311.  
  3312. };
  3313.  
  3314.  
  3315. // let mActive = false;
  3316. // let lastContent = '';
  3317. const removeAttrs = () => {
  3318. for (const s of document.querySelectorAll('a[href][dxcpj]')) {
  3319. s.removeAttribute('dxcpj');
  3320. }
  3321. for (const s of document.querySelectorAll('a[href][jkrgy]')) {
  3322. s.removeAttribute('jkrgy');
  3323. }
  3324. }
  3325.  
  3326. // setInterval(() => {
  3327. // if (!mActive) return;
  3328. // let content = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  3329. // if (content !== lastContent) {
  3330. // lastContent = content;
  3331. // removeAttrs();
  3332. // }
  3333. // }, 400);
  3334.  
  3335. /**
  3336. *
  3337. * @param {Node} app
  3338. * @returns
  3339. */
  3340. function setupOnPageFetched(app) {
  3341.  
  3342. firstDOMCheck = false;
  3343.  
  3344. if (!cfg['INNERTUBE_API_KEY']) {
  3345. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  3346. return;
  3347. }
  3348.  
  3349. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  3350. doShortsChecking = true;
  3351. } else {
  3352. doShortsChecking = false;
  3353. }
  3354.  
  3355. _lastAnchorCount = -1;
  3356.  
  3357. if (!domObserver) {
  3358. domObserver = new MutationObserver(domChecker);
  3359. } else {
  3360. domObserver.takeRecords();
  3361. domObserver.disconnect();
  3362. }
  3363.  
  3364. // lastContent = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  3365. // mActive = true;
  3366. removeAttrs();
  3367.  
  3368. domObserver.observe(app, { childList: true, subtree: true, attributes: true, attributeFilter: ['jkrgy', 'href', 'dxcpj'] });
  3369. domChecker();
  3370.  
  3371. }
  3372.  
  3373. /**
  3374. *
  3375. * @param {Object|null} dest
  3376. * @param {Object} ytcfg
  3377. * @param {string[]} keys
  3378. * @returns
  3379. */
  3380. function getYtConfig(dest, ytcfg, keys) {
  3381. dest = dest || {};
  3382. if (typeof ytcfg.get === 'function') { // mobile
  3383. for (const key of keys) {
  3384. dest[key] = ytcfg.get(key);
  3385. }
  3386. } else {
  3387. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  3388. for (const key of keys) {
  3389. dest[key] = cfgData[key];
  3390. }
  3391. }
  3392. return dest;
  3393. }
  3394.  
  3395. /** @type { (evt: Object) => Element | null } */
  3396. const getPageApp = isMobile
  3397. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  3398. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  3399.  
  3400. onPageFetched(async (evt) => {
  3401. const app = getPageApp(evt);
  3402. console.assert(app);
  3403. const ytcfg = ((window || 0).ytcfg || 0);
  3404. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  3405. setupOnPageFetched(app);
  3406. });
  3407.  
  3408. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });