Restore YouTube Username from Handle to Custom

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

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