Restore YouTube Username from Handle to Custom

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

目前为 2024-03-02 提交的版本。查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name Restore YouTube Username from Handle to Custom
  28. // @namespace http://tampermonkey.net/
  29. // @version 0.11.014
  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://github.com/cyfung1031/userscript-supports/raw/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. let object = channelIdToHandle.get(mt);
  839.  
  840. if (object) {
  841.  
  842. const handleText = object.handleText;
  843.  
  844. if (handleText === name) channelIdToHandle.delete(mt);
  845. else {
  846. object.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. /**
  879. *
  880. * @param {string} channelId
  881. */
  882. function stackNewRequest(channelId) {
  883.  
  884. mutex.add(lockResolve => {
  885.  
  886. let bResult = displayNameResStore.get(channelId);
  887. if (!(bResult instanceof AsyncValue)) {
  888. // resolved or removed
  889. lockResolve(); lockResolve = null;
  890. return;
  891. }
  892.  
  893. let setResult = (result) => {
  894. setResult = null;
  895. if (!result) {
  896. bResult.fetchingState = 0;
  897. bResult.setValue(null);
  898. displayNameResStore.delete(channelId); // create another network response in the next request
  899. } else {
  900. bResult.fetchingState = 4;
  901. bResult.setValue(result);
  902. displayNameResStore.set(channelId, result); // update store result to resolved value
  903. }
  904. bResult = null;
  905. }
  906.  
  907. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  908. // request is already done. no need to stack any request
  909. lockResolve(); lockResolve = null;
  910. return;
  911. }
  912.  
  913. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  914. // element has already been removed
  915. lockResolve(); lockResolve = null;
  916. setResult(null);
  917. return;
  918. }
  919.  
  920. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  921.  
  922. bResult.fetchingState = 2;
  923.  
  924.  
  925. const retry = () => {
  926.  
  927. fetchRSSFailed = true;
  928.  
  929. bResult.fetchingState = 2;
  930.  
  931. // Promise.resolve(channelId).then(stackNewRequest);
  932. fetcherBrowseAPI(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  933. }
  934.  
  935. const mobj = {
  936. fetchOnDownload: () => {
  937. bResult.fetchingState = 3;
  938. },
  939. fetchOnSuccess: resultInfo => {
  940.  
  941. if (resultInfo === -1) {
  942. retry();
  943. return;
  944. }
  945.  
  946. lockResolve && lockResolve();
  947. lockResolve = null;
  948. // console.log(900)
  949.  
  950. if (!resultInfo) {
  951. // invalid json format
  952. setResult(null);
  953. return;
  954. }
  955.  
  956. if (IGNORE_NO_NAME) {
  957. const titleForDisplay = resultInfo.langTitle || resultInfo.title;
  958. if (!titleForDisplay) {
  959. const handle = channelIdToHandle.get(channelId);
  960. if (handle && handle.handleText) {
  961. resultInfo.langTitle = resultInfo.title = handle.handleText;
  962. } else {
  963. setResult(null);
  964. return;
  965. }
  966. }
  967. }
  968.  
  969. cacheHandleToChannel(resultInfo, channelId);
  970.  
  971. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  972.  
  973. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  974.  
  975. setResult(displayNameRes);
  976. },
  977. fetchOnFail: e => {
  978.  
  979.  
  980. console.warn(e);
  981. if (mobj.fetcher === fetcherRSS) {
  982. retry();
  983.  
  984. } else {
  985.  
  986. lockResolve && lockResolve();
  987. lockResolve = null;
  988. // console.warn(e);
  989. setResult && setResult(null);
  990. }
  991. }
  992. }
  993.  
  994.  
  995. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  996. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  997. mobj.fetcher = USE_RSS_FETCHER && fetcherRSS && !fetchRSSFailed && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  998. mobj.fetcher(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  999.  
  1000. });
  1001.  
  1002. }
  1003.  
  1004. /**
  1005. *
  1006. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  1007. * @returns Example: _\@yr__kd_
  1008. */
  1009. function urlToHandle(url) {
  1010.  
  1011. if (typeof url !== 'string') return '';
  1012. let i = url.indexOf('.youtube.com/');
  1013. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  1014. else if (url.charAt(0) === '/') url = url.substring(1);
  1015. return isDisplayAsHandle(url) ? url : '';
  1016.  
  1017. }
  1018.  
  1019. /**
  1020. *
  1021. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  1022. * @returns {Promise<DisplayNameResultObject | null>}
  1023. */
  1024. async function getDisplayName(channelId) {
  1025.  
  1026. let cache = displayNameResStore.get(channelId);
  1027. let isStackNewRequest = false;
  1028.  
  1029. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  1030. let aResult;
  1031.  
  1032. if (cache instanceof AsyncValue) {
  1033. aResult = cache;
  1034. if (aResult.fetchingState >= 2) {
  1035. // aResult.fetchingState
  1036. // 2: network fetch started
  1037. // 3: network fetch ended
  1038. // isStackNewRequest = false;
  1039. } else {
  1040. // 0: invalid before
  1041. // 1: scheduled but not yet fetch
  1042. isStackNewRequest = true;
  1043. }
  1044. } else if (cache) {
  1045. // resolved result
  1046. return cache;
  1047. } else {
  1048. // else no cached value found
  1049. /** @type {AsyncValue<DisplayNameResultObject>} */
  1050. aResult = new AsyncValue();
  1051. displayNameResStore.set(channelId, aResult);
  1052. isStackNewRequest = true;
  1053. }
  1054.  
  1055. if (isStackNewRequest) {
  1056. aResult.fetchingState = 1;
  1057. stackNewRequest(channelId);
  1058. }
  1059. return await aResult.getValue();
  1060. }
  1061.  
  1062.  
  1063. /**
  1064. *
  1065. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  1066. * @returns
  1067. * * Outdated?
  1068. */
  1069. const obtainChannelId = (href) => {
  1070. const s = `/${href}`;
  1071. if (s.length >= 33) {
  1072. const m = /\/channel\/(UC[-_a-zA-Z0-9+=.]{22})(\/|$)/.exec(s);
  1073. return !m ? '' : (m[1] || '');
  1074. }
  1075. return '';
  1076. };
  1077.  
  1078. const isUCBrowserId = (browseId) => {
  1079. return typeof browseId === 'string' && browseId.length === 24 && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId);
  1080. }
  1081.  
  1082.  
  1083. /**
  1084. *
  1085. * @param {Element} ytElm
  1086. */
  1087. const resetWhenDataChanged = (ths) => {
  1088. const cnt = insp(ths);
  1089. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1090. if (ytElm instanceof Element) {
  1091. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1092. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1093. if ((anchors || 0).length >= 1 && (insp(ytElm).data || 0).jkrgx !== 1) {
  1094. for (const anchor of anchors) {
  1095. anchor.removeAttribute('jkrgy');
  1096. }
  1097. }
  1098. }
  1099. }
  1100.  
  1101. /**
  1102. *
  1103. * @param {Element} ytElm
  1104. */
  1105. const resetWhenPropChanged = (ths) => {
  1106. const cnt = insp(ths);
  1107. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1108. if (ytElm instanceof Element) {
  1109. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1110. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1111. if ((anchors || 0).length >= 1 && ((insp(ytElm).commentEntity || 0).author || 0).jkrgx !== 1) {
  1112. for (const anchor of anchors) {
  1113. anchor.removeAttribute('jkrgy');
  1114. }
  1115. }
  1116. }
  1117. }
  1118.  
  1119. /**
  1120. *
  1121. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  1122. * @param {string} hrefAttribute Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ (old) 2024 Feb -> /@user-abc1234
  1123. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  1124. * @returns
  1125. */
  1126. const anchorIntegrityCheck = (anchor, hrefAttribute) => {
  1127.  
  1128. let currentHref = anchor.getAttribute('href');
  1129. if (currentHref === hrefAttribute) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  1130.  
  1131. return (currentHref + '/').indexOf(hrefAttribute + '/') >= 0;
  1132.  
  1133. };
  1134.  
  1135. /**
  1136. *
  1137. * @param {string} currentDisplayed
  1138. * @param {DisplayNameResultObject} fetchResult
  1139. * @returns
  1140. */
  1141. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  1142.  
  1143. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  1144.  
  1145. const currentDisplayTrimmed = currentDisplayed.trim(); // @IORIMATSUNAGA
  1146. const currentDisplayTrimmedLowerCase = currentDisplayTrimmed.toLowerCase(); // @iorimatsunaga
  1147. let match = false;
  1148. if (verified123) {
  1149. match = true;
  1150. } else if ((vanityChannelUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmedLowerCase}`)) {
  1151. match = true;
  1152. } else if ((ownerUrls || 0).length >= 1) {
  1153. for (const ownerUrl of ownerUrls) {
  1154. if ((ownerUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmed}`)) {
  1155. match = true;
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. if (match) {
  1161. return currentDisplayTrimmed;
  1162. }
  1163. return '';
  1164.  
  1165. };
  1166.  
  1167. /**
  1168. *
  1169. *
  1170.  
  1171. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  1172.  
  1173. - Is between 3-30 characters
  1174. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1175. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  1176. - Is not URL-like or phone number-like
  1177. - Is not already being used
  1178. - Follows YouTube's Community Guidelines
  1179.  
  1180. ### Handle automatically generated by YouTube
  1181. - `@user-XXXX`
  1182. - without dot (.)
  1183. *
  1184. * @param {string} text
  1185. * @returns
  1186. */
  1187. const isDisplayAsHandle = (text) => {
  1188.  
  1189. if (typeof text !== 'string') return false;
  1190. if (text.length < 4) return false;
  1191. if (text.indexOf('@') < 0) return false;
  1192. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  1193.  
  1194. };
  1195.  
  1196. /**
  1197. *
  1198. * @param {Object[]} contentTexts
  1199. * @param {number} idx
  1200. * @returns
  1201. */
  1202. const contentTextProcess = (contentTexts, idx) => {
  1203. const contentText = contentTexts[idx];
  1204. const text = (contentText || 0).text;
  1205. const browseId = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1206. const canonicalBaseUrl = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1207. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1208. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1209.  
  1210. if (!isDisplayAsHandle(text)) return null;
  1211. const channelId = browseId;
  1212.  
  1213. return getDisplayName(channelId).then(fetchResult => {
  1214. let resolveResult = null;
  1215. if (fetchResult) {
  1216. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1217.  
  1218. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1219. if (textTrimmed) {
  1220. resolveResult = (md) => {
  1221. let runs = ((md || 0).contentText || 0).runs;
  1222. if (!runs || !runs[idx]) return;
  1223. if (runs[idx].text !== text) return;
  1224. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1225. md.contentText = Object.assign({}, md.contentText);
  1226. };
  1227. }
  1228. }
  1229. return resolveResult; // function as a Promise
  1230. });
  1231. }
  1232.  
  1233. return null;
  1234. };
  1235.  
  1236. const editableTextProcess = (editableTexts, idx) => {
  1237. const editableText = editableTexts[idx];
  1238. const text = (editableText || 0).text;
  1239.  
  1240. const browseId = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1241. const canonicalBaseUrl = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1242. const url = (((editableText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1243. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1244.  
  1245. if (!isDisplayAsHandle(text)) return null;
  1246. const channelId = browseId;
  1247.  
  1248. return getDisplayName(channelId).then(fetchResult => {
  1249. let resolveResult = null;
  1250. if (fetchResult) {
  1251. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1252.  
  1253. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1254. if (textTrimmed) {
  1255. resolveResult = (md) => {
  1256. let commentReplyDialogRenderer = null;
  1257. try {
  1258. commentReplyDialogRenderer = md.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1259. } catch (e) { }
  1260. if (!commentReplyDialogRenderer) return;
  1261. const editableText = commentReplyDialogRenderer.editableText || 0;
  1262.  
  1263. let runs = (editableText || 0).runs;
  1264. if (!runs || !runs[idx]) return;
  1265. if (runs[idx].text !== text) return;
  1266. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1267. commentReplyDialogRenderer.editableText = Object.assign({}, commentReplyDialogRenderer.editableText);
  1268. };
  1269. }
  1270. }
  1271. return resolveResult; // function as a Promise
  1272. });
  1273. }
  1274.  
  1275. return null;
  1276. };
  1277. const contentTextProcessViewModel = async (content, idx) => {
  1278. const { commandRuns, content: text, styleRuns } = content;
  1279. if (typeof text !== 'string') return;
  1280. const names = [];
  1281.  
  1282. function replaceNamePN(o) {
  1283. return getDisplayName(o.channelId).then(fetchResult => {
  1284. let resolveResult = null;
  1285. if (fetchResult) {
  1286. const textTrimmed = verifyAndConvertHandle(o.handle, fetchResult);
  1287. if (textTrimmed) {
  1288. o.display = `@${fetchResult.title}`;
  1289. o.newText = o.oldText.replace(o.handle, o.display);
  1290. }
  1291. }
  1292. return resolveResult; // function as a Promise
  1293. });
  1294. }
  1295. const promises = [];
  1296. for (const commandRun of commandRuns) {
  1297. let browseEndpoint = null;
  1298. if (commandRun.length >= 1 && commandRun.startIndex >= 0 && (browseEndpoint = ((commandRun.onTap || 0).innertubeCommand || 0).browseEndpoint)) {
  1299. let substr = text.substring(commandRun.startIndex, commandRun.startIndex + commandRun.length);
  1300. const substrTrimmed = substr.trim();
  1301. if (isDisplayAsHandle(substrTrimmed) && `/${substrTrimmed}` === browseEndpoint.canonicalBaseUrl && isUCBrowserId(browseEndpoint.browseId)) {
  1302. const o = {
  1303. startIndex: commandRun.startIndex,
  1304. endIndex: commandRun.startIndex + commandRun.length,
  1305. handle: substrTrimmed,
  1306. oldText: substr,
  1307. newText: null,
  1308. channelId: browseEndpoint.browseId,
  1309. nStartIndex: null,
  1310. nEndIndex: null,
  1311. nText: null
  1312. }
  1313. names.push(o);
  1314. promises.push(replaceNamePN(o));
  1315. }
  1316. }
  1317. }
  1318. await Promise.all(promises);
  1319.  
  1320. let offset = 0;
  1321. for (const o of names) {
  1322. o.nStartIndex = o.startIndex + offset;
  1323. o.nText = o.newText === null ? o.oldText : o.newText;
  1324. o.nEndIndex = o.nStartIndex + offset + o.nText.length;
  1325. offset += o.nText.length - o.oldText.length;
  1326. }
  1327.  
  1328. let w1 = 0, w2 = 0;
  1329. let s = [];
  1330. let j = 0;
  1331. for (let i = 0; i < text.length;) {
  1332. while (w1 < commandRuns.length && commandRuns[w1].startIndex < i) w1++;
  1333. while (w2 < styleRuns.length && styleRuns[w2].startIndex < i) w2++;
  1334.  
  1335. if (j < names.length && i == names[j].startIndex) {
  1336.  
  1337. if (w1 < commandRuns.length && commandRuns[w1].startIndex === names[j].startIndex) {
  1338. const run = commandRuns[w1];
  1339. const o = names[j];
  1340. if (run.length === o.endIndex - o.startIndex) {
  1341. run.startIndex = o.nStartIndex;
  1342. run.length = o.nText.length;
  1343. }
  1344. w1++;
  1345. }
  1346.  
  1347. if (w2 < styleRuns.length && styleRuns[w2].startIndex === names[j].startIndex) {
  1348. const run = styleRuns[w2];
  1349. const o = names[j];
  1350. if (run.length === o.endIndex - o.startIndex) {
  1351. run.startIndex = o.nStartIndex;
  1352. run.length = o.nText.length;
  1353. }
  1354. w2++;
  1355. }
  1356.  
  1357.  
  1358. // s.push(text.substring(names[j].startIndex, names[j].endIndex));
  1359. s.push(names[j].nText);
  1360. i = names[j].endIndex;
  1361. j++;
  1362. } else {
  1363. if (j >= names.length) {
  1364. s.push(text.substring(i));
  1365. i = text.length;
  1366. } else {
  1367. if (j < names.length && names[j].startIndex > i + 1) {
  1368. s.push(text.substring(i, names[j].startIndex));
  1369. i = names[j].startIndex;
  1370. } else {
  1371. s.push(text.charAt(i));
  1372. i++;
  1373. }
  1374. }
  1375. }
  1376. }
  1377.  
  1378. content.content = s.join('');
  1379. s.length = 0;
  1380.  
  1381.  
  1382. };
  1383.  
  1384. /**
  1385. *
  1386. * @param {ParentNode & Element} parentNode
  1387. * @param {Function} callback
  1388. */
  1389. function findTextNodes(parentNode, callback) {
  1390. /**
  1391. *
  1392. * @param {Node} node
  1393. * @returns
  1394. */
  1395. function traverse(node) {
  1396. if (node.nodeType === Node.TEXT_NODE) {
  1397. let r = callback(node);
  1398. if (r === true) return true;
  1399. } else if (node.nodeType === Node.ELEMENT_NODE) {
  1400. for (let childNode = nodeFirstChild(node); childNode; childNode = nodeNextSibling(childNode)) {
  1401. const r = traverse(childNode);
  1402. if (r === true) return true;
  1403. }
  1404. }
  1405. }
  1406.  
  1407. traverse(parentNode);
  1408. }
  1409.  
  1410. function updatePinnedCommentBadge(md, title, langTitle) {
  1411. const titleForDisplay = langTitle || title;
  1412. if (typeof titleForDisplay !== 'string') return;
  1413. if (title === titleForDisplay) return;
  1414. const runs = ((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0); // can be 0
  1415. if (runs.length === 2) {
  1416. let idx = 0;
  1417. let jdx = -1;
  1418. for (const textRun of runs) {
  1419. if (textRun.text === title) {
  1420. jdx = idx;
  1421. break;
  1422. }
  1423. idx++;
  1424. }
  1425. if (jdx >= 0) {
  1426. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  1427. runs[jdx] = Object.assign({}, runs[jdx], { text: titleForDisplay });
  1428. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  1429. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  1430. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  1431. }
  1432. }
  1433. }
  1434.  
  1435. /**
  1436. *
  1437. * @param {ParentNode} parentNode
  1438. * @param {Object[]} contentTexts
  1439. * @param {number} aidx
  1440. * @returns
  1441. */
  1442. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  1443.  
  1444.  
  1445. let commentText = elementQS(parentNode, '.comment-text');
  1446. if (!commentText) return;
  1447. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  1448. let currentText = commentText.textContent;
  1449. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1450. if (!textMatch) return;
  1451.  
  1452. const contentText = contentTexts[aidx];
  1453.  
  1454. /** @type {string} */
  1455. const handleText = contentText.text.trim();
  1456. /** @type {string | null | undefined} */
  1457. let channelId;
  1458.  
  1459. let cache = handleToChannelId.get(handleText);
  1460.  
  1461. if (typeof cache === 'string') {
  1462. channelId = cache;
  1463. } else if (cache instanceof AsyncValue) {
  1464. channelId = await cache.getValue();
  1465. } else {
  1466. /** @type {AsyncValue<string>} */
  1467. const asyncValue = new AsyncValue();
  1468. handleToChannelId.set(handleText, asyncValue);
  1469. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1470. }
  1471.  
  1472. if (!channelId) return; // just in case
  1473.  
  1474. if (commentText.isConnected !== true) return; // already removed
  1475. if (commentText.textContent !== currentText) return; // already changed
  1476.  
  1477. const fetchResult = await getDisplayName(channelId);
  1478.  
  1479. if (fetchResult === null) return;
  1480.  
  1481. const { title, langTitle, externalId } = fetchResult;
  1482. const titleForDisplay = langTitle || title;
  1483. if (externalId !== channelId) return; // channel id must be the same
  1484.  
  1485. if (commentText.isConnected !== true) return; // already removed
  1486. if (commentText.textContent !== currentText) return; // already changed
  1487.  
  1488. let search = contentText.text;
  1489. if (typeof search === 'string') {
  1490.  
  1491. const searchTrimmed = search.trim();
  1492. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1493. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  1494.  
  1495. findTextNodes(commentText, (textnode) => {
  1496. if (textnode.nodeValue.indexOf(search) >= 0) {
  1497. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1498. return true;
  1499. }
  1500. });
  1501. }
  1502.  
  1503. }
  1504.  
  1505. }
  1506.  
  1507. /**
  1508. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1509. * @type { (anchor: HTMLElement, anchorHref: string?, mt: string?) => Promise<void> }
  1510. */
  1511.  
  1512. const getDisplayTextDOMForCommentRenderer = (root) => { // mobile
  1513. let displayTextDOM = elementQS(root, '.comment-header .comment-title');
  1514. if (displayTextDOM) {
  1515. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1516. }
  1517. return displayTextDOM;
  1518. }
  1519.  
  1520. const ytPathnameExtract = (href) => {
  1521.  
  1522. if (!href || typeof href !== 'string') return '';
  1523. let i = 0;
  1524. if (href.startsWith('/')) {
  1525.  
  1526. } else if ((i = href.indexOf('youtube.com/')) >= 0) {
  1527. href = href.substring(i + 11);
  1528. } else {
  1529. return '';
  1530. }
  1531. return href;
  1532.  
  1533. }
  1534.  
  1535. const getHrefType = (href) => {
  1536. if (href.length === 33 && href.startsWith('/channel/') && /^\/channel\/UC[-_a-zA-Z0-9+=.]{22}$/.test(href)) {
  1537. return 1;
  1538. } else if (href.length >= 5 && href.length <= 32 && href.startsWith('/@') && /^\/@[-_a-zA-Z0-9.]{3,30}$/.test(href)) {
  1539. return 2;
  1540. }
  1541. return 0;
  1542. }
  1543.  
  1544. const getYTextType = (text) => {
  1545. // if (typeof text === 'string') return 1;
  1546. if (typeof text === 'object' && text) {
  1547. if (typeof text.simpleText === 'string') return 2;
  1548. const runs = text.runs;
  1549. if (runs && runs.length === 1) {
  1550. let r = runs[0];
  1551. return typeof r === 'string' ? 3 : typeof (r || 0).text === 'string' ? 4 : null;
  1552. }
  1553. }
  1554. return null;
  1555. }
  1556.  
  1557. const getYTextContent = (text) => {
  1558. // if (typeof text === 'string') return text;
  1559. if (typeof text === 'object' && text) {
  1560. const simpleText = text.simpleText;
  1561. if (typeof simpleText === 'string') return simpleText;
  1562. const runs = text.runs;
  1563. if (runs && runs.length === 1) {
  1564. let r = runs[0];
  1565. return typeof r === 'string' ? r : typeof (r || 0).text === 'string' ? r.text : null;
  1566. }
  1567. }
  1568. return null;
  1569. }
  1570.  
  1571. const setYTextContent = (text, fn) => {
  1572. // if (typeof text === 'string') {
  1573. // res=fn(text);
  1574. // }
  1575. if (typeof text === 'object' && text) {
  1576. const simpleText = text.simpleText;
  1577. if (typeof simpleText === 'string') {
  1578. return Object.assign({}, text, { simpleText: fn(simpleText) });
  1579. }
  1580. const runs = text.runs;
  1581. if (runs && runs.length === 1) {
  1582. let r = runs[0];
  1583. 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;
  1584. }
  1585. }
  1586. return null;
  1587. }
  1588.  
  1589. const domCheckAsync = isMobile ? async (anchor, hrefAttribute, mt) => {
  1590.  
  1591. let sHandleName = null;
  1592. let sNodeValue = null;
  1593. try {
  1594. if (!hrefAttribute || !mt) return;
  1595. let parentNode = nodeParent(anchor);
  1596. while (parentNode instanceof Node) {
  1597. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1598. parentNode = nodeParent(parentNode);
  1599. }
  1600. if (parentNode instanceof Node) { } else return;
  1601.  
  1602. const commentRendererAuthorTextDOM = getDisplayTextDOMForCommentRenderer(parentNode);
  1603. const anchorAiraLabel = anchor.getAttribute('aria-label');
  1604. const anchorHrefValue = ytPathnameExtract(anchor.getAttribute('href')); // guess (Feb 2024)
  1605.  
  1606. const cnt = insp(parentNode);
  1607. const parentNodeData = cnt._commentData || cnt.data || 0;
  1608. const authorTextData = (parentNodeData.authorText || 0);
  1609.  
  1610. let tHandleName = null;
  1611.  
  1612. if (commentRendererAuthorTextDOM && authorTextData) {
  1613. const hType = getHrefType(anchorHrefValue);
  1614. let ytext = null;
  1615. if (hType === 2) {
  1616. tHandleName = anchorHrefValue.substring(1); // guess
  1617. } else if (hType === 1) {
  1618. ytext = getYTextContent(authorTextData)
  1619. tHandleName = ytext; // authorTextData.runs[0].text
  1620. }
  1621. if (typeof tHandleName === 'string' && commentRendererAuthorTextDOM.textContent.trim() === tHandleName && isDisplayAsHandle(tHandleName)) {
  1622. ytext = ytext || getYTextContent(authorTextData)
  1623. if (ytext === tHandleName) {
  1624. sHandleName = tHandleName;
  1625. sNodeValue = tHandleName;
  1626. }
  1627. }
  1628. }
  1629.  
  1630. if (typeof sHandleName === 'string' && typeof sNodeValue === 'string') {
  1631.  
  1632. if (!channelIdToHandle.has(mt)) {
  1633. channelIdToHandle.set(mt, {
  1634. handleText: sHandleName,
  1635. justPossible: true
  1636. });
  1637. }
  1638.  
  1639. const fetchResult = await getDisplayName(mt);
  1640.  
  1641. if (fetchResult === null) return;
  1642.  
  1643. const { title, langTitle, externalId } = fetchResult;
  1644. const titleForDisplay = langTitle || title;
  1645. if (externalId !== mt) return; // channel id must be the same
  1646.  
  1647. // anchor href might be changed by external
  1648. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1649.  
  1650. if (commentRendererAuthorTextDOM.isConnected !== true) return; // already removed
  1651.  
  1652. let found = false;
  1653.  
  1654. findTextNodes(commentRendererAuthorTextDOM, (textnode) => {
  1655. if (textnode.nodeValue === sNodeValue) {
  1656. textnode.nodeValue = titleForDisplay;
  1657. found = true;
  1658. return true;
  1659. }
  1660. });
  1661.  
  1662. if (!found) return;
  1663. if (anchorAiraLabel && anchorAiraLabel.trim() === sHandleName) anchor.setAttribute('aria-label', anchorAiraLabel.replace(sHandleName, titleForDisplay));
  1664. const authorTextDataNew = setYTextContent(authorTextData, (t) => t.replace(t.trim(), titleForDisplay));
  1665. if (authorTextDataNew && parentNodeData.authorText === authorTextData) {
  1666. parentNodeData.authorText = authorTextDataNew;
  1667. }
  1668.  
  1669. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  1670. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  1671. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  1672. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  1673. const tc = spanText ? spanText.textContent : '';
  1674. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  1675. let idx;
  1676. if (tc && tc === spanText.textContent && (idx = tc.indexOf(title)) >= 0) {
  1677. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  1678. }
  1679. }
  1680.  
  1681. const contentTexts = (parentNodeData.contentText || 0).runs;
  1682. if (contentTexts && contentTexts.length >= 2) {
  1683. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1684. const contentText = contentTexts[aidx] || 0;
  1685. if (contentText.italics !== true && isDisplayAsHandle(contentText.text)) {
  1686. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1687. }
  1688. }
  1689. }
  1690.  
  1691. }
  1692.  
  1693. } catch (e) {
  1694. console.warn(e);
  1695. }
  1696.  
  1697. } : async (anchor, hrefAttribute, mt) => {
  1698.  
  1699. try {
  1700. if (!hrefAttribute || !mt) return;
  1701. let parentNode = nodeParent(anchor);
  1702. let isCommentViewModel = false;
  1703. while (parentNode instanceof Node) {
  1704. const cnt = insp(parentNode);
  1705. if (typeof cnt.is === 'string') {
  1706. if (cnt.commentEntity && cnt._propertiesChanged) { isCommentViewModel = true; break; } // Feb 2024: ytd-comment-view-model
  1707. else if (typeof cnt.dataChanged === 'function') break;
  1708. }
  1709. parentNode = nodeParent(parentNode);
  1710. }
  1711. if (parentNode instanceof Node) { } else return;
  1712. const parentNodeController = insp(parentNode);
  1713.  
  1714. if (isCommentViewModel) {
  1715.  
  1716. const commentEntity = parentNodeController.commentEntity || 0;
  1717. const commentEntityAuthor = commentEntity.author || 0;
  1718. const currentDisplayed = commentEntityAuthor.displayName || 0;
  1719. if (typeof currentDisplayed !== 'string') return;
  1720. if (!isDisplayAsHandle(currentDisplayed)) return;
  1721. if (!channelIdToHandle.has(mt)) {
  1722. channelIdToHandle.set(mt, {
  1723. handleText: currentDisplayed.trim(),
  1724. justPossible: true
  1725. });
  1726. }
  1727.  
  1728. if (typeof parentNodeController._propertiesChanged === 'function' && !parentNodeController._propertiesChanged159) {
  1729. const cntp = parentNodeController.constructor.prototype;
  1730. const c = cntp._propertiesChanged === parentNodeController._propertiesChanged ? cntp : parentNodeController;
  1731. c._propertiesChanged159 = c._propertiesChanged;
  1732. c._propertiesChanged = function () {
  1733. resetWhenPropChanged(this);
  1734. return this._propertiesChanged159.apply(this, arguments);
  1735. };
  1736. }
  1737.  
  1738. const fetchResult = await getDisplayName(mt);
  1739.  
  1740. if (fetchResult === null) return;
  1741.  
  1742. const { title, langTitle, externalId } = fetchResult;
  1743. const titleForDisplay = langTitle || title;
  1744. if (externalId !== mt) return; // channel id must be the same
  1745.  
  1746. // anchor href might be changed by external
  1747. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1748.  
  1749. if (commentEntityAuthor.displayName === currentDisplayed && commentEntityAuthor.channelId === mt) {
  1750. commentEntityAuthor.displayName = titleForDisplay;
  1751.  
  1752. if (commentEntity.properties) {
  1753. if (commentEntity.properties.authorButtonA11y === currentDisplayed) {
  1754. commentEntity.properties.authorButtonA11y = titleForDisplay;
  1755. }
  1756.  
  1757. // the inside hyperlinks will be only converted if its parent author name is handle
  1758. const content = commentEntity.properties.content;
  1759. if (content && (content.commandRuns || 0).length >= 1) {
  1760. try {
  1761. await contentTextProcessViewModel(content);
  1762.  
  1763. // $0.polymerController.commentEntity = Object.assign({}, $0.polymerController.commentEntity , { properties: Object.assign({}, $0.polymerController.commentEntity.properties, { content: Object.assign({},$0.polymerController.commentEntity.properties.content) } )})
  1764.  
  1765. // parentNodeController.commentEntity.properties = Object.assign({}, parentNodeController.commentEntity.properties, {
  1766. // content: Object.assign({}, parentNodeController.commentEntity.properties.content)
  1767. // });
  1768.  
  1769. commentEntity.properties.content = Object.assign({}, content);
  1770. } catch (e) {
  1771. console.log(e);
  1772. }
  1773.  
  1774. }
  1775.  
  1776. }
  1777.  
  1778. if (commentEntityAuthor && parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1779. commentEntityAuthor.jkrgx = 1;
  1780. addCSSRulesIfRequired();
  1781. }
  1782.  
  1783. parentNodeController.commentEntity = Object.assign({}, parentNodeController.commentEntity);
  1784.  
  1785. }
  1786.  
  1787. } else {
  1788.  
  1789. const authorText = (parentNodeController.data || 0).authorText;
  1790. const currentDisplayed = getYTextContent(authorText || 0); // authorText.simpleText
  1791. if (typeof currentDisplayed !== 'string') return;
  1792. if (!isDisplayAsHandle(currentDisplayed)) return;
  1793.  
  1794. if (!channelIdToHandle.has(mt)) {
  1795. channelIdToHandle.set(mt, {
  1796. handleText: currentDisplayed.trim(),
  1797. justPossible: true
  1798. });
  1799. }
  1800.  
  1801. if (typeof parentNodeController.dataChanged === 'function' && !parentNodeController.dataChanged159) {
  1802. const cntp = parentNodeController.constructor.prototype;
  1803. const c = cntp.dataChanged === parentNodeController.dataChanged ? cntp : parentNodeController;
  1804. c.dataChanged159 = c.dataChanged;
  1805. c.dataChanged = function () {
  1806. resetWhenDataChanged(this);
  1807. return this.dataChanged159.apply(this, arguments);
  1808. };
  1809. }
  1810.  
  1811. const fetchResult = await getDisplayName(mt);
  1812.  
  1813. if (fetchResult === null) return;
  1814.  
  1815. const { title, langTitle, externalId } = fetchResult;
  1816. const titleForDisplay = langTitle || title;
  1817. if (externalId !== mt) return; // channel id must be the same
  1818.  
  1819. // anchor href might be changed by external
  1820. if (!anchorIntegrityCheck(anchor, hrefAttribute)) return;
  1821.  
  1822. const parentNodeData = parentNodeController.data;
  1823. const funcPromises = [];
  1824.  
  1825. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1826.  
  1827. if (getYTextContent(authorText) !== currentDisplayed) return;
  1828. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1829. const cSimpleText = (getYTextContent(parentNodeData.authorText || 0) || '');
  1830. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  1831.  
  1832. // the inside hyperlinks will be only converted if its parent author name is handle
  1833. const contentTexts = (parentNodeData.contentText || 0).runs;
  1834. if (contentTexts && contentTexts.length >= 1) {
  1835. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1836. const r = contentTextProcess(contentTexts, aidx);
  1837. if (r instanceof Promise) funcPromises.push(r);
  1838. }
  1839. }
  1840.  
  1841. const md = Object.assign({}, parentNodeData);
  1842. const authorCommentBadgeAuthorText = (((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0);
  1843.  
  1844. const authorCommentBadgeAuthorTextNew = authorCommentBadgeAuthorText ? setYTextContent(authorCommentBadgeAuthorText, (currentText) => {
  1845. if ((currentText || '').trim() === cSimpleText.trim()) {
  1846. return (currentText || '').replace((currentText || '').trim(), titleForDisplay);
  1847. } else {
  1848. return currentText;
  1849. }
  1850. }) : null;
  1851.  
  1852. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1853. const authorTextNew = setYTextContent(md.authorText, (t) => t.replace(currentDisplayTrimmed, titleForDisplay))
  1854. md.authorText = authorTextNew;
  1855.  
  1856. if (authorCommentBadgeAuthorTextNew) {
  1857. const authorCommentBadgeRendererNew = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer, { authorText: authorCommentBadgeAuthorTextNew });
  1858. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge, { authorCommentBadgeRenderer: authorCommentBadgeRendererNew });
  1859. }
  1860.  
  1861. let setReplyEditableText = false;
  1862. if (((((((((parentNodeData.actionButtons || 0).commentActionButtonsRenderer || 0).replyButton || 0).buttonRenderer || 0).navigationEndpoint || 0).createCommentReplyDialogEndpoint || 0).dialog || 0).commentReplyDialogRenderer || 0).editableText) {
  1863. setReplyEditableText = true;
  1864. }
  1865. if (setReplyEditableText) {
  1866. const commentReplyDialogRenderer = parentNodeData.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1867. const editableText = commentReplyDialogRenderer.editableText;
  1868. const editableTexts = editableText.runs;
  1869. if (editableTexts && editableTexts.length >= 1) {
  1870. for (let aidx = 0; aidx < editableTexts.length; aidx++) {
  1871. const r = editableTextProcess(editableTexts, aidx);
  1872. if (r instanceof Promise) funcPromises.push(r);
  1873. }
  1874. }
  1875. }
  1876.  
  1877. if (UPDATE_PIN_NAME) {
  1878. updatePinnedCommentBadge(md, title, langTitle);
  1879. }
  1880.  
  1881. if (funcPromises.length >= 1) {
  1882. let funcs = await Promise.all(funcPromises);
  1883.  
  1884. for (const func of funcs) {
  1885. if (typeof func === 'function') {
  1886. func(md);
  1887. }
  1888. }
  1889. }
  1890.  
  1891. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1892. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  1893. addCSSRulesIfRequired();
  1894. }
  1895.  
  1896.  
  1897. }
  1898.  
  1899. }
  1900. }
  1901. } catch (e) {
  1902. console.warn(e);
  1903. }
  1904.  
  1905. }
  1906.  
  1907. /**
  1908. *
  1909. * @param {string} url
  1910. * @returns
  1911. */
  1912. const channelUrlUnify = (url) => {
  1913.  
  1914. if (typeof url !== 'string') return url; // type unchanged
  1915. let c0 = url.charAt(0);
  1916. if (c0 === '/') return url;
  1917. let i = url.indexOf('.youtube.com/');
  1918. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1919. else if (url.charAt(0) !== '/') url = '/' + url;
  1920. return url
  1921.  
  1922. }
  1923.  
  1924. const parentYtElement = (node, nodeName, maxN) => {
  1925. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1926. if (pDom.nodeName === nodeName) {
  1927. return pDom;
  1928. }
  1929. }
  1930. return null;
  1931. }
  1932.  
  1933. const checkShortsChannelName = (rchannelNameDOM) => {
  1934. let browseId = '';
  1935. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1936.  
  1937. if (pDom instanceof HTMLElement) {
  1938. const pDomController = insp(pDom);
  1939. const channelTitleText = (pDomController.data || 0).channelTitleText || 0;
  1940. const runs = ((channelTitleText || 0).runs || 0);
  1941. if (getYTextType(channelTitleText) === 4) {
  1942. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1943. browseId = (browserEndpoint.browseId || '');
  1944. const currentDisplayText = runs[0].text || ''
  1945.  
  1946. if (isUCBrowserId(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1947.  
  1948. if (!channelIdToHandle.has(browseId)) {
  1949. channelIdToHandle.set(browseId, {
  1950. handleText: currentDisplayText.trim(),
  1951. justPossible: true
  1952. });
  1953. }
  1954.  
  1955. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1956. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1957. // anchorNode &&
  1958. getDisplayName(browseId).then(fetchResult => {
  1959.  
  1960. if (fetchResult === null) return;
  1961.  
  1962. const { title, langTitle, externalId } = fetchResult;
  1963. const titleForDisplay = langTitle || title;
  1964. if (externalId !== browseId) return; // channel id must be the same
  1965.  
  1966. const hDom = pDom;
  1967. const hDomHostElement = hDom.hostElement || hDom;
  1968. const hDomController = insp(hDom);
  1969. const hData = (hDomController || 0).data || 0;
  1970. const hChannelTitleText = (hData || 0).channelTitleText || 0;
  1971. const runs = ((hChannelTitleText).runs || 0);
  1972. if (getYTextType(hChannelTitleText) === 4 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  1973.  
  1974. const channelTitleTextNew = { runs: [Object.assign({}, runs[0], { text: titleForDisplay })] }
  1975.  
  1976. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: channelTitleTextNew, rSk0e: 1 });
  1977. addCSSRulesIfRequired();
  1978.  
  1979. byPassCheckStore.delete(rchannelNameDOM);
  1980. }
  1981.  
  1982. })
  1983. }
  1984.  
  1985. }
  1986. }
  1987. return browseId
  1988. }
  1989.  
  1990. let firstDOMCheck = false;
  1991. const updateDisplayNameFn = (channelId, newName) => {
  1992. const cached = displayNameResStore.get(channelId);
  1993. if (typeof (cached || 0).title === 'string') {
  1994. cached.title = newName;
  1995. } else if (!cached) {
  1996. displayNameResStore.set(channelId, {
  1997. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1998. externalId: `${channelId}`,
  1999. ownerUrls: [],
  2000. title: newName,
  2001. vanityChannelUrl: null,
  2002. verified123: true
  2003. });
  2004. } else {
  2005. console.warn('unexpected display name cache', cached);
  2006. }
  2007. };
  2008. const firstDOMChecker = isMobile ? () => {
  2009.  
  2010. let playerMicroformatRenderer = null;
  2011. try {
  2012. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  2013. } catch (e) { }
  2014. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  2015. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  2016. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  2017. }
  2018.  
  2019. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  2020. const channelNameCData = !channelNameDOM ? null : insp(channelNameDOM).data;
  2021.  
  2022. if (channelNameCData) {
  2023. let mainChannelUrl = null;
  2024. let mainFormattedNameUrl = null;
  2025. let mainChannelText = null;
  2026. let mainFormattedNameText = null;
  2027. let mainChannelBrowseId = null;
  2028.  
  2029. try {
  2030. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl) // channelUrlUnify("http://www.youtube.com/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2031. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl) // channelUrlUnify("/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  2032. mainChannelText = channelNameCData.channelName
  2033. mainFormattedNameText = channelNameCData.title.runs[0].text
  2034. mainChannelBrowseId = channelNameCData.navigationEndpoint.browseEndpoint.browseId;
  2035. } catch (e) { }
  2036.  
  2037. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2038.  
  2039. const channelId = mainChannelBrowseId;
  2040. if (channelId) {
  2041. if (mainChannelText.startsWith('@')) return;
  2042. if (mainChannelText.trim() !== mainChannelText) return;
  2043. updateDisplayNameFn(channelId, mainChannelText);
  2044. }
  2045.  
  2046.  
  2047. }
  2048. }
  2049.  
  2050. } : () => {
  2051.  
  2052. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  2053. const channelNameCnt = insp(channelNameDOM);
  2054. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  2055. if (channelNameCData) {
  2056. let mainChannelUrl = null;
  2057. let mainFormattedNameUrl = null;
  2058. let mainChannelText = null;
  2059. let mainFormattedNameText = null;
  2060. let mainChannelBrowseId = null;
  2061. try {
  2062. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2063. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  2064. mainChannelText = channelNameCData.channelName.runs[0].text
  2065. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  2066. mainChannelBrowseId = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.browseId;
  2067. } catch (e) { }
  2068.  
  2069. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  2070.  
  2071. const m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.exec(mainChannelUrl);
  2072.  
  2073. if (m && m[1] && mainChannelText !== m[1]) {
  2074.  
  2075. const channelHandle = m[1];
  2076. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  2077. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  2078. }
  2079.  
  2080. } else {
  2081.  
  2082. const channelId = mainChannelBrowseId;
  2083. if (channelId) {
  2084. if (mainChannelText.startsWith('@')) return;
  2085. if (mainChannelText.trim() !== mainChannelText) return;
  2086. updateDisplayNameFn(channelId, mainChannelText);
  2087. }
  2088.  
  2089. }
  2090. }
  2091. }
  2092.  
  2093. };
  2094.  
  2095. // let newAnchorAdded = false;
  2096. /*
  2097.  
  2098. const intersectionobserver = new IntersectionObserver((entries) => {
  2099. let anchorAppear = false;
  2100. for (const entry of entries) {
  2101. if (entry.isIntersecting === true) {
  2102. anchorAppear = true;
  2103. break;
  2104. }
  2105. }
  2106. if (anchorAppear && newAnchorAdded) {
  2107. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  2108. mutex.nextIndex = 0; // higher pirority for new elements being shown
  2109. }
  2110. }, {
  2111. rootMargin:"0px 0px 0px 0px",
  2112. threshold:1
  2113. })
  2114. */
  2115.  
  2116.  
  2117. /* globals WeakRef:false */
  2118.  
  2119. /** @type {(o: Object | null) => WeakRef | null} */
  2120. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  2121.  
  2122. /** @type {(wr: Object | null) => Object | null} */
  2123. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  2124.  
  2125. let doShortsChecking = false;
  2126. let doDescriptionChecking = true;
  2127.  
  2128. let lastNewAnchorLastWR = null;
  2129.  
  2130. const pipelineForDOMMutations = createPipeline();
  2131.  
  2132. const byPassCheckStore = new WeakSet();
  2133.  
  2134. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  2135. for (const mutation of mutations) {
  2136. const target = mutation.target;
  2137. if (!target) continue;
  2138. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  2139. if (!rchannelNameElm) continue;
  2140. const rchannelNameCnt = insp(rchannelNameElm);
  2141. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  2142. const channelId = rchannelNameElm.getAttribute('jkrgy');
  2143. if (channelId) {
  2144. if (byPassCheckStore.has(rchannelNameElm)) continue;
  2145. const object = channelIdToHandle.get(channelId);
  2146. if (object && object.handleText && !object.justPossible) {
  2147. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  2148. if (textDom) {
  2149. let t = textDom.textContent.trim()
  2150. if (t === object.handleText || t === '') {
  2151. rchannelNameElm.removeAttribute('jkrgy');
  2152. // Promise.resolve().then(domChecker);
  2153. }
  2154. }
  2155. }
  2156. }
  2157. }
  2158. });
  2159.  
  2160. let domCheckScheduledForShorts = false;
  2161. const domCheckSelectorForShorts = [
  2162. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  2163. ].join(', ');
  2164.  
  2165.  
  2166. const domCheckerForShorts = async () => {
  2167.  
  2168. if (domCheckScheduledForShorts) return;
  2169. if (document.querySelector(domCheckSelectorForShorts) === null) {
  2170. return;
  2171. }
  2172. domCheckScheduledForShorts = true;
  2173.  
  2174. await pipelineForDOMMutations(async () => {
  2175.  
  2176. domCheckScheduledForShorts = false;
  2177. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  2178.  
  2179. try {
  2180.  
  2181. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  2182. if (nodes.length === 0) {
  2183. return;
  2184. }
  2185.  
  2186. for (const node of nodes) {
  2187.  
  2188. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  2189. if (rchannelNameElm) {
  2190. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  2191. childList: true,
  2192. subtree: true
  2193. });
  2194. byPassCheckStore.add(rchannelNameElm);
  2195. const channelId = checkShortsChannelName(rchannelNameElm);
  2196. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  2197. }
  2198.  
  2199. }
  2200.  
  2201. } catch (e) {
  2202. console.log('error occur', e);
  2203. }
  2204.  
  2205. });
  2206. domCheckScheduledForShorts = false;
  2207.  
  2208. };
  2209.  
  2210. /** @param {Element} s */
  2211. const domCheckerForDescriptionAnchor = (s) => {
  2212.  
  2213. findTextNodes(s, (textNode) => {
  2214. const p = textNode.nodeValue;
  2215. const index = p.indexOf('@');
  2216. if (index < 0) return;
  2217. const q = p.substring(index);
  2218. const b = isDisplayAsHandle(q);
  2219. if (b) {
  2220. const href = s.getAttribute('href')
  2221.  
  2222. const channelId = obtainChannelId(href);
  2223. if (channelId) {
  2224. const h = q.trim();
  2225.  
  2226. if (!firstDOMCheck) {
  2227. firstDOMCheck = true;
  2228. USE_CHANNEL_META && firstDOMChecker();
  2229. }
  2230.  
  2231. if (!channelIdToHandle.has(channelId)) {
  2232. channelIdToHandle.set(channelId, {
  2233. handleText: h,
  2234. justPossible: true
  2235. });
  2236. }
  2237.  
  2238. s.setAttribute('jkrgy', channelId);
  2239. getDisplayName(channelId).then(fetchResult => {
  2240.  
  2241. if (fetchResult === null) return;
  2242.  
  2243. const { title, langTitle, externalId } = fetchResult;
  2244. const titleForDisplay = langTitle || title;
  2245. if (externalId !== channelId) return; // channel id must be the same
  2246.  
  2247. const anchorElement = s;
  2248. const anchorTextNode = textNode;
  2249.  
  2250. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  2251.  
  2252. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  2253.  
  2254. }
  2255.  
  2256. });
  2257. }
  2258. }
  2259. return true;
  2260. });
  2261.  
  2262. }
  2263.  
  2264. // domCheckerForDescription: To be reviewed
  2265. // Example: https://www.youtube.com/watch?v=1NL-sIP9p_U
  2266. const domCheckerForDescription = isMobile ? () => {
  2267. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  2268. 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])')) {
  2269. s.setAttribute('dxcpj', '');
  2270. domCheckerForDescriptionAnchor(s);
  2271. }
  2272. } : () => {
  2273. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  2274. 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])')) {
  2275. s.setAttribute('dxcpj', '');
  2276. domCheckerForDescriptionAnchor(s);
  2277. }
  2278. };
  2279.  
  2280. const domCheckScheduledBools = [];
  2281. const domCheckScheduledSelectors = isMobile ? [
  2282. 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2283. 'a.comment-icon-container[href*="/@"]:not([jkrgy])', // Feb 2024
  2284. 'a.comment-icon-container[href*="channel/"]:not([jkrgy])' // Mar 2024
  2285. ] : [
  2286. 'a[id][href*="channel/"]:not([jkrgy])', // old; Before Feb 2024
  2287. 'a.yt-simple-endpoint.style-scope[id][href^="/@"]:not([jkrgy])' // Feb 2024
  2288. ];
  2289.  
  2290. const newAuthorAnchorsProceed = async (newAnchors) => {
  2291.  
  2292. const cNewAnchorFirst = newAnchors[0]; // non-null
  2293. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  2294. /** @type {HTMLElement | null} */
  2295. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  2296. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  2297.  
  2298. if (!firstDOMCheck) {
  2299. firstDOMCheck = true;
  2300. USE_CHANNEL_META && firstDOMChecker();
  2301. }
  2302.  
  2303. await Promise.resolve();
  2304.  
  2305. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  2306. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  2307. mutex.nextIndex = 0;
  2308. }
  2309. await Promise.resolve();
  2310. }
  2311.  
  2312. // newAnchorAdded = true;
  2313. for (const anchor of newAnchors) {
  2314. const hrefAttribute = anchor.getAttribute('href');
  2315. const hrefV = ytPathnameExtract(hrefAttribute);
  2316. let channelId = '';
  2317. const ytElm = isMobile ? closestYtmData(anchor) : closestYtParent(anchor);
  2318. if (ytElm) {
  2319. const cnt = insp(ytElm);
  2320. const { browseId, canonicalBaseUrl } = getAuthorBrowseEndpoint(cnt) || 0;
  2321.  
  2322. if (browseId && canonicalBaseUrl === hrefV && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId)) {
  2323.  
  2324. const hrefType = getHrefType(hrefV);
  2325. if (hrefType === 1) {
  2326. if (hrefV === `/channel/${browseId}`) {
  2327. let authorText = null;
  2328. if (isMobile) { // mobile only
  2329. authorText = (cnt._commentData || cnt.data || ytElm._commentData || ytElm.data || 0).authorText || 0;
  2330. } else if (!isMobile) {
  2331. authorText = (cnt.data || 0).authorText || 0;
  2332. }
  2333. if (authorText) {
  2334. const text = getYTextContent(authorText);
  2335. if (typeof text === 'string' && text.startsWith('@') && /^@[-_a-zA-Z0-9.]{3,30}$/.test(text)) {
  2336. channelIdToHandle.set(browseId, {
  2337. handleText: `${text}`,
  2338. justPossible: true
  2339. });
  2340. }
  2341. }
  2342. channelId = browseId;
  2343. }
  2344. } else if (hrefType === 2) {
  2345. const handle = hrefV.substring(2);
  2346. channelIdToHandle.set(browseId, {
  2347. handleText: `@${handle}`
  2348. });
  2349. channelId = browseId;
  2350. }
  2351.  
  2352. }
  2353.  
  2354. if (!channelId && hrefV) { // fallback
  2355.  
  2356. // author-text or name
  2357. // normal url: /channel/xxxxxxx
  2358. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  2359.  
  2360. const temp = obtainChannelId(hrefV); // string, can be empty
  2361. if (temp) {
  2362. channelId = temp;
  2363. }
  2364.  
  2365. }
  2366. }
  2367. anchor.setAttribute('jkrgy', channelId);
  2368. if (channelId) {
  2369. domCheckAsync(anchor, hrefAttribute, channelId);
  2370. }
  2371. }
  2372.  
  2373. }
  2374.  
  2375. const closestYtParent = (dom) => {
  2376. while (dom instanceof Element) {
  2377. if (typeof dom.is === 'string' && dom.is) return dom;
  2378. dom = dom.parentNode;
  2379. }
  2380. return null;
  2381. };
  2382. const closestYtmData = (dom) => {
  2383. while (dom instanceof Element) {
  2384. if (typeof (dom._commentData || dom.data || 0) === 'object') return dom;
  2385. dom = dom.parentNode;
  2386. }
  2387. return null;
  2388. };
  2389. const noAuthorDataSet = new Set();
  2390. const getAuthorBrowseEndpoint = (cnt) => {
  2391. let d;
  2392. let haveData = false;
  2393. if (isMobile) {
  2394. const data = ((cnt || 0).data || 0);
  2395. if (data) {
  2396. haveData = true;
  2397. if (d = data.authorEndpoint) return d.browseEndpoint || null;
  2398. }
  2399. } else {
  2400. const __data = ((cnt || 0).__data || 0);
  2401. if (__data) {
  2402. haveData = true;
  2403. if (d = __data.authorTextCommand) return d.browseEndpoint || null; // ytd-comment-renderer
  2404. if (d = __data.authorEndpoint) return d.browseEndpoint || null; // ytd-comment-view-model
  2405. if (d = (__data.data || 0).authorEndpoint) return d.browseEndpoint || null; // ytd-author-comment-badge-renderer
  2406. }
  2407. }
  2408. if (haveData) {
  2409. const tag = cnt.is;
  2410. if (!noAuthorDataSet.has(tag)) {
  2411. noAuthorDataSet.add(tag);
  2412. if (tag === 'ytd-video-description-infocards-section-renderer') {
  2413. return null; // skip console logging
  2414. } else if (tag === 'ytd-thumbnail') {
  2415. return null;
  2416. } else if (tag === 'ytd-structured-description-channel-lockup-renderer') {
  2417. return null;
  2418. } else if (tag === 'ytd-rich-grid-media') {
  2419. return null;
  2420. } else if (tag === 'ytd-rich-metadata-renderer') {
  2421. return null;
  2422. } else if (tag === 'ytd-guide-entry-renderer') {
  2423. return null;
  2424. }
  2425. console.log('no browseEndpoint can be found', tag);
  2426. }
  2427. } else {
  2428. console.log('no browseEndpoint can be found', (cnt || 0).is, 'NO DATA');
  2429. }
  2430. return null;
  2431. };
  2432.  
  2433. const domAuthorNameCheckN = async (kq) => {
  2434. if (domCheckScheduledBools[kq]) return;
  2435. const selector = domCheckScheduledSelectors[kq];
  2436. if (!selector || document.querySelector(selector) === null) return;
  2437. domCheckScheduledBools[kq] = true;
  2438. await pipelineForDOMMutations(async () => {
  2439. domCheckScheduledBools[kq] = false;
  2440. try {
  2441. const newAnchors = document.querySelectorAll(selector);
  2442. if (newAnchors.length === 0) return;
  2443. await newAuthorAnchorsProceed(newAnchors);
  2444. } catch (e) {
  2445. console.log('error occur', e);
  2446. }
  2447. });
  2448. domCheckScheduledBools[kq] = false;
  2449. };
  2450.  
  2451. let _lastAnchorCount = -1;
  2452. const anchorCollection = document.getElementsByTagName('A');
  2453.  
  2454. /*
  2455. const collectionChangeObserverFn = (collection)=>{
  2456. let _len = -1;
  2457. let ws = null;
  2458. ws = new WeakSet(collection);
  2459. return {check: ()=>{
  2460. const lastLen = _len;
  2461. const len = collection.length;
  2462. if(len !== lastLen){
  2463. ws = new WeakSet(collection);
  2464. return true;
  2465. }
  2466. for (const elm of collection) {
  2467. if (!ws.has(elm)){
  2468. ws = new WeakSet(collection);
  2469. return true;
  2470. }
  2471. }
  2472. return false;
  2473. }}
  2474.  
  2475. }
  2476. */
  2477.  
  2478. const domChecker = (mutations) => {
  2479.  
  2480. const currAnchorCount = anchorCollection.length;
  2481. const lastAnchorCount = _lastAnchorCount;
  2482. _lastAnchorCount = currAnchorCount;
  2483. if (currAnchorCount === 0) return;
  2484.  
  2485. if (mutations && lastAnchorCount === currAnchorCount) {
  2486. // test to skip
  2487. let state = 0;
  2488. let addedNonElement = false;
  2489. for (const mutation of mutations) {
  2490. const addedNodes = mutation.addedNodes || 0;
  2491. const removedNodes = mutation.removedNodes || 0;
  2492. const target = mutation.target || 0;
  2493. if (target.nodeName === 'YT-FORMATTED-STRING') continue; // ignore changes in <yt-formatted-string>
  2494. if (addedNodes.length >= 1) {
  2495. state |= 1;
  2496. if (!addedNonElement) {
  2497. for (const addedNode of addedNodes) {
  2498. if (!(addedNode instanceof Element)) {
  2499. addedNonElement = true;
  2500. break;
  2501. }
  2502. }
  2503. }
  2504. if (state & 2) break;
  2505. } else if (removedNodes.length >= 1) {
  2506. state |= 2;
  2507. if (state & 1) break;
  2508. } else {
  2509. state |= 4;
  2510. break;
  2511. }
  2512. }
  2513. if (state === 1) {
  2514. if (!addedNonElement) return; // no change in anchor
  2515. } else if (state === 2) {
  2516. return; // only removal
  2517. } else if (state === 0) {
  2518. return; // no recognized mutation
  2519. }
  2520. }
  2521.  
  2522. doShortsChecking && domCheckerForShorts();
  2523. doDescriptionChecking && domCheckerForDescription();
  2524. for (let i = 0; i < domCheckScheduledSelectors.length; i++) domAuthorNameCheckN(i);
  2525.  
  2526. };
  2527.  
  2528.  
  2529. /** @type {MutationObserver | null} */
  2530. let domObserver = null;
  2531.  
  2532. /** @type {(callback: (event: Event)=>{})} */
  2533. const onPageFetched = isMobile ? (callback) => {
  2534.  
  2535. let state = 0;
  2536.  
  2537. window.addEventListener('state-change', function (evt) {
  2538. if (state === 1) return; // ignore intermediate events
  2539. state = 1; // before value: 0 or 2;
  2540. callback(evt);
  2541. }, false);
  2542.  
  2543. window.addEventListener('state-navigateend', function (evt) { // fallback
  2544. let inSeq = state === 1;
  2545. state = 2; // 2 when loaded
  2546. if (!inSeq) callback(evt);
  2547. }, false);
  2548.  
  2549. } : (callback) => {
  2550.  
  2551. let state = 0;
  2552.  
  2553. document.addEventListener('yt-page-data-fetched', function (evt) {
  2554. if (state === 1) return; // ignore intermediate events if any
  2555. state = 1; // before value: 0 or 2;
  2556. callback(evt);
  2557. }, false);
  2558.  
  2559. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  2560. let inSeq = state === 1;
  2561. state = 2; // 2 when loaded
  2562. if (!inSeq) callback(evt);
  2563. }, false);
  2564.  
  2565. };
  2566.  
  2567.  
  2568. // let mActive = false;
  2569. // let lastContent = '';
  2570. const removeAttrs = () => {
  2571. for (const s of document.querySelectorAll('a[href][dxcpj]')) {
  2572. s.removeAttribute('dxcpj');
  2573. }
  2574. for (const s of document.querySelectorAll('a[href][jkrgy]')) {
  2575. s.removeAttribute('jkrgy');
  2576. }
  2577. }
  2578.  
  2579. // setInterval(() => {
  2580. // if (!mActive) return;
  2581. // let content = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  2582. // if (content !== lastContent) {
  2583. // lastContent = content;
  2584. // removeAttrs();
  2585. // }
  2586. // }, 400);
  2587.  
  2588. /**
  2589. *
  2590. * @param {Node} app
  2591. * @returns
  2592. */
  2593. function setupOnPageFetched(app) {
  2594.  
  2595. firstDOMCheck = false;
  2596.  
  2597. if (!cfg['INNERTUBE_API_KEY']) {
  2598. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  2599. return;
  2600. }
  2601.  
  2602. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  2603. doShortsChecking = true;
  2604. } else {
  2605. doShortsChecking = false;
  2606. }
  2607.  
  2608. _lastAnchorCount = -1;
  2609.  
  2610. if (!domObserver) {
  2611. domObserver = new MutationObserver(domChecker);
  2612. } else {
  2613. domObserver.takeRecords();
  2614. domObserver.disconnect();
  2615. }
  2616.  
  2617. // lastContent = (document.querySelector('ytd-comments-header-renderer #title') || 0).textContent || '';
  2618. // mActive = true;
  2619. removeAttrs();
  2620.  
  2621. domObserver.observe(app, { childList: true, subtree: true, attributes: true, attributeFilter: ['jkrgy', 'href', 'dxcpj'] });
  2622. domChecker();
  2623.  
  2624. }
  2625.  
  2626. /**
  2627. *
  2628. * @param {Object|null} dest
  2629. * @param {Object} ytcfg
  2630. * @param {string[]} keys
  2631. * @returns
  2632. */
  2633. function getYtConfig(dest, ytcfg, keys) {
  2634. dest = dest || {};
  2635. if (typeof ytcfg.get === 'function') { // mobile
  2636. for (const key of keys) {
  2637. dest[key] = ytcfg.get(key);
  2638. }
  2639. } else {
  2640. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  2641. for (const key of keys) {
  2642. dest[key] = cfgData[key];
  2643. }
  2644. }
  2645. return dest;
  2646. }
  2647.  
  2648. /** @type { (evt: Object) => Element | null } */
  2649. const getPageApp = isMobile
  2650. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  2651. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  2652.  
  2653. onPageFetched(async (evt) => {
  2654. const app = getPageApp(evt);
  2655. console.assert(app);
  2656. const ytcfg = ((window || 0).ytcfg || 0);
  2657. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  2658. setupOnPageFetched(app);
  2659. });
  2660.  
  2661. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });

QingJ © 2025

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