Restore YouTube Username from Handle to Custom

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

目前为 2024-04-30 提交的版本。查看 最新版本

  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.11.019
  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}
  139. */
  140.  
  141. /**
  142. @typedef {string} ChannelId
  143. * UC[-_a-zA-Z0-9+=.]{22}
  144. * https://support.google.com/youtube/answer/6070344?hl=en
  145. * The channel ID is the 24 character alphanumeric string that starts with 'UC' in the channel URL.
  146. */
  147.  
  148. /**
  149. @typedef {string} DisplayName
  150. * Display Name
  151. */
  152.  
  153. /**
  154. @typedef DisplayNameResultObject
  155. @type {Object}
  156. @property {DisplayName} title
  157. @property {DisplayName} langTitle
  158. @property {ChannelId?} externalId
  159. @property {string[]} ownerUrls
  160. @property {string} channelUrl
  161. @property {string} vanityChannelUrl
  162. @property {boolean|undefined} verified123
  163. */
  164.  
  165. /**
  166. @typedef ChannelIdToHandleResult
  167. @type {Object}
  168. @property {HandleText} handleText
  169. @property {boolean} justPossible
  170. */
  171.  
  172. (function (__CONTEXT__) {
  173. 'use strict';
  174.  
  175. const USE_RSS_FETCHER = true; // might 404
  176. const USE_TIMEOUT_SIGNAL = false;
  177. const USE_CHANNEL_META = true;
  178. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  179. const USE_LANG_SPECIFIC_NAME = true;
  180. const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
  181. const FIX_RTL_ISSUE = true;
  182.  
  183. const IGNORE_NO_NAME = false;
  184.  
  185. /** @type {globalThis.PromiseConstructor} */
  186. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  187.  
  188. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  189.  
  190. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  191. let controller = new AbortController();
  192. const r = controller.signal;
  193. let cid = setTimeout(() => {
  194. if (cid >= 1) {
  195. cid = 0;
  196. controller && controller.abort();
  197. controller = null;
  198. }
  199. }, timeout);
  200. r.clearTimeout = () => {
  201. if (cid >= 1) {
  202. clearTimeout(cid);
  203. cid = 0;
  204. }
  205. }
  206. return r;
  207. } : () => { };
  208.  
  209. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  210.  
  211. const fxOperator = (proto, propertyName) => {
  212. let propertyDescriptorGetter = null;
  213. try {
  214. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  215. // https://github.com/cyfung1031/userscript-supports/issues/9
  216. // .parentNode becomes DocumentFragment
  217. /**
  218. *
  219. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  220. *
  221. * e.g. ytd-comment-renderer#comment > div#body
  222. *
  223. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  224. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  225. *
  226. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  227. *
  228. * Alternative way: ytCustomElement.$.xxxxxxx
  229. *
  230. */
  231. } catch (e) { }
  232. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  233. };
  234.  
  235. const fxAPI = (proto, propertyName) => {
  236. const methodFunc = proto[propertyName];
  237. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  238. };
  239.  
  240. /** @type { (node: Node)=>Node | null } */
  241. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  242. /** @type { (node: Node)=>Node | null } */
  243. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  244. /** @type { (node: Node)=>Node | null } */
  245. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  246.  
  247. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  248. const elementQS = fxAPI(Element.prototype, 'querySelector');
  249. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  250. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  251.  
  252. /*
  253.  
  254.  
  255. init
  256.  
  257. initialdata
  258. state-progress
  259. state-responsereceived
  260. player-autonav-pause
  261. state-change
  262. state-navigateend
  263. player-initialized
  264. renderer-module-load-start
  265. video-data-change
  266. player-state-change
  267. updateui
  268. renderer-module-load-end -> channel owner DOM available
  269. player-autonav-pause
  270. updateui
  271. renderer-module-load-start
  272. updateui
  273. renderer-module-load-end
  274.  
  275.  
  276. playing
  277.  
  278. h5player.video-progress
  279. h5player.video-progress
  280. h5player.video-progress
  281. h5player.video-progress
  282. ...
  283.  
  284.  
  285.  
  286.  
  287. navigate new video
  288.  
  289. state-navigatestart
  290. state-change => channel owener DOM vanished
  291. state-progress
  292. ...
  293. h5player.player-state-change
  294. h5player.video-data-change
  295. h5player.player-state-change
  296. h5player.muted-autoplay-change
  297. h5player.volume-change
  298. h5player.video-data-change
  299. h5player.volume-change
  300. ...
  301.  
  302. state-progress
  303. ...
  304.  
  305. state-progress => channel owner DOM appear [just before state-responsereceived]
  306. state-responsereceived
  307.  
  308. video-data-change
  309. state-change
  310. state-navigateend
  311.  
  312.  
  313.  
  314.  
  315. UX interaction
  316.  
  317. user-activity
  318. player-autonav-pause
  319.  
  320.  
  321.  
  322.  
  323.  
  324. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  325.  
  326. EventTarget.prototype.dispatchEvent = function (ev) {
  327. if (ev instanceof Event) {
  328. if (ev.type === 'video-progress') { } else {
  329. console.log(ev.type, this, ev.target)
  330. if (ev.target === null) {
  331. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  332. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  333. }
  334. }
  335. }
  336. return this.uhfsE.apply(this, arguments);
  337. }
  338.  
  339.  
  340.  
  341. */
  342.  
  343. const isMobile = location.hostname === 'm.youtube.com';
  344.  
  345. const cfg = {};
  346. class Mutex {
  347.  
  348. constructor() {
  349. this.p = Promise.resolve()
  350. }
  351.  
  352. /**
  353. * @param {(lockResolve: () => void)} f
  354. */
  355. lockWith(f) {
  356. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  357. }
  358.  
  359. }
  360.  
  361. class OrderedMutex extends Mutex {
  362. constructor() {
  363. super();
  364. this.nextIndex = 0;
  365. this.arr = [];
  366. this.lockFunc = resolve => {
  367. if (this.arr.length >= 1) {
  368. let f = this.arr[0];
  369. if (typeof f === 'function') {
  370. this.arr.shift();
  371. if (this.nextIndex > 0) this.nextIndex--;
  372. f(resolve);
  373. return;
  374. } else {
  375. // reset if unknown error
  376. this.arr.length = 0;
  377. this.nextIndex = 0;
  378. }
  379. }
  380. resolve();
  381. };
  382. }
  383. /**
  384. * @param {(lockResolve: () => void)} f
  385. */
  386. add(f) {
  387. if (this.nextIndex === this.arr.length) {
  388. this.arr.push(f); this.nextIndex++;
  389. } else {
  390. this.arr.splice(this.nextIndex++, 0, f);
  391. }
  392. this.lockWith(this.lockFunc);
  393. }
  394. }
  395. // usage: run network request one by one
  396. const mutex = new OrderedMutex();
  397.  
  398. const createPipeline = () => {
  399. let pipelineMutex = Promise.resolve();
  400. const pipelineExecution = fn => {
  401. return new Promise((resolve, reject) => {
  402. pipelineMutex = pipelineMutex.then(async () => {
  403. let res;
  404. try {
  405. res = await fn();
  406. } catch (e) {
  407. console.log('error_F1', e);
  408. reject(e);
  409. }
  410. resolve(res);
  411. }).catch(console.warn);
  412. });
  413. };
  414. return pipelineExecution;
  415. };
  416.  
  417. /**
  418. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  419. * @template T */
  420.  
  421. /**
  422. * usage: cache the network result per web application instance.
  423. * @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  424. const displayNameResStore = new Map();
  425.  
  426. /**
  427. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  428. * @type {WeakMap<Function, Function>} */
  429. const dataChangedFuncStore = new WeakMap();
  430.  
  431. /**
  432. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  433. * @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
  434. const handleToChannelId = new Map();
  435.  
  436. /**
  437. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  438. * @type {Map<ChannelId, ChannelIdToHandleResult>} */
  439. const channelIdToHandle = new Map();
  440.  
  441. /**
  442. * usage: replace handle to lang-specific display name
  443. * @type {Map<HandleText, DisplayName>} */
  444. const langPreferredDisplayNameMap = new Map();
  445.  
  446. /**
  447. * AsyncValue
  448. * @class
  449. * @template T
  450. */
  451. class AsyncValue {
  452. constructor() {
  453. /** @type {T | null} */
  454. this.__value__ = null;
  455. /** @type {((value: any)=>void) | null} */
  456. this.__resolve__ = null;
  457. this.__promise__ = new Promise(resolve => {
  458. this.__resolve__ = resolve;
  459. });
  460. }
  461. /**
  462. *
  463. * @param {T} value
  464. */
  465. setValue(value) {
  466. const promise = this.__promise__;
  467. if (promise === null) throw 'Value has already been set.';
  468. this.__value__ = value;
  469. this.__promise__ = null;
  470. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  471. }
  472. /**
  473. *
  474. * @returns {Promise<T>}
  475. */
  476. async getValue() {
  477. const promise = this.__promise__;
  478. if (promise === null) return this.__value__;
  479. await promise; // promise become null
  480. this.__promise__ = null; // just in case
  481. this.__resolve__ = null;
  482. return this.__value__;
  483. }
  484. }
  485.  
  486. let isCSSAdded = false;
  487. const addCSSRulesIfRequired = () => {
  488. if (isCSSAdded) return;
  489. isCSSAdded = true;
  490. const style = document.createElement('style')
  491. let nonce = document.querySelector('head style[nonce]');
  492. nonce = nonce ? nonce.getAttribute('nonce') : null;
  493.  
  494. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (LTR, when mixed with LTR languages) */
  495. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (pure) */
  496.  
  497. const cssText01_FIX_RTL_ISSUE = FIX_RTL_ISSUE ? `
  498.  
  499. /* Left-to-Right (LTR) Languages */
  500. #contenteditable-root.yt-formatted-string:lang(en) /* English */,
  501. #contenteditable-root.yt-formatted-string:lang(es) /* Spanish */,
  502. #contenteditable-root.yt-formatted-string:lang(fr) /* French */,
  503. #contenteditable-root.yt-formatted-string:lang(de) /* German */,
  504. #contenteditable-root.yt-formatted-string:lang(it) /* Italian */,
  505. #contenteditable-root.yt-formatted-string:lang(pt) /* Portuguese */,
  506. #contenteditable-root.yt-formatted-string:lang(ru) /* Russian */,
  507. #contenteditable-root.yt-formatted-string:lang(zh) /* Chinese */,
  508. #contenteditable-root.yt-formatted-string:lang(ja) /* Japanese */,
  509. #contenteditable-root.yt-formatted-string:lang(ko) /* Korean */,
  510. #contenteditable-root.yt-formatted-string:lang(nl) /* Dutch */,
  511. #contenteditable-root.yt-formatted-string:lang(sv) /* Swedish */,
  512. #contenteditable-root.yt-formatted-string:lang(fi) /* Finnish */,
  513. #contenteditable-root.yt-formatted-string:lang(da) /* Danish */,
  514. #contenteditable-root.yt-formatted-string:lang(no) /* Norwegian */,
  515. #contenteditable-root.yt-formatted-string:lang(pl) /* Polish */,
  516. #contenteditable-root.yt-formatted-string:lang(cs) /* Czech */,
  517. #contenteditable-root.yt-formatted-string:lang(sk) /* Slovak */,
  518. #contenteditable-root.yt-formatted-string:lang(hu) /* Hungarian */,
  519. #contenteditable-root.yt-formatted-string:lang(tr) /* Turkish */,
  520. #contenteditable-root.yt-formatted-string:lang(el) /* Greek */,
  521. #contenteditable-root.yt-formatted-string:lang(id) /* Indonesian */,
  522. #contenteditable-root.yt-formatted-string:lang(ms) /* Malay */,
  523. #contenteditable-root.yt-formatted-string:lang(th) /* Thai */,
  524. #contenteditable-root.yt-formatted-string:lang(vi) /* Vietnamese */
  525. {
  526. direction: ltr;
  527. }
  528.  
  529. /* Right-to-Left (RTL) Languages */
  530. #contenteditable-root.yt-formatted-string:lang(ar) /* Arabic */,
  531. #contenteditable-root.yt-formatted-string:lang(fa) /* Persian */,
  532. #contenteditable-root.yt-formatted-string:lang(ur) /* Urdu */,
  533. #contenteditable-root.yt-formatted-string:lang(dv) /* Divehi */
  534. {
  535. direction: rtl;
  536. }
  537.  
  538. ` : '';
  539. style.textContent = `
  540. ${cssText01_FIX_RTL_ISSUE}
  541. `.trim();
  542. if (nonce) style.setAttribute('nonce', nonce);
  543. document.head.appendChild(style);
  544. }
  545.  
  546. /**
  547. *
  548. * @param {DisplayNameResultObject} resultInfo
  549. * @param {string} channelId
  550. */
  551. const cacheHandleToChannel = (resultInfo, channelId) => {
  552.  
  553. const { vanityChannelUrl, ownerUrls } = resultInfo;
  554.  
  555. let handleText = urlToHandle(vanityChannelUrl || '');
  556.  
  557. if (handleText) {
  558. // match = true;
  559. } else if ((ownerUrls || 0).length >= 1) {
  560. for (const ownerUrl of ownerUrls) {
  561. handleText = urlToHandle(ownerUrl || '');
  562.  
  563. if (handleText) {
  564. // match = true;
  565. break;
  566. }
  567. }
  568. }
  569. if (handleText) {
  570.  
  571. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  572. if (asyncValue instanceof AsyncValue) {
  573. asyncValue.setValue(channelId);
  574. }
  575. handleToChannelId.set(handleText, channelId);
  576. }
  577.  
  578.  
  579. }
  580.  
  581. /**
  582. *
  583. * @param {string} channelId
  584. * @param {Function} onDownloaded
  585. * @param {Function} onResulted
  586. * @param {Function} onError
  587. */
  588. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  589.  
  590. let signal = timeoutSignal(4000);
  591.  
  592. const requestBody = {
  593. "context": {
  594. "client": {
  595. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  596. "clientName": "MWEB", // "WEB", "MWEB"
  597. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  598. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  599. "playerType": "UNIPLAYER",
  600. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  601. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  602. "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",
  603. "mainAppWebInfo": {
  604. "graftUrl": `/channel/${channelId}`,
  605. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  606. "isWebNativeShareAvailable": true
  607. }
  608. },
  609. "user": {
  610. "lockedSafetyMode": false
  611. },
  612. "request": {
  613. "useSsl": true,
  614. "internalExperimentFlags": [],
  615. "consistencyTokenJars": []
  616. }
  617. },
  618. "browseId": `${channelId}`
  619. };
  620.  
  621. if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
  622. Object.assign(requestBody.context.client, {
  623. "hl": cfg.HL,
  624. "gl": cfg.GL,
  625. });
  626. }
  627.  
  628. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  629. "method": "POST",
  630. "mode": "same-origin",
  631. "credentials": "omit",
  632.  
  633. referrerPolicy: "no-referrer",
  634. cache: "default", // no effect on POST request
  635. // cache: "force-cache",
  636. redirect: "error", // there shall be no redirection in this API request
  637. integrity: "",
  638. keepalive: false,
  639. signal,
  640.  
  641. "headers": {
  642. "Content-Type": "application/json", // content type of the body data in POST request
  643. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  644. // X-Youtube-Bootstrap-Logged-In: false,
  645. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  646. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  647.  
  648. "Accept": "application/json",
  649. },
  650. "body": JSON.stringify(requestBody)
  651. })).then(res => {
  652. signal && signal.clearTimeout && signal.clearTimeout();
  653. signal = null;
  654. onDownloaded();
  655. onDownloaded = null;
  656. return res.json();
  657. }).then(resJson => {
  658. const resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  659. const title = resultInfo ? resultInfo.title : null;
  660. if (title || title === '') {
  661.  
  662. resultInfo.title = '';
  663. resultInfo.langTitle = title;
  664.  
  665. if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
  666. let matched = false;
  667.  
  668. const ownerProfileUrlLowerCase = cfg.ownerProfileUrl.toLowerCase();
  669. if (ownerProfileUrlLowerCase.endsWith(`/channel/${channelId.toLowerCase()}`)) matched = true;
  670. else {
  671.  
  672. for (const ownerUrl of resultInfo.ownerUrls) {
  673. if (ownerUrl.toLowerCase().endsWith(ownerProfileUrlLowerCase)) {
  674. matched = true;
  675. break;
  676. }
  677. }
  678.  
  679. }
  680.  
  681. if (matched) {
  682. resultInfo.title = cfg.ownerChannelName;
  683. }
  684. }
  685.  
  686. }
  687.  
  688. onResulted(resultInfo);
  689. onResulted = null;
  690. }).catch(onError);
  691.  
  692. };
  693.  
  694. /**
  695. *
  696. * @param {string} channelId
  697. * @param {Function} onDownloaded
  698. * @param {Function} onResulted
  699. * @param {Function} onError
  700. */
  701. let fetchRSSFailed = false;
  702. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  703.  
  704. let signal = timeoutSignal(4000);
  705. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  706. // YouTube RSS Response - public, max-age=900
  707.  
  708. "method": "GET",
  709. "mode": "same-origin",
  710. "credentials": "omit",
  711.  
  712. referrerPolicy: "no-referrer",
  713. cache: "default",
  714. // cache: "no-cache",
  715. redirect: "error", // there shall be no redirection in this API request
  716. integrity: "",
  717. keepalive: false,
  718. signal,
  719.  
  720. "headers": {
  721. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  722. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  723. // seems YouTube RSS Feeds server insists its own Cache-Control.
  724.  
  725. // "Content-Type": "text/xml; charset=UTF-8",
  726. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  727. // X-Youtube-Bootstrap-Logged-In: false,
  728. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  729. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  730.  
  731. "Accept": "text/xml",
  732. }
  733. }).then(res => {
  734.  
  735. signal && signal.clearTimeout && signal.clearTimeout();
  736. signal = null;
  737.  
  738. if (res.ok === true && res.redirected === false && res.status === 200 && res.type === "basic") {
  739.  
  740. onDownloaded();
  741. onDownloaded = null;
  742. return res.text();
  743.  
  744. }
  745. return null;
  746.  
  747. }).then(resText => {
  748. if (resText && typeof resText === 'string' && resText.includes('<feed') && !resText.includes('<!DOCTYPE')) {
  749.  
  750. } else {
  751. if (onDownloaded) {
  752.  
  753. onDownloaded();
  754. onDownloaded = null;
  755. }
  756. onResulted(-1);
  757. return;
  758.  
  759. }
  760.  
  761.  
  762. // console.log(124, , resText)
  763. let eIdx = resText.indexOf('<entry>');
  764. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  765.  
  766. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  767. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  768. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  769. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  770.  
  771.  
  772. let name, uri, mt;
  773.  
  774. // ===============================================================
  775.  
  776. /* removed in 2023.06.30 */
  777.  
  778.  
  779. // ===============================================================
  780.  
  781.  
  782. const wIdx1 = mText.indexOf('<author>');
  783. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  784.  
  785. if (wIdx1 > 0 && wIdx2 > 0) {
  786. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  787. const template = document.createElement('template');
  788. template.innerHTML = qText;
  789. /** @type {HTMLElement | null} */
  790. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  791. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  792. const nodeName = authorChild.nodeName;
  793. if (nodeName === 'NAME') name = authorChild.textContent;
  794. else if (nodeName === 'URI') {
  795. uri = authorChild.textContent;
  796. mt = obtainChannelId(uri);
  797. }
  798. }
  799. template.innerHTML = '';
  800. }
  801.  
  802. if (!name && !uri) {
  803.  
  804. // fallback
  805.  
  806. const parser = new DOMParser();
  807. const xmlDoc = parser.parseFromString(mText, "text/xml");
  808.  
  809. // const author = xmlDoc.querySelector("author");
  810.  
  811. // https://extendsclass.com/xpath-tester.html
  812.  
  813. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  814.  
  815. let authorChild;
  816. while ((authorChild = authorChilds.iterateNext()) !== null) {
  817. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  818. else if (authorChild.nodeName === 'uri') {
  819. uri = authorChild.textContent;
  820. mt = obtainChannelId(uri);
  821. }
  822. }
  823.  
  824. try {
  825. xmlDoc.firstChild.remove();
  826. } catch (e) { }
  827.  
  828. }
  829.  
  830.  
  831.  
  832.  
  833. let res = null;
  834.  
  835. if ((name || name === '') && uri && mt && mt === channelId) {
  836.  
  837.  
  838. const handleObj = channelIdToHandle.get(mt);
  839.  
  840. if (handleObj) {
  841.  
  842. const handleText = handleObj.handleText;
  843.  
  844. if (handleText === name) channelIdToHandle.delete(mt);
  845. else {
  846. handleObj.justPossible = false; // ignore @handle checking
  847.  
  848. res = {
  849. "title": name,
  850. "externalId": mt,
  851. "ownerUrls": [
  852. `http://www.youtube.com/${handleText}`
  853. ],
  854. "channelUrl": uri,
  855. "vanityChannelUrl": `http://www.youtube.com/${handleText}`
  856. };
  857.  
  858. if (USE_LANG_SPECIFIC_NAME) {
  859. const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
  860. if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
  861. }
  862.  
  863. }
  864. }
  865. }
  866.  
  867. onResulted(res);
  868. onResulted = null;
  869.  
  870. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  871. // onResulted(resultInfo);
  872. }).catch(onError);
  873.  
  874.  
  875.  
  876. }
  877.  
  878. sessionStorage.setItem('js-yt-usernames', '');
  879. let isFirstStackNewRequestSuccess = true;
  880. /**
  881. *
  882. * @param {string} channelId
  883. */
  884. function stackNewRequest(channelId) {
  885.  
  886. mutex.add(lockResolve => {
  887.  
  888. let bResult = displayNameResStore.get(channelId);
  889. if (!(bResult instanceof AsyncValue)) {
  890. // resolved or removed
  891. lockResolve(); lockResolve = null;
  892. return;
  893. }
  894.  
  895. let setResult = (result) => {
  896. setResult = null;
  897. if (!result) {
  898. bResult.fetchingState = 0;
  899. bResult.setValue(null);
  900. displayNameResStore.delete(channelId); // create another network response in the next request
  901. } else {
  902. bResult.fetchingState = 4;
  903. bResult.setValue(result);
  904. displayNameResStore.set(channelId, result); // update store result to resolved value
  905. }
  906. bResult = null;
  907. }
  908.  
  909. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  910. // request is already done. no need to stack any request
  911. lockResolve(); lockResolve = null;
  912. return;
  913. }
  914.  
  915. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  916. // element has already been removed
  917. lockResolve(); lockResolve = null;
  918. setResult(null);
  919. return;
  920. }
  921.  
  922. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  923.  
  924. bResult.fetchingState = 2;
  925.  
  926.  
  927. const retry = () => {
  928.  
  929. fetchRSSFailed = true;
  930.  
  931. bResult.fetchingState = 2;
  932.  
  933. // Promise.resolve(channelId).then(stackNewRequest);
  934. fetcherBrowseAPI(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  935. }
  936.  
  937. const mobj = {
  938. fetchOnDownload: () => {
  939. bResult.fetchingState = 3;
  940. },
  941. fetchOnSuccess: resultInfo => {
  942.  
  943. if (resultInfo === -1) {
  944. retry();
  945. return;
  946. }
  947.  
  948. lockResolve && lockResolve();
  949. lockResolve = null;
  950. // console.log(900)
  951.  
  952. if (!resultInfo) {
  953. // invalid json format
  954. setResult(null);
  955. return;
  956. }
  957.  
  958. const titleForDisplay = resultInfo.langTitle || resultInfo.title;
  959. const handleObj = channelIdToHandle.get(channelId);
  960. const handleId = handleObj ? handleObj.handleText : '';
  961. if (IGNORE_NO_NAME && !titleForDisplay) {
  962. if (handleId) {
  963. resultInfo.langTitle = resultInfo.title = handleObj.handleText;
  964. } else {
  965. setResult(null);
  966. return;
  967. }
  968. }
  969.  
  970. cacheHandleToChannel(resultInfo, channelId);
  971.  
  972. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  973.  
  974. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  975.  
  976. if (handleId) {
  977. if (isFirstStackNewRequestSuccess) {
  978. isFirstStackNewRequestSuccess = false;
  979. sessionStorage.setItem('js-yt-usernames', `${handleId}\t${titleForDisplay}`);
  980. } else {
  981. let current = sessionStorage.getItem('js-yt-usernames') || '';
  982. if (current.length > 900000) {
  983. const na = current.split('\n');
  984. const n3 = Math.floor(na.length / 3);
  985. if (n3 > 2) {
  986. const newText = na.slice(0, n3).concat(na.slice(na.length - n3)).join('\n');
  987. if (newText.length < 720000) {
  988. current = newText;
  989. }
  990. }
  991. }
  992. sessionStorage.setItem('js-yt-usernames', `${current}\n${handleId}\t${titleForDisplay}`);
  993. }
  994. }
  995.  
  996. setResult(displayNameRes);
  997. },
  998. fetchOnFail: e => {
  999.  
  1000.  
  1001. console.warn(e);
  1002. if (mobj.fetcher === fetcherRSS) {
  1003. retry();
  1004.  
  1005. } else {
  1006.  
  1007. lockResolve && lockResolve();
  1008. lockResolve = null;
  1009. // console.warn(e);
  1010. setResult && setResult(null);
  1011. }
  1012. }
  1013. }
  1014.  
  1015.  
  1016. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  1017. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  1018. mobj.fetcher = USE_RSS_FETCHER && fetcherRSS && !fetchRSSFailed && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  1019. mobj.fetcher(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  1020.  
  1021. });
  1022.  
  1023. }
  1024.  
  1025. /**
  1026. *
  1027. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  1028. * @returns Example: _\@yr__kd_
  1029. */
  1030. function urlToHandle(url) {
  1031.  
  1032. if (typeof url !== 'string') return '';
  1033. let i = url.indexOf('.youtube.com/');
  1034. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  1035. else if (url.charAt(0) === '/') url = url.substring(1);
  1036. return isDisplayAsHandle(url) ? url : '';
  1037.  
  1038. }
  1039.  
  1040. /**
  1041. *
  1042. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  1043. * @returns {Promise<DisplayNameResultObject | null>}
  1044. */
  1045. async function getDisplayName(channelId) {
  1046.  
  1047. let cache = displayNameResStore.get(channelId);
  1048. let isStackNewRequest = false;
  1049.  
  1050. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  1051. let aResult;
  1052.  
  1053. if (cache instanceof AsyncValue) {
  1054. aResult = cache;
  1055. if (aResult.fetchingState >= 2) {
  1056. // aResult.fetchingState
  1057. // 2: network fetch started
  1058. // 3: network fetch ended
  1059. // isStackNewRequest = false;
  1060. } else {
  1061. // 0: invalid before
  1062. // 1: scheduled but not yet fetch
  1063. isStackNewRequest = true;
  1064. }
  1065. } else if (cache) {
  1066. // resolved result
  1067. return cache;
  1068. } else {
  1069. // else no cached value found
  1070. /** @type {AsyncValue<DisplayNameResultObject>} */
  1071. aResult = new AsyncValue();
  1072. displayNameResStore.set(channelId, aResult);
  1073. isStackNewRequest = true;
  1074. }
  1075.  
  1076. if (isStackNewRequest) {
  1077. aResult.fetchingState = 1;
  1078. stackNewRequest(channelId);
  1079. }
  1080. const result = await aResult.getValue();
  1081. return result;
  1082. }
  1083.  
  1084.  
  1085. /**
  1086. *
  1087. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  1088. * @returns
  1089. * * Outdated?
  1090. */
  1091. const obtainChannelId = (href) => {
  1092. const s = `/${href}`;
  1093. if (s.length >= 33) {
  1094. const m = /\/channel\/(UC[-_a-zA-Z0-9+=.]{22})(\/|$)/.exec(s);
  1095. return !m ? '' : (m[1] || '');
  1096. }
  1097. return '';
  1098. };
  1099.  
  1100. const isUCBrowserId = (browseId) => {
  1101. return typeof browseId === 'string' && browseId.length === 24 && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId);
  1102. }
  1103.  
  1104.  
  1105. /**
  1106. *
  1107. * @param {Element} ytElm
  1108. */
  1109. const resetWhenDataChanged = (ths) => {
  1110. const cnt = insp(ths);
  1111. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1112. if (ytElm instanceof Element) {
  1113. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1114. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1115. if ((anchors || 0).length >= 1 && (insp(ytElm).data || 0).jkrgx !== 1) {
  1116. for (const anchor of anchors) {
  1117. anchor.removeAttribute('jkrgy');
  1118. }
  1119. }
  1120. }
  1121. }
  1122.  
  1123. /**
  1124. *
  1125. * @param {Element} ytElm
  1126. */
  1127. const resetWhenPropChanged = (ths) => {
  1128. const cnt = insp(ths);
  1129. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1130. if (ytElm instanceof Element) {
  1131. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1132. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1133. if ((anchors || 0).length >= 1 && ((insp(ytElm).commentEntity || 0).author || 0).jkrgx !== 1) {
  1134. for (const anchor of anchors) {
  1135. anchor.removeAttribute('jkrgy');
  1136. }
  1137. }
  1138. }
  1139. }
  1140.  
  1141. /**
  1142. *
  1143. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  1144. * @param {string} hrefAttribute Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ (old) 2024 Feb -> /@user-abc1234
  1145. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  1146. * @returns
  1147. */
  1148. const anchorIntegrityCheck = (anchor, hrefAttribute) => {
  1149.  
  1150. let currentHref = anchor.getAttribute('href');
  1151. if (currentHref === hrefAttribute) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  1152.  
  1153. return (currentHref + '/').indexOf(hrefAttribute + '/') >= 0;
  1154.  
  1155. };
  1156.  
  1157. /**
  1158. *
  1159. * @param {string} currentDisplayed
  1160. * @param {DisplayNameResultObject} fetchResult
  1161. * @returns
  1162. */
  1163. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  1164.  
  1165. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  1166.  
  1167. const currentDisplayTrimmed = currentDisplayed.trim(); // @IORIMATSUNAGA
  1168. const currentDisplayTrimmedLowerCase = currentDisplayTrimmed.toLowerCase(); // @iorimatsunaga
  1169. let match = false;
  1170. if (verified123) {
  1171. match = true;
  1172. } else if ((vanityChannelUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmedLowerCase}`)) {
  1173. match = true;
  1174. } else if ((ownerUrls || 0).length >= 1) {
  1175. for (const ownerUrl of ownerUrls) {
  1176. if ((ownerUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmed}`)) {
  1177. match = true;
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. if (match) {
  1183. return currentDisplayTrimmed;
  1184. }
  1185. return '';
  1186.  
  1187. };
  1188.  
  1189. /**
  1190. *
  1191. *
  1192.  
  1193. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  1194.  
  1195. - Is between 3-30 characters
  1196. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1197. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  1198. - Is not URL-like or phone number-like
  1199. - Is not already being used
  1200. - Follows YouTube's Community Guidelines
  1201.  
  1202. ### Handle automatically generated by YouTube
  1203. - `@user-XXXX`
  1204. - without dot (.)
  1205. *
  1206. * @param {string} text
  1207. * @returns
  1208. */
  1209. const isDisplayAsHandle = (text) => {
  1210.  
  1211. if (typeof text !== 'string') return false;
  1212. if (text.length < 4) return false;
  1213. if (text.indexOf('@') < 0) return false;
  1214. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  1215.  
  1216. };
  1217.  
  1218. /**
  1219. *
  1220. * @param {Object[]} contentTexts
  1221. * @param {number} idx
  1222. * @returns
  1223. */
  1224. const contentTextProcess = (contentTexts, idx) => {
  1225. const contentText = contentTexts[idx];
  1226. const text = (contentText || 0).text;
  1227. const browseId = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1228. const canonicalBaseUrl = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1229. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1230. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1231.  
  1232. if (!isDisplayAsHandle(text)) return null;
  1233. const channelId = browseId;
  1234.  
  1235. return getDisplayName(channelId).then(fetchResult => {
  1236. let resolveResult = null;
  1237. if (fetchResult) {
  1238. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1239.  
  1240. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1241. if (textTrimmed) {
  1242. resolveResult = (md) => {
  1243. let runs = ((md || 0).contentText || 0).runs;
  1244. if (!runs || !runs[idx]) return;
  1245. if (runs[idx].text !== text) return;
  1246. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1247. md.contentText = Object.assign({}, md.contentText);
  1248. };
  1249. }
  1250. }
  1251. return resolveResult; // function as a Promise
  1252. });
  1253. }
  1254.  
  1255. return null;
  1256. };
  1257.  
  1258. const editableTextProcess = (editableTexts, idx) => {
  1259. const editableText = editableTexts[idx];
  1260. const text = (editableText || 0).text;
  1261.  
  1262. const browseId = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1263. const canonicalBaseUrl = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1264. const url = (((editableText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1265. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1266.  
  1267. if (!isDisplayAsHandle(text)) return null;
  1268. const channelId = browseId;
  1269.  
  1270. return getDisplayName(channelId).then(fetchResult => {
  1271. let resolveResult = null;
  1272. if (fetchResult) {
  1273. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1274.  
  1275. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1276. if (textTrimmed) {
  1277. resolveResult = (md) => {
  1278. let commentReplyDialogRenderer = null;
  1279. try {
  1280. commentReplyDialogRenderer = md.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1281. } catch (e) { }
  1282. if (!commentReplyDialogRenderer) return;
  1283. const editableText = commentReplyDialogRenderer.editableText || 0;
  1284.  
  1285. let runs = (editableText || 0).runs;
  1286. if (!runs || !runs[idx]) return;
  1287. if (runs[idx].text !== text) return;
  1288. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1289. commentReplyDialogRenderer.editableText = Object.assign({}, commentReplyDialogRenderer.editableText);
  1290. };
  1291. }
  1292. }
  1293. return resolveResult; // function as a Promise
  1294. });
  1295. }
  1296.  
  1297. return null;
  1298. };
  1299. const contentTextProcessViewModel = async (content, idx) => {
  1300. const { commandRuns, content: text, styleRuns } = content;
  1301. if (typeof text !== 'string') return;
  1302. const names = [];
  1303.  
  1304. function replaceNamePN(o) {
  1305. return getDisplayName(o.channelId).then(fetchResult => {
  1306. let resolveResult = null;
  1307. if (fetchResult) {
  1308. const textTrimmed = verifyAndConvertHandle(o.handle, fetchResult);
  1309. if (textTrimmed) {
  1310. o.display = `@${fetchResult.title}`;
  1311. o.newText = o.oldText.replace(o.handle, o.display);
  1312. }
  1313. }
  1314. return resolveResult; // function as a Promise
  1315. });
  1316. }
  1317. const promises = [];
  1318. for (const commandRun of commandRuns) {
  1319. let browseEndpoint = null;
  1320. if (commandRun.length >= 1 && commandRun.startIndex >= 0 && (browseEndpoint = ((commandRun.onTap || 0).innertubeCommand || 0).browseEndpoint)) {
  1321. let substr = text.substring(commandRun.startIndex, commandRun.startIndex + commandRun.length);
  1322. const substrTrimmed = substr.trim();
  1323. if (isDisplayAsHandle(substrTrimmed) && `/${substrTrimmed}` === browseEndpoint.canonicalBaseUrl && isUCBrowserId(browseEndpoint.browseId)) {
  1324. const o = {
  1325. startIndex: commandRun.startIndex,
  1326. endIndex: commandRun.startIndex + commandRun.length,
  1327. handle: substrTrimmed,
  1328. oldText: substr,
  1329. newText: null,
  1330. channelId: browseEndpoint.browseId,
  1331. nStartIndex: null,
  1332. nEndIndex: null,
  1333. nText: null
  1334. }
  1335. names.push(o);
  1336. promises.push(replaceNamePN(o));
  1337. }
  1338. }
  1339. }
  1340. await Promise.all(promises);
  1341.  
  1342. let offset = 0;
  1343. for (const o of names) {
  1344. o.nStartIndex = o.startIndex + offset;
  1345. o.nText = o.newText === null ? o.oldText : o.newText;
  1346. o.nEndIndex = o.nStartIndex + offset + o.nText.length;
  1347. offset += o.nText.length - o.oldText.length;
  1348. }
  1349.  
  1350. let w1 = 0, w2 = 0;
  1351. let s = [];
  1352. let j = 0;
  1353. for (let i = 0; i < text.length;) {
  1354. while (w1 < commandRuns.length && commandRuns[w1].startIndex < i) w1++;
  1355. while (w2 < styleRuns.length && styleRuns[w2].startIndex < i) w2++;
  1356.  
  1357. if (j < names.length && i == names[j].startIndex) {
  1358.  
  1359. if (w1 < commandRuns.length && commandRuns[w1].startIndex === names[j].startIndex) {
  1360. const run = commandRuns[w1];
  1361. const o = names[j];
  1362. if (run.length === o.endIndex - o.startIndex) {
  1363. run.startIndex = o.nStartIndex;
  1364. run.length = o.nText.length;
  1365. }
  1366. w1++;
  1367. }
  1368.  
  1369. if (w2 < styleRuns.length && styleRuns[w2].startIndex === names[j].startIndex) {
  1370. const run = styleRuns[w2];
  1371. const o = names[j];
  1372. if (run.length === o.endIndex - o.startIndex) {
  1373. run.startIndex = o.nStartIndex;
  1374. run.length = o.nText.length;
  1375. }
  1376. w2++;
  1377. }
  1378.  
  1379.  
  1380. // s.push(text.substring(names[j].startIndex, names[j].endIndex));
  1381. s.push(names[j].nText);
  1382. i = names[j].endIndex;
  1383. j++;
  1384. } else {
  1385. if (j >= names.length) {
  1386. s.push(text.substring(i));
  1387. i = text.length;
  1388. } else {
  1389. if (j < names.length && names[j].startIndex > i + 1) {
  1390. s.push(text.substring(i, names[j].startIndex));
  1391. i = names[j].startIndex;
  1392. } else {
  1393. s.push(text.charAt(i));
  1394. i++;
  1395. }
  1396. }
  1397. }
  1398. }
  1399.  
  1400. content.content = s.join('');
  1401. s.length = 0;
  1402.  
  1403.  
  1404. };
  1405.  
  1406. /**
  1407. *
  1408. * @param {ParentNode & Element} parentNode
  1409. * @param {Function} callback
  1410. */
  1411. function findTextNodes(parentNode, callback) {
  1412. /**
  1413. *
  1414. * @param {Node} node
  1415. * @returns
  1416. */
  1417. function traverse(node) {
  1418. if (node.nodeType === Node.TEXT_NODE) {
  1419. let r = callback(node);
  1420. if (r === true) return true;
  1421. } else if (node.nodeType === Node.ELEMENT_NODE) {
  1422. for (let childNode = nodeFirstChild(node); childNode; childNode = nodeNextSibling(childNode)) {
  1423. const r = traverse(childNode);
  1424. if (r === true) return true;
  1425. }
  1426. }
  1427. }
  1428.  
  1429. traverse(parentNode);
  1430. }
  1431.  
  1432. function updatePinnedCommentBadge(md, title, langTitle) {
  1433. const titleForDisplay = langTitle || title;
  1434. if (typeof titleForDisplay !== 'string') return;
  1435. if (title === titleForDisplay) return;
  1436. const runs = ((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0); // can be 0
  1437. if (runs.length === 2) {
  1438. let idx = 0;
  1439. let jdx = -1;
  1440. for (const textRun of runs) {
  1441. if (textRun.text === title) {
  1442. jdx = idx;
  1443. break;
  1444. }
  1445. idx++;
  1446. }
  1447. if (jdx >= 0) {
  1448. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  1449. runs[jdx] = Object.assign({}, runs[jdx], { text: titleForDisplay });
  1450. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  1451. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  1452. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  1453. }
  1454. }
  1455. }
  1456.  
  1457. /**
  1458. *
  1459. * @param {ParentNode} parentNode
  1460. * @param {Object[]} contentTexts
  1461. * @param {number} aidx
  1462. * @returns
  1463. */
  1464. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  1465.  
  1466.  
  1467. let commentText = elementQS(parentNode, '.comment-text');
  1468. if (!commentText) return;
  1469. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  1470. let currentText = commentText.textContent;
  1471. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1472. if (!textMatch) return;
  1473.  
  1474. const contentText = contentTexts[aidx];
  1475.  
  1476. /** @type {string} */
  1477. const handleText = contentText.text.trim();
  1478. /** @type {string | null | undefined} */
  1479. let channelId;
  1480.  
  1481. let cache = handleToChannelId.get(handleText);
  1482.  
  1483. if (typeof cache === 'string') {
  1484. channelId = cache;
  1485. } else if (cache instanceof AsyncValue) {
  1486. channelId = await cache.getValue();
  1487. } else {
  1488. /** @type {AsyncValue<string>} */
  1489. const asyncValue = new AsyncValue();
  1490. handleToChannelId.set(handleText, asyncValue);
  1491. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1492. }
  1493.  
  1494. if (!channelId) return; // just in case
  1495.  
  1496. if (commentText.isConnected !== true) return; // already removed
  1497. if (commentText.textContent !== currentText) return; // already changed
  1498.  
  1499. const fetchResult = await getDisplayName(channelId);
  1500.  
  1501. if (fetchResult === null) return;
  1502.  
  1503. const { title, langTitle, externalId } = fetchResult;
  1504. const titleForDisplay = langTitle || title;
  1505. if (externalId !== channelId) return; // channel id must be the same
  1506.  
  1507. if (commentText.isConnected !== true) return; // already removed
  1508. if (commentText.textContent !== currentText) return; // already changed
  1509.  
  1510. let search = contentText.text;
  1511. if (typeof search === 'string') {
  1512.  
  1513. const searchTrimmed = search.trim();
  1514. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1515. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  1516.  
  1517. findTextNodes(commentText, (textnode) => {
  1518. if (textnode.nodeValue.indexOf(search) >= 0) {
  1519. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1520. return true;
  1521. }
  1522. });
  1523. }
  1524.  
  1525. }
  1526.  
  1527. }
  1528.  
  1529. /**
  1530. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1531. * @type { (anchor: HTMLElement, anchorHref: string?, mt: string?) => Promise<void> }
  1532. */
  1533.  
  1534. const getDisplayTextDOMForCommentRenderer = (root) => { // mobile
  1535. let displayTextDOM = elementQS(root, '.comment-header .comment-title');
  1536. if (displayTextDOM) {
  1537. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1538. }
  1539. return displayTextDOM;
  1540. }
  1541.  
  1542. const ytPathnameExtract = (href) => {
  1543.  
  1544. if (!href || typeof href !== 'string') return '';
  1545. let i = 0;
  1546. if (href.startsWith('/')) {
  1547.  
  1548. } else if ((i = href.indexOf('youtube.com/')) >= 0) {
  1549. href = href.substring(i + 11);
  1550. } else {
  1551. return '';
  1552. }
  1553. return href;
  1554.  
  1555. }
  1556.  
  1557. const getHrefType = (href) => {
  1558. if (href.length === 33 && href.startsWith('/channel/') && /^\/channel\/UC[-_a-zA-Z0-9+=.]{22}$/.test(href)) {
  1559. return 1;
  1560. } else if (href.length >= 5 && href.length <= 32 && href.startsWith('/@') && /^\/@[-_a-zA-Z0-9.]{3,30}$/.test(href)) {
  1561. return 2;
  1562. }
  1563. return 0;
  1564. }
  1565.  
  1566. const getYTextType = (text) => {
  1567. // if (typeof text === 'string') return 1;
  1568. if (typeof text === 'object' && text) {
  1569. if (typeof text.simpleText === 'string') return 2;
  1570. const runs = text.runs;
  1571. if (runs && runs.length === 1) {
  1572. let r = runs[0];
  1573. return typeof r === 'string' ? 3 : typeof (r || 0).text === 'string' ? 4 : null;
  1574. }
  1575. }
  1576. return null;
  1577. }
  1578.  
  1579. const getYTextContent = (text) => {
  1580. // if (typeof text === 'string') return text;
  1581. if (typeof text === 'object' && text) {
  1582. const simpleText = text.simpleText;
  1583. if (typeof simpleText === 'string') return simpleText;
  1584. const runs = text.runs;
  1585. if (runs && runs.length === 1) {
  1586. let r = runs[0];
  1587. return typeof r === 'string' ? r : typeof (r || 0).text === 'string' ? r.text : null;
  1588. }
  1589. }
  1590. return null;
  1591. }
  1592.  
  1593. const setYTextContent = (text, fn) => {
  1594. // if (typeof text === 'string') {
  1595. // res=fn(text);
  1596. // }
  1597. if (typeof text === 'object' && text) {
  1598. const simpleText = text.simpleText;
  1599. if (typeof simpleText === 'string') {
  1600. return Object.assign({}, text, { simpleText: fn(simpleText) });
  1601. }
  1602. const runs = text.runs;
  1603. if (runs && runs.length === 1) {
  1604. let r = runs[0];
  1605. 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;
  1606. }
  1607. }
  1608. return null;
  1609. }
  1610.  
  1611. const domCheckAsync = isMobile ? async (anchor, hrefAttribute, mt) => {
  1612.  
  1613. let sHandleName = null;
  1614. let sNodeValue = null;
  1615. try {
  1616. if (!hrefAttribute || !mt) return;
  1617. let parentNode = nodeParent(anchor);
  1618. while (parentNode instanceof Node) {
  1619. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1620. parentNode = nodeParent(parentNode);
  1621. }
  1622. if (parentNode instanceof Node) { } else return;
  1623.  
  1624. const commentRendererAuthorTextDOM = getDisplayTextDOMForCommentRenderer(parentNode);
  1625. const anchorAiraLabel = anchor.getAttribute('aria-label');
  1626. const anchorHrefValue = ytPathnameExtract(anchor.getAttribute('href')); // guess (Feb 2024)
  1627.  
  1628. const cnt = insp(parentNode);
  1629. const parentNodeData = cnt._commentData || cnt.data || 0;
  1630. const authorTextData = (parentNodeData.authorText || 0);
  1631.  
  1632. let tHandleName = null;
  1633.  
  1634. if (commentRendererAuthorTextDOM && authorTextData) {
  1635. const hType = getHrefType(anchorHrefValue);
  1636. let ytext = null;
  1637. if (hType === 2) {
  1638. tHandleName = anchorHrefValue.substring(1); // guess
  1639. } else if (hType === 1) {
  1640. ytext = getYTextContent(authorTextData)
  1641. tHandleName = ytext; // authorTextData.runs[0].text
  1642. }
  1643. if (typeof tHandleName === 'string' && commentRendererAuthorTextDOM.textContent.trim() === tHandleName && isDisplayAsHandle(tHandleName)) {
  1644. ytext = ytext || getYTextContent(authorTextData)
  1645. if (ytext === tHandleName) {
  1646. sHandleName = tHandleName;
  1647. sNodeValue = tHandleName;
  1648. }
  1649. }
  1650. }
  1651.  
  1652. if (typeof sHandleName === 'string' && typeof sNodeValue === 'string') {
  1653.  
  1654. if (!channelIdToHandle.has(mt)) {
  1655. channelIdToHandle.set(mt, {
  1656. handleText: sHandleName,
  1657. justPossible: true
  1658. });
  1659. }
  1660.  
  1661. const fetchResult = await getDisplayName(mt);
  1662.  
  1663. if (fetchResult === null) return;
  1664.  
  1665. const { title, langTitle, externalId } = fetchResult;
  1666. const titleForDisplay = langTitle || title;
  1667. if (externalId !== mt) return; // channel id must be the same
  1668.  
  1669. // anchor href might be changed by external
  1670. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1671.  
  1672. if (commentRendererAuthorTextDOM.isConnected !== true) return; // already removed
  1673.  
  1674. let found = false;
  1675.  
  1676. findTextNodes(commentRendererAuthorTextDOM, (textnode) => {
  1677. if (textnode.nodeValue === sNodeValue) {
  1678. textnode.nodeValue = titleForDisplay;
  1679. found = true;
  1680. return true;
  1681. }
  1682. });
  1683.  
  1684. if (!found) return;
  1685. if (anchorAiraLabel && anchorAiraLabel.trim() === sHandleName) anchor.setAttribute('aria-label', anchorAiraLabel.replace(sHandleName, titleForDisplay));
  1686. const authorTextDataNew = setYTextContent(authorTextData, (t) => t.replace(t.trim(), titleForDisplay));
  1687. if (authorTextDataNew && parentNodeData.authorText === authorTextData) {
  1688. parentNodeData.authorText = authorTextDataNew;
  1689. }
  1690.  
  1691. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  1692. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  1693. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  1694. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  1695. const tc = spanText ? spanText.textContent : '';
  1696. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  1697. let idx;
  1698. if (tc && tc === spanText.textContent && (idx = tc.indexOf(title)) >= 0) {
  1699. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  1700. }
  1701. }
  1702.  
  1703. const contentTexts = (parentNodeData.contentText || 0).runs;
  1704. if (contentTexts && contentTexts.length >= 2) {
  1705. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1706. const contentText = contentTexts[aidx] || 0;
  1707. if (contentText.italics !== true && isDisplayAsHandle(contentText.text)) {
  1708. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1709. }
  1710. }
  1711. }
  1712.  
  1713. }
  1714.  
  1715. } catch (e) {
  1716. console.warn(e);
  1717. }
  1718.  
  1719. } : async (anchor, hrefAttribute, mt) => {
  1720.  
  1721. try {
  1722. if (!hrefAttribute || !mt) return;
  1723. let parentNode = nodeParent(anchor);
  1724. let isCommentViewModel = 0;
  1725. while (parentNode instanceof Node) {
  1726. const cnt = insp(parentNode);
  1727. if (typeof cnt.is === 'string') {
  1728. if (cnt.commentEntity && !cnt._propertiesChanged) { isCommentViewModel = 2; break; } // 2024.04.30: ytd-comment-view-model (v3)
  1729. if (cnt.commentEntity && typeof cnt._propertiesChanged === 'function') { isCommentViewModel = 1; break; } // Feb 2024: ytd-comment-view-model (v1 & v2)
  1730. else if (typeof cnt.dataChanged === 'function') break;
  1731. }
  1732. parentNode = nodeParent(parentNode);
  1733. }
  1734. if (parentNode instanceof Node) { } else return;
  1735. const parentNodeController = insp(parentNode);
  1736.  
  1737. if (isCommentViewModel > 0) {
  1738.  
  1739. const commentEntity = parentNodeController.commentEntity || 0;
  1740. const commentEntityAuthor = commentEntity.author || 0;
  1741. const currentDisplayed = commentEntityAuthor.displayName || 0;
  1742. if (typeof currentDisplayed !== 'string') return;
  1743. if (!isDisplayAsHandle(currentDisplayed)) return;
  1744. if (!channelIdToHandle.has(mt)) {
  1745. channelIdToHandle.set(mt, {
  1746. handleText: currentDisplayed.trim(),
  1747. justPossible: true
  1748. });
  1749. }
  1750.  
  1751. // not working for CommentViewModel v3
  1752. if (typeof parentNodeController._propertiesChanged === 'function' && !parentNodeController._propertiesChanged159) {
  1753. const cntp = parentNodeController.constructor.prototype;
  1754. const c = cntp._propertiesChanged === parentNodeController._propertiesChanged ? cntp : parentNodeController;
  1755. c._propertiesChanged159 = c._propertiesChanged;
  1756. c._propertiesChanged = function () {
  1757. resetWhenPropChanged(this);
  1758. return this._propertiesChanged159.apply(this, arguments);
  1759. };
  1760. }
  1761.  
  1762. const fetchResult = await getDisplayName(mt);
  1763.  
  1764. if (fetchResult === null) return;
  1765.  
  1766. const { title, langTitle, externalId } = fetchResult;
  1767. const titleForDisplay = langTitle || title;
  1768. if (externalId !== mt) return; // channel id must be the same
  1769.  
  1770. // anchor href might be changed by external
  1771. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1772.  
  1773. if (commentEntityAuthor.displayName === currentDisplayed && commentEntityAuthor.channelId === mt) {
  1774. commentEntityAuthor.displayName = titleForDisplay;
  1775.  
  1776. if (commentEntity.properties) {
  1777. if (commentEntity.properties.authorButtonA11y === currentDisplayed) {
  1778. commentEntity.properties.authorButtonA11y = titleForDisplay;
  1779. }
  1780.  
  1781. // the inside hyperlinks will be only converted if its parent author name is handle
  1782. const content = commentEntity.properties.content;
  1783. if (content && (content.commandRuns || 0).length >= 1) {
  1784. try {
  1785. await contentTextProcessViewModel(content);
  1786.  
  1787. // $0.polymerController.commentEntity = Object.assign({}, $0.polymerController.commentEntity , { properties: Object.assign({}, $0.polymerController.commentEntity.properties, { content: Object.assign({},$0.polymerController.commentEntity.properties.content) } )})
  1788.  
  1789. // parentNodeController.commentEntity.properties = Object.assign({}, parentNodeController.commentEntity.properties, {
  1790. // content: Object.assign({}, parentNodeController.commentEntity.properties.content)
  1791. // });
  1792.  
  1793. commentEntity.properties.content = Object.assign({}, content);
  1794. } catch (e) {
  1795. console.log(e);
  1796. }
  1797.  
  1798. }
  1799.  
  1800. }
  1801.  
  1802. if (commentEntityAuthor && parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1803. commentEntityAuthor.jkrgx = 1;
  1804. addCSSRulesIfRequired();
  1805. }
  1806.  
  1807. parentNodeController.commentEntity = Object.assign({}, parentNodeController.commentEntity);
  1808.  
  1809. }
  1810.  
  1811. } else {
  1812.  
  1813. const authorText = (parentNodeController.data || 0).authorText;
  1814. const currentDisplayed = getYTextContent(authorText || 0); // authorText.simpleText
  1815. if (typeof currentDisplayed !== 'string') return;
  1816. if (!isDisplayAsHandle(currentDisplayed)) return;
  1817.  
  1818. if (!channelIdToHandle.has(mt)) {
  1819. channelIdToHandle.set(mt, {
  1820. handleText: currentDisplayed.trim(),
  1821. justPossible: true
  1822. });
  1823. }
  1824.  
  1825. if (typeof parentNodeController.dataChanged === 'function' && !parentNodeController.dataChanged159) {
  1826. const cntp = parentNodeController.constructor.prototype;
  1827. const c = cntp.dataChanged === parentNodeController.dataChanged ? cntp : parentNodeController;
  1828. c.dataChanged159 = c.dataChanged;
  1829. c.dataChanged = function () {
  1830. resetWhenDataChanged(this);
  1831. return this.dataChanged159.apply(this, arguments);
  1832. };
  1833. }
  1834.  
  1835. const fetchResult = await getDisplayName(mt);
  1836.  
  1837. if (fetchResult === null) return;
  1838.  
  1839. const { title, langTitle, externalId } = fetchResult;
  1840. const titleForDisplay = langTitle || title;
  1841. if (externalId !== mt) return; // channel id must be the same
  1842.  
  1843. // anchor href might be changed by external
  1844. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1845.  
  1846. const parentNodeData = parentNodeController.data;
  1847. const funcPromises = [];
  1848.  
  1849. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1850.  
  1851. if (getYTextContent(authorText) !== currentDisplayed) return;
  1852. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1853. const cSimpleText = (getYTextContent(parentNodeData.authorText || 0) || '');
  1854. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  1855.  
  1856. // the inside hyperlinks will be only converted if its parent author name is handle
  1857. const contentTexts = (parentNodeData.contentText || 0).runs;
  1858. if (contentTexts && contentTexts.length >= 1) {
  1859. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1860. const r = contentTextProcess(contentTexts, aidx);
  1861. if (r instanceof Promise) funcPromises.push(r);
  1862. }
  1863. }
  1864.  
  1865. const md = Object.assign({}, parentNodeData);
  1866. const authorCommentBadgeAuthorText = (((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0);
  1867.  
  1868. const authorCommentBadgeAuthorTextNew = authorCommentBadgeAuthorText ? setYTextContent(authorCommentBadgeAuthorText, (currentText) => {
  1869. if ((currentText || '').trim() === cSimpleText.trim()) {
  1870. return (currentText || '').replace((currentText || '').trim(), titleForDisplay);
  1871. } else {
  1872. return currentText;
  1873. }
  1874. }) : null;
  1875.  
  1876. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1877. const authorTextNew = setYTextContent(md.authorText, (t) => t.replace(currentDisplayTrimmed, titleForDisplay))
  1878. md.authorText = authorTextNew;
  1879.  
  1880. if (authorCommentBadgeAuthorTextNew) {
  1881. const authorCommentBadgeRendererNew = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer, { authorText: authorCommentBadgeAuthorTextNew });
  1882. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge, { authorCommentBadgeRenderer: authorCommentBadgeRendererNew });
  1883. }
  1884.  
  1885. let setReplyEditableText = false;
  1886. if (((((((((parentNodeData.actionButtons || 0).commentActionButtonsRenderer || 0).replyButton || 0).buttonRenderer || 0).navigationEndpoint || 0).createCommentReplyDialogEndpoint || 0).dialog || 0).commentReplyDialogRenderer || 0).editableText) {
  1887. setReplyEditableText = true;
  1888. }
  1889. if (setReplyEditableText) {
  1890. const commentReplyDialogRenderer = parentNodeData.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1891. const editableText = commentReplyDialogRenderer.editableText;
  1892. const editableTexts = editableText.runs;
  1893. if (editableTexts && editableTexts.length >= 1) {
  1894. for (let aidx = 0; aidx < editableTexts.length; aidx++) {
  1895. const r = editableTextProcess(editableTexts, aidx);
  1896. if (r instanceof Promise) funcPromises.push(r);
  1897. }
  1898. }
  1899. }
  1900.  
  1901. if (UPDATE_PIN_NAME) {
  1902. updatePinnedCommentBadge(md, title, langTitle);
  1903. }
  1904.  
  1905. if (funcPromises.length >= 1) {
  1906. let funcs = await Promise.all(funcPromises);
  1907.  
  1908. for (const func of funcs) {
  1909. if (typeof func === 'function') {
  1910. func(md);
  1911. }
  1912. }
  1913. }
  1914.  
  1915. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1916. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  1917. addCSSRulesIfRequired();
  1918. }
  1919.  
  1920.  
  1921. }
  1922.  
  1923. }
  1924. }
  1925. } catch (e) {
  1926. console.warn(e);
  1927. }
  1928.  
  1929. }
  1930.  
  1931. /**
  1932. *
  1933. * @param {string} url
  1934. * @returns
  1935. */
  1936. const channelUrlUnify = (url) => {
  1937.  
  1938. if (typeof url !== 'string') return url; // type unchanged
  1939. let c0 = url.charAt(0);
  1940. if (c0 === '/') return url;
  1941. let i = url.indexOf('.youtube.com/');
  1942. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1943. else if (url.charAt(0) !== '/') url = '/' + url;
  1944. return url
  1945.  
  1946. }
  1947.  
  1948. const parentYtElement = (node, nodeName, maxN) => {
  1949. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1950. if (pDom.nodeName === nodeName) {
  1951. return pDom;
  1952. }
  1953. }
  1954. return null;
  1955. }
  1956.  
  1957. const checkShortsChannelName = (rchannelNameDOM) => {
  1958. let browseId = '';
  1959. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1960.  
  1961. if (pDom instanceof HTMLElement) {
  1962. const pDomController = insp(pDom);
  1963. const channelTitleText = (pDomController.data || 0).channelTitleText || 0;
  1964. const runs = ((channelTitleText || 0).runs || 0);
  1965. if (getYTextType(channelTitleText) === 4) {
  1966. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1967. browseId = (browserEndpoint.browseId || '');
  1968. const currentDisplayText = runs[0].text || ''
  1969.  
  1970. if (isUCBrowserId(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1971.  
  1972. if (!channelIdToHandle.has(browseId)) {
  1973. channelIdToHandle.set(browseId, {
  1974. handleText: currentDisplayText.trim(),
  1975. justPossible: true
  1976. });
  1977. }
  1978.  
  1979. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1980. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1981. // anchorNode &&
  1982. getDisplayName(browseId).then(fetchResult => {
  1983.  
  1984. if (fetchResult === null) return;
  1985.  
  1986. const { title, langTitle, externalId } = fetchResult;
  1987. const titleForDisplay = langTitle || title;
  1988. if (externalId !== browseId) return; // channel id must be the same
  1989.  
  1990. const hDom = pDom;
  1991. const hDomHostElement = hDom.hostElement || hDom;
  1992. const hDomController = insp(hDom);
  1993. const hData = (hDomController || 0).data || 0;
  1994. const hChannelTitleText = (hData || 0).channelTitleText || 0;
  1995. const runs = ((hChannelTitleText).runs || 0);
  1996. if (getYTextType(hChannelTitleText) === 4 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  1997.  
  1998. const channelTitleTextNew = { runs: [Object.assign({}, runs[0], { text: titleForDisplay })] }
  1999.  
  2000. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: channelTitleTextNew, rSk0e: 1 });
  2001. addCSSRulesIfRequired();
  2002.  
  2003. byPassCheckStore.delete(rchannelNameDOM);
  2004. }
  2005.  
  2006. })
  2007. }
  2008.  
  2009. }
  2010. }
  2011. return browseId
  2012. }
  2013.  
  2014. let firstDOMCheck = false;
  2015. const updateDisplayNameFn = (channelId, newName) => {
  2016. const cached = displayNameResStore.get(channelId);
  2017. if (typeof (cached || 0).title === 'string') {
  2018. cached.title = newName;
  2019. } else if (!cached) {
  2020. displayNameResStore.set(channelId, {
  2021. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  2022. externalId: `${channelId}`,
  2023. ownerUrls: [],
  2024. title: newName,
  2025. vanityChannelUrl: null,
  2026. verified123: true
  2027. });
  2028. } else {
  2029. console.warn('unexpected display name cache', cached);
  2030. }
  2031. };
  2032. const firstDOMChecker = isMobile ? () => {
  2033.  
  2034. let playerMicroformatRenderer = null;
  2035. try {
  2036. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  2037. } catch (e) { }
  2038. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  2039. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  2040. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  2041. }
  2042.  
  2043. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  2044. const channelNameCData = !channelNameDOM ? null : insp(channelNameDOM).data;
  2045.  
  2046. if (channelNameCData) {
  2047. let mainChannelUrl = null;
  2048. let mainFormattedNameUrl = null;
  2049. let mainChannelText = null;
  2050. let mainFormattedNameText = null;
  2051. let mainChannelBrowseId = null;
  2052.  
  2053. try {
  2054. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl) // channelUrlUnify("http://www.youtube.com/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2055. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl) // channelUrlUnify("/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2056. mainChannelText = channelNameCData.channelName
  2057. mainFormattedNameText = channelNameCData.title.runs[0].text
  2058. mainChannelBrowseId = channelNameCData.navigationEndpoint.browseEndpoint.browseId;
  2059. } catch (e) { }
  2060.  
  2061. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2062.  
  2063. const channelId = mainChannelBrowseId;
  2064. if (channelId) {
  2065. if (mainChannelText.startsWith('@')) return;
  2066. if (mainChannelText.trim() !== mainChannelText) return;
  2067. updateDisplayNameFn(channelId, mainChannelText);
  2068. }
  2069.  
  2070.  
  2071. }
  2072. }
  2073.  
  2074. } : () => {
  2075.  
  2076. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  2077. const channelNameCnt = insp(channelNameDOM);
  2078. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  2079. if (channelNameCData) {
  2080. let mainChannelUrl = null;
  2081. let mainFormattedNameUrl = null;
  2082. let mainChannelText = null;
  2083. let mainFormattedNameText = null;
  2084. let mainChannelBrowseId = null;
  2085. try {
  2086. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2087. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2088. mainChannelText = channelNameCData.channelName.runs[0].text
  2089. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  2090. mainChannelBrowseId = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.browseId;
  2091. } catch (e) { }
  2092.  
  2093. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2094.  
  2095. const m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.exec(mainChannelUrl);
  2096.  
  2097. if (m && m[1] && mainChannelText !== m[1]) {
  2098.  
  2099. const channelHandle = m[1];
  2100. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  2101. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  2102. }
  2103.  
  2104. } else {
  2105.  
  2106. const channelId = mainChannelBrowseId;
  2107. if (channelId) {
  2108. if (mainChannelText.startsWith('@')) return;
  2109. if (mainChannelText.trim() !== mainChannelText) return;
  2110. updateDisplayNameFn(channelId, mainChannelText);
  2111. }
  2112.  
  2113. }
  2114. }
  2115. }
  2116.  
  2117. };
  2118.  
  2119. // let newAnchorAdded = false;
  2120. /*
  2121.  
  2122. const intersectionobserver = new IntersectionObserver((entries) => {
  2123. let anchorAppear = false;
  2124. for (const entry of entries) {
  2125. if (entry.isIntersecting === true) {
  2126. anchorAppear = true;
  2127. break;
  2128. }
  2129. }
  2130. if (anchorAppear && newAnchorAdded) {
  2131. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  2132. mutex.nextIndex = 0; // higher pirority for new elements being shown
  2133. }
  2134. }, {
  2135. rootMargin:"0px 0px 0px 0px",
  2136. threshold:1
  2137. })
  2138. */
  2139.  
  2140.  
  2141. /* globals WeakRef:false */
  2142.  
  2143. /** @type {(o: Object | null) => WeakRef | null} */
  2144. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  2145.  
  2146. /** @type {(wr: Object | null) => Object | null} */
  2147. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  2148.  
  2149. let doShortsChecking = false;
  2150. let doDescriptionChecking = true;
  2151.  
  2152. let lastNewAnchorLastWR = null;
  2153.  
  2154. const pipelineForDOMMutations = createPipeline();
  2155.  
  2156. const byPassCheckStore = new WeakSet();
  2157.  
  2158. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  2159. for (const mutation of mutations) {
  2160. const target = mutation.target;
  2161. if (!target) continue;
  2162. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  2163. if (!rchannelNameElm) continue;
  2164. const rchannelNameCnt = insp(rchannelNameElm);
  2165. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  2166. const channelId = rchannelNameElm.getAttribute('jkrgy');
  2167. if (channelId) {
  2168. if (byPassCheckStore.has(rchannelNameElm)) continue;
  2169. const handleObj = channelIdToHandle.get(channelId);
  2170. if (handleObj && handleObj.handleText && !handleObj.justPossible) {
  2171. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  2172. if (textDom) {
  2173. let t = textDom.textContent.trim()
  2174. if (t === handleObj.handleText || t === '') {
  2175. rchannelNameElm.removeAttribute('jkrgy');
  2176. // Promise.resolve().then(domChecker);
  2177. }
  2178. }
  2179. }
  2180. }
  2181. }
  2182. });
  2183.  
  2184. let domCheckScheduledForShorts = false;
  2185. const domCheckSelectorForShorts = [
  2186. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  2187. ].join(', ');
  2188.  
  2189.  
  2190. const domCheckerForShorts = async () => {
  2191.  
  2192. if (domCheckScheduledForShorts) return;
  2193. if (document.querySelector(domCheckSelectorForShorts) === null) {
  2194. return;
  2195. }
  2196. domCheckScheduledForShorts = true;
  2197.  
  2198. await pipelineForDOMMutations(async () => {
  2199.  
  2200. domCheckScheduledForShorts = false;
  2201. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  2202.  
  2203. try {
  2204.  
  2205. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  2206. if (nodes.length === 0) {
  2207. return;
  2208. }
  2209.  
  2210. for (const node of nodes) {
  2211.  
  2212. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  2213. if (rchannelNameElm) {
  2214. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  2215. childList: true,
  2216. subtree: true
  2217. });
  2218. byPassCheckStore.add(rchannelNameElm);
  2219. const channelId = checkShortsChannelName(rchannelNameElm);
  2220. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  2221. }
  2222.  
  2223. }
  2224.  
  2225. } catch (e) {
  2226. console.log('error occur', e);
  2227. }
  2228.  
  2229. });
  2230. domCheckScheduledForShorts = false;
  2231.  
  2232. };
  2233.  
  2234. /** @param {Element} s */
  2235. const domCheckerForDescriptionAnchor = (s) => {
  2236.  
  2237. findTextNodes(s, (textNode) => {
  2238. const p = textNode.nodeValue;
  2239. const index = p.indexOf('@');
  2240. if (index < 0) return;
  2241. const q = p.substring(index);
  2242. const b = isDisplayAsHandle(q);
  2243. if (b) {
  2244. const href = s.getAttribute('href')
  2245.  
  2246. const channelId = obtainChannelId(href);
  2247. if (channelId) {
  2248. const h = q.trim();
  2249.  
  2250. if (!firstDOMCheck) {
  2251. firstDOMCheck = true;
  2252. USE_CHANNEL_META && firstDOMChecker();
  2253. }
  2254.  
  2255. if (!channelIdToHandle.has(channelId)) {
  2256. channelIdToHandle.set(channelId, {
  2257. handleText: h,
  2258. justPossible: true
  2259. });
  2260. }
  2261.  
  2262. s.setAttribute('jkrgy', channelId);
  2263. getDisplayName(channelId).then(fetchResult => {
  2264.  
  2265. if (fetchResult === null) return;
  2266.  
  2267. const { title, langTitle, externalId } = fetchResult;
  2268. const titleForDisplay = langTitle || title;
  2269. if (externalId !== channelId) return; // channel id must be the same
  2270.  
  2271. const anchorElement = s;
  2272. const anchorTextNode = textNode;
  2273.  
  2274. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  2275.  
  2276. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  2277.  
  2278. }
  2279.  
  2280. });
  2281. }
  2282. }
  2283. return true;
  2284. });
  2285.  
  2286. }
  2287.  
  2288. // domCheckerForDescription: To be reviewed
  2289. // Example: https://www.youtube.com/watch?v=1NL-sIP9p_U
  2290. const domCheckerForDescription = isMobile ? () => {
  2291. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  2292. 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])')) {
  2293. s.setAttribute('dxcpj', '');
  2294. domCheckerForDescriptionAnchor(s);
  2295. }
  2296. } : () => {
  2297. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  2298. 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])')) {
  2299. s.setAttribute('dxcpj', '');
  2300. domCheckerForDescriptionAnchor(s);
  2301. }
  2302. };
  2303.  
  2304. const domCheckScheduledBools = [];
  2305. const domCheckScheduledSelectors = isMobile ? [
  2306. 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2307. 'a.comment-icon-container[href*="/@"]:not([jkrgy])', // Feb 2024
  2308. 'a.comment-icon-container[href*="channel/"]:not([jkrgy])' // Mar 2024
  2309. ] : [
  2310. 'a[id][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2311. 'a.yt-simple-endpoint.style-scope[id][href^="/@"]:not([jkrgy])' // Feb 2024
  2312. ];
  2313.  
  2314. const newAuthorAnchorsProceed = async (newAnchors) => {
  2315.  
  2316. const cNewAnchorFirst = newAnchors[0]; // non-null
  2317. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  2318. /** @type {HTMLElement | null} */
  2319. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  2320. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  2321.  
  2322. if (!firstDOMCheck) {
  2323. firstDOMCheck = true;
  2324. USE_CHANNEL_META && firstDOMChecker();
  2325. }
  2326.  
  2327. await Promise.resolve();
  2328.  
  2329. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  2330. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  2331. mutex.nextIndex = 0;
  2332. }
  2333. await Promise.resolve();
  2334. }
  2335.  
  2336. // newAnchorAdded = true;
  2337. for (const anchor of newAnchors) {
  2338. const hrefAttribute = anchor.getAttribute('href');
  2339. const hrefV = ytPathnameExtract(hrefAttribute);
  2340. let channelId = '';
  2341. const ytElm = isMobile ? closestYtmData(anchor) : closestYtParent(anchor);
  2342. if (ytElm) {
  2343. const cnt = insp(ytElm);
  2344. const { browseId, canonicalBaseUrl } = getAuthorBrowseEndpoint(cnt) || 0;
  2345.  
  2346. if (browseId && canonicalBaseUrl === hrefV && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId)) {
  2347.  
  2348. const hrefType = getHrefType(hrefV);
  2349. if (hrefType === 1) {
  2350. if (hrefV === `/channel/${browseId}`) {
  2351. let authorText = null;
  2352. if (isMobile) { // mobile only
  2353. authorText = (cnt._commentData || cnt.data || ytElm._commentData || ytElm.data || 0).authorText || 0;
  2354. } else if (!isMobile) {
  2355. authorText = (cnt.data || 0).authorText || 0;
  2356. }
  2357. if (authorText) {
  2358. const text = getYTextContent(authorText);
  2359. if (typeof text === 'string' && text.startsWith('@') && /^@[-_a-zA-Z0-9.]{3,30}$/.test(text)) {
  2360. channelIdToHandle.set(browseId, {
  2361. handleText: `${text}`,
  2362. justPossible: true
  2363. });
  2364. }
  2365. }
  2366. channelId = browseId;
  2367. }
  2368. } else if (hrefType === 2) {
  2369. const handle = hrefV.substring(2);
  2370. channelIdToHandle.set(browseId, {
  2371. handleText: `@${handle}`
  2372. });
  2373. channelId = browseId;
  2374. }
  2375.  
  2376. }
  2377.  
  2378. if (!channelId && hrefV) { // fallback
  2379.  
  2380. // author-text or name
  2381. // normal url: /channel/xxxxxxx
  2382. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  2383.  
  2384. const temp = obtainChannelId(hrefV); // string, can be empty
  2385. if (temp) {
  2386. channelId = temp;
  2387. }
  2388.  
  2389. }
  2390. }
  2391. anchor.setAttribute('jkrgy', channelId);
  2392. if (channelId) {
  2393. domCheckAsync(anchor, hrefAttribute, channelId);
  2394. }
  2395. }
  2396.  
  2397. }
  2398.  
  2399. const closestYtParent = (dom) => {
  2400. while (dom instanceof Element) {
  2401. if (typeof dom.is === 'string' && dom.is) return dom;
  2402. dom = dom.parentNode;
  2403. }
  2404. return null;
  2405. };
  2406. const closestYtmData = (dom) => {
  2407. while (dom instanceof Element) {
  2408. if (typeof (dom._commentData || dom.data || 0) === 'object') return dom;
  2409. dom = dom.parentNode;
  2410. }
  2411. return null;
  2412. };
  2413. const noAuthorDataSet = new Set();
  2414. const getAuthorBrowseEndpoint = (cnt) => {
  2415. let d;
  2416. let haveData = false;
  2417. if (isMobile) {
  2418. const data = ((cnt || 0).data || 0);
  2419. if (data) {
  2420. haveData = true;
  2421. if (d = (data.authorNameEndpoint || data.authorEndpoint)) return d.browseEndpoint || null;
  2422. }
  2423. } else {
  2424. const __data = ((cnt || 0).__data || 0);
  2425. if (__data) {
  2426. haveData = true;
  2427. if (d = __data.authorTextCommand) return d.browseEndpoint || null; // ytd-comment-renderer
  2428. if (d = (__data.authorNameEndpoint || __data.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (v1 & v2)
  2429. if ((d = (__data.data || 0)) && (d = (d.authorNameEndpoint || d.authorEndpoint))) return d.browseEndpoint || null; // ytd-author-comment-badge-renderer
  2430. // note: authorNameEndpoint instead of authorEndpoint for ytd-comment-view-model since 2024.04
  2431.  
  2432. } else {
  2433.  
  2434. if (d = (cnt.authorTextCommand || cnt.authorNameEndpoint || cnt.authorEndpoint)) return d.browseEndpoint || null; // ytd-comment-view-model (2024.04.30) (v3)
  2435.  
  2436. }
  2437.  
  2438. }
  2439. if (haveData) {
  2440. const tag = cnt.is;
  2441. if (!noAuthorDataSet.has(tag)) {
  2442. noAuthorDataSet.add(tag);
  2443. if (tag === 'ytd-video-description-infocards-section-renderer') {
  2444. return null; // skip console logging
  2445. } else if (tag === 'ytd-thumbnail') {
  2446. return null;
  2447. } else if (tag === 'ytd-structured-description-channel-lockup-renderer') {
  2448. return null;
  2449. } else if (tag === 'ytd-rich-grid-media') {
  2450. return null;
  2451. } else if (tag === 'ytd-rich-metadata-renderer') {
  2452. return null;
  2453. } else if (tag === 'ytd-guide-entry-renderer') {
  2454. return null;
  2455. } else if (tag === 'ytd-grid-channel-renderer') {
  2456. return null;
  2457. } else if (tag === 'ytd-channel-renderer') {
  2458. return null;
  2459. }
  2460. console.log('no browseEndpoint can be found', tag);
  2461. }
  2462. } else {
  2463. console.log('no browseEndpoint can be found', (cnt || 0).is, 'NO DATA');
  2464. }
  2465. return null;
  2466. };
  2467.  
  2468. const domAuthorNameCheckN = async (kq) => {
  2469. if (domCheckScheduledBools[kq]) return;
  2470. const selector = domCheckScheduledSelectors[kq];
  2471. if (!selector || document.querySelector(selector) === null) return;
  2472. domCheckScheduledBools[kq] = true;
  2473. await pipelineForDOMMutations(async () => {
  2474. domCheckScheduledBools[kq] = false;
  2475. try {
  2476. const newAnchors = document.querySelectorAll(selector);
  2477. if (newAnchors.length === 0) return;
  2478. await newAuthorAnchorsProceed(newAnchors);
  2479. } catch (e) {
  2480. console.log('error occur', e);
  2481. }
  2482. });
  2483. domCheckScheduledBools[kq] = false;
  2484. };
  2485.  
  2486. let _lastAnchorCount = -1;
  2487. const anchorCollection = document.getElementsByTagName('A');
  2488.  
  2489. /*
  2490. const collectionChangeObserverFn = (collection)=>{
  2491. let _len = -1;
  2492. let ws = null;
  2493. ws = new WeakSet(collection);
  2494. return {check: ()=>{
  2495. const lastLen = _len;
  2496. const len = collection.length;
  2497. if(len !== lastLen){
  2498. ws = new WeakSet(collection);
  2499. return true;
  2500. }
  2501. for (const elm of collection) {
  2502. if (!ws.has(elm)){
  2503. ws = new WeakSet(collection);
  2504. return true;
  2505. }
  2506. }
  2507. return false;
  2508. }}
  2509.  
  2510. }
  2511. */
  2512.  
  2513. const domChecker = (mutations) => {
  2514.  
  2515. const currAnchorCount = anchorCollection.length;
  2516. const lastAnchorCount = _lastAnchorCount;
  2517. _lastAnchorCount = currAnchorCount;
  2518. if (currAnchorCount === 0) return;
  2519.  
  2520. if (mutations && lastAnchorCount === currAnchorCount) {
  2521. // test to skip
  2522. let state = 0;
  2523. let addedNonElement = false;
  2524. for (const mutation of mutations) {
  2525. const addedNodes = mutation.addedNodes || 0;
  2526. const removedNodes = mutation.removedNodes || 0;
  2527. const target = mutation.target || 0;
  2528. if (target.nodeName === 'YT-FORMATTED-STRING') continue; // ignore changes in <yt-formatted-string>
  2529. if (addedNodes.length >= 1) {
  2530. state |= 1;
  2531. if (!addedNonElement) {
  2532. for (const addedNode of addedNodes) {
  2533. if (!(addedNode instanceof Element)) {
  2534. addedNonElement = true;
  2535. break;
  2536. }
  2537. }
  2538. }
  2539. if (state & 2) break;
  2540. } else if (removedNodes.length >= 1) {
  2541. state |= 2;
  2542. if (state & 1) break;
  2543. } else {
  2544. state |= 4;
  2545. break;
  2546. }
  2547. }
  2548. if (state === 1) {
  2549. if (!addedNonElement) return; // no change in anchor
  2550. } else if (state === 2) {
  2551. return; // only removal
  2552. } else if (state === 0) {
  2553. return; // no recognized mutation
  2554. }
  2555. }
  2556.  
  2557. doShortsChecking && domCheckerForShorts();
  2558. doDescriptionChecking && domCheckerForDescription();
  2559. for (let i = 0; i < domCheckScheduledSelectors.length; i++) domAuthorNameCheckN(i);
  2560.  
  2561. };
  2562.  
  2563.  
  2564. /** @type {MutationObserver | null} */
  2565. let domObserver = null;
  2566.  
  2567. /** @type {(callback: (event: Event)=>{})} */
  2568. const onPageFetched = isMobile ? (callback) => {
  2569.  
  2570. let state = 0;
  2571.  
  2572. window.addEventListener('state-change', function (evt) {
  2573. if (state === 1) return; // ignore intermediate events
  2574. state = 1; // before value: 0 or 2;
  2575. callback(evt);
  2576. }, false);
  2577.  
  2578. window.addEventListener('state-navigateend', function (evt) { // fallback
  2579. let inSeq = state === 1;
  2580. state = 2; // 2 when loaded
  2581. if (!inSeq) callback(evt);
  2582. }, false);
  2583.  
  2584. } : (callback) => {
  2585.  
  2586. let state = 0;
  2587.  
  2588. document.addEventListener('yt-page-data-fetched', function (evt) {
  2589. if (state === 1) return; // ignore intermediate events if any
  2590. state = 1; // before value: 0 or 2;
  2591. callback(evt);
  2592. }, false);
  2593.  
  2594. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  2595. let inSeq = state === 1;
  2596. state = 2; // 2 when loaded
  2597. if (!inSeq) callback(evt);
  2598. }, false);
  2599.  
  2600. };
  2601.  
  2602.  
  2603. // let mActive = false;
  2604. // let lastContent = '';
  2605. const removeAttrs = () => {
  2606. for (const s of document.querySelectorAll('a[href][dxcpj]')) {
  2607. s.removeAttribute('dxcpj');
  2608. }
  2609. for (const s of document.querySelectorAll('a[href][jkrgy]')) {
  2610. s.removeAttribute('jkrgy');
  2611. }
  2612. }
  2613.  
  2614. // setInterval(() => {
  2615. // if (!mActive) return;
  2616. // let content = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  2617. // if (content !== lastContent) {
  2618. // lastContent = content;
  2619. // removeAttrs();
  2620. // }
  2621. // }, 400);
  2622.  
  2623. /**
  2624. *
  2625. * @param {Node} app
  2626. * @returns
  2627. */
  2628. function setupOnPageFetched(app) {
  2629.  
  2630. firstDOMCheck = false;
  2631.  
  2632. if (!cfg['INNERTUBE_API_KEY']) {
  2633. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  2634. return;
  2635. }
  2636.  
  2637. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  2638. doShortsChecking = true;
  2639. } else {
  2640. doShortsChecking = false;
  2641. }
  2642.  
  2643. _lastAnchorCount = -1;
  2644.  
  2645. if (!domObserver) {
  2646. domObserver = new MutationObserver(domChecker);
  2647. } else {
  2648. domObserver.takeRecords();
  2649. domObserver.disconnect();
  2650. }
  2651.  
  2652. // lastContent = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  2653. // mActive = true;
  2654. removeAttrs();
  2655.  
  2656. domObserver.observe(app, { childList: true, subtree: true, attributes: true, attributeFilter: ['jkrgy', 'href', 'dxcpj'] });
  2657. domChecker();
  2658.  
  2659. }
  2660.  
  2661. /**
  2662. *
  2663. * @param {Object|null} dest
  2664. * @param {Object} ytcfg
  2665. * @param {string[]} keys
  2666. * @returns
  2667. */
  2668. function getYtConfig(dest, ytcfg, keys) {
  2669. dest = dest || {};
  2670. if (typeof ytcfg.get === 'function') { // mobile
  2671. for (const key of keys) {
  2672. dest[key] = ytcfg.get(key);
  2673. }
  2674. } else {
  2675. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  2676. for (const key of keys) {
  2677. dest[key] = cfgData[key];
  2678. }
  2679. }
  2680. return dest;
  2681. }
  2682.  
  2683. /** @type { (evt: Object) => Element | null } */
  2684. const getPageApp = isMobile
  2685. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  2686. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  2687.  
  2688. onPageFetched(async (evt) => {
  2689. const app = getPageApp(evt);
  2690. console.assert(app);
  2691. const ytcfg = ((window || 0).ytcfg || 0);
  2692. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  2693. setupOnPageFetched(app);
  2694. });
  2695.  
  2696. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址