Restore YouTube Username from Handle to Custom

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

当前为 2023-08-12 提交的版本,查看 最新版本

  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.9.1
  30. // @license MIT License
  31.  
  32. // @author CY Fung
  33. // @match https://www.youtube.com/*
  34. // @match https://m.youtube.com/*
  35. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  36. // @icon https://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+=.]+
  144. */
  145.  
  146. /**
  147. @typedef {string} DisplayName
  148. * Display Name
  149. */
  150.  
  151. /**
  152. @typedef DisplayNameResultObject
  153. @type {Object}
  154. @property {DisplayName} title
  155. @property {DisplayName} langTitle
  156. @property {ChannelId?} externalId
  157. @property {string[]} ownerUrls
  158. @property {string} channelUrl
  159. @property {string} vanityChannelUrl
  160. @property {boolean|undefined} verified123
  161. */
  162.  
  163. /**
  164. @typedef ChannelIdToHandleResult
  165. @type {Object}
  166. @property {HandleText} handleText
  167. @property {boolean} justPossible
  168. */
  169.  
  170. (function (__CONTEXT__) {
  171. 'use strict';
  172.  
  173. const USE_RSS_FETCHER = true;
  174. const USE_TIMEOUT_SIGNAL = false;
  175. const USE_CHANNEL_META = true;
  176. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  177. const USE_LANG_SPECIFIC_NAME = true;
  178. const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
  179.  
  180. /** @type {globalThis.PromiseConstructor} */
  181. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  182.  
  183. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  184.  
  185. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  186. let controller = new AbortController();
  187. const r = controller.signal;
  188. let cid = setTimeout(() => {
  189. if (cid >= 1) {
  190. cid = 0;
  191. controller && controller.abort();
  192. controller = null;
  193. }
  194. }, timeout);
  195. r.clearTimeout = () => {
  196. if (cid >= 1) {
  197. clearTimeout(cid);
  198. cid = 0;
  199. }
  200. }
  201. return r;
  202. } : () => { };
  203.  
  204. const fxOperator = (proto, propertyName) => {
  205. let propertyDescriptorGetter = null;
  206. try {
  207. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  208. // https://github.com/cyfung1031/userscript-supports/issues/9
  209. // .parentNode becomes DocumentFragment
  210. /**
  211. *
  212. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  213. *
  214. * e.g. ytd-comment-renderer#comment > div#body
  215. *
  216. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  217. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  218. *
  219. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  220. *
  221. * Alternative way: ytCustomElement.$.xxxxxxx
  222. *
  223. */
  224. } catch (e) { }
  225. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  226. };
  227.  
  228. const fxAPI = (proto, propertyName) => {
  229. const methodFunc = proto[propertyName];
  230. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  231. };
  232.  
  233. /** @type { (node: Node)=>Node | null } */
  234. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  235. /** @type { (node: Node)=>Node | null } */
  236. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  237. /** @type { (node: Node)=>Node | null } */
  238. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  239.  
  240. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  241. const elementQS = fxAPI(Element.prototype, 'querySelector');
  242. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  243. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  244.  
  245. /*
  246. init
  247. initialdata
  248. state-progress
  249. state-responsereceived
  250. player-autonav-pause
  251. state-change
  252. state-navigateend
  253. player-initialized
  254. renderer-module-load-start
  255. video-data-change
  256. player-state-change
  257. updateui
  258. renderer-module-load-end -> channel owner DOM available
  259. player-autonav-pause
  260. updateui
  261. renderer-module-load-start
  262. updateui
  263. renderer-module-load-end
  264. playing
  265. h5player.video-progress
  266. h5player.video-progress
  267. h5player.video-progress
  268. h5player.video-progress
  269. ...
  270. navigate new video
  271. state-navigatestart
  272. state-change => channel owener DOM vanished
  273. state-progress
  274. ...
  275. h5player.player-state-change
  276. h5player.video-data-change
  277. h5player.player-state-change
  278. h5player.muted-autoplay-change
  279. h5player.volume-change
  280. h5player.video-data-change
  281. h5player.volume-change
  282. ...
  283. state-progress
  284. ...
  285. state-progress => channel owner DOM appear [just before state-responsereceived]
  286. state-responsereceived
  287. video-data-change
  288. state-change
  289. state-navigateend
  290. UX interaction
  291. user-activity
  292. player-autonav-pause
  293. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  294. EventTarget.prototype.dispatchEvent = function (ev) {
  295. if (ev instanceof Event) {
  296. if (ev.type === 'video-progress') { } else {
  297. console.log(ev.type, this, ev.target)
  298. if (ev.target === null) {
  299. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  300. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  301. }
  302. }
  303. }
  304. return this.uhfsE.apply(this, arguments);
  305. }
  306. */
  307.  
  308. const isMobile = location.hostname === 'm.youtube.com';
  309.  
  310. const cfg = {};
  311. class Mutex {
  312.  
  313. constructor() {
  314. this.p = Promise.resolve()
  315. }
  316.  
  317. /**
  318. * @param {(lockResolve: () => void)} f
  319. */
  320. lockWith(f) {
  321. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  322. }
  323.  
  324. }
  325.  
  326. class OrderedMutex extends Mutex {
  327. constructor() {
  328. super();
  329. this.nextIndex = 0;
  330. this.arr = [];
  331. this.lockFunc = resolve => {
  332. if (this.arr.length >= 1) {
  333. let f = this.arr[0];
  334. if (typeof f === 'function') {
  335. this.arr.shift();
  336. if (this.nextIndex > 0) this.nextIndex--;
  337. f(resolve);
  338. return;
  339. } else {
  340. // reset if unknown error
  341. this.arr.length = 0;
  342. this.nextIndex = 0;
  343. }
  344. }
  345. resolve();
  346. };
  347. }
  348. /**
  349. * @param {(lockResolve: () => void)} f
  350. */
  351. add(f) {
  352. if (this.nextIndex === this.arr.length) {
  353. this.arr.push(f); this.nextIndex++;
  354. } else {
  355. this.arr.splice(this.nextIndex++, 0, f);
  356. }
  357. this.lockWith(this.lockFunc);
  358. }
  359. }
  360. // usage: run network request one by one
  361. const mutex = new OrderedMutex();
  362.  
  363. /**
  364. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  365. * @template T */
  366.  
  367. /**
  368. * usage: cache the network result per web application instance.
  369. * @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  370. const displayNameResStore = new Map();
  371.  
  372. /**
  373. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  374. * @type {WeakMap<Function, Function>} */
  375. const dataChangedFuncStore = new WeakMap();
  376.  
  377. /**
  378. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  379. * @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
  380. const handleToChannelId = new Map();
  381.  
  382. /**
  383. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  384. * @type {Map<ChannelId, ChannelIdToHandleResult>} */
  385. const channelIdToHandle = new Map();
  386.  
  387. /**
  388. * usage: replace handle to lang-specific display name
  389. * @type {Map<HandleText, DisplayName>} */
  390. const langPreferredDisplayNameMap = new Map();
  391.  
  392. /**
  393. * AsyncValue
  394. * @class
  395. * @template T
  396. */
  397. class AsyncValue {
  398. constructor() {
  399. /** @type {T | null} */
  400. this.__value__ = null;
  401. /** @type {((value: any)=>void) | null} */
  402. this.__resolve__ = null;
  403. this.__promise__ = new Promise(resolve => {
  404. this.__resolve__ = resolve;
  405. });
  406. }
  407. /**
  408. *
  409. * @param {T} value
  410. */
  411. setValue(value) {
  412. const promise = this.__promise__;
  413. if (promise === null) throw 'Value has already been set.';
  414. this.__value__ = value;
  415. this.__promise__ = null;
  416. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  417. }
  418. /**
  419. *
  420. * @returns {Promise<T>}
  421. */
  422. async getValue() {
  423. const promise = this.__promise__;
  424. if (promise === null) return this.__value__;
  425. await promise; // promise become null
  426. this.__promise__ = null; // just in case
  427. this.__resolve__ = null;
  428. return this.__value__;
  429. }
  430. }
  431.  
  432. /**
  433. *
  434. * @param {DisplayNameResultObject} resultInfo
  435. * @param {string} channelId
  436. */
  437. const cacheHandleToChannel = (resultInfo, channelId) => {
  438.  
  439. const { vanityChannelUrl, ownerUrls } = resultInfo;
  440.  
  441. let handleText = urlToHandle(vanityChannelUrl || '');
  442.  
  443. if (handleText) {
  444. // match = true;
  445. } else if ((ownerUrls || 0).length >= 1) {
  446. for (const ownerUrl of ownerUrls) {
  447. handleText = urlToHandle(ownerUrl || '');
  448.  
  449. if (handleText) {
  450. // match = true;
  451. break;
  452. }
  453. }
  454. }
  455. if (handleText) {
  456.  
  457. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  458. if (asyncValue instanceof AsyncValue) {
  459. asyncValue.setValue(channelId);
  460. }
  461. handleToChannelId.set(handleText, channelId);
  462. }
  463.  
  464.  
  465. }
  466.  
  467. /**
  468. *
  469. * @param {string} channelId
  470. * @param {Function} onDownloaded
  471. * @param {Function} onResulted
  472. * @param {Function} onError
  473. */
  474. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  475.  
  476. let signal = timeoutSignal(4000);
  477.  
  478. const requestBody = {
  479. "context": {
  480. "client": {
  481. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  482. "clientName": "MWEB", // "WEB", "MWEB"
  483. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  484. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  485. "playerType": "UNIPLAYER",
  486. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  487. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  488. "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",
  489. "mainAppWebInfo": {
  490. "graftUrl": `/channel/${channelId}`,
  491. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  492. "isWebNativeShareAvailable": true
  493. }
  494. },
  495. "user": {
  496. "lockedSafetyMode": false
  497. },
  498. "request": {
  499. "useSsl": true,
  500. "internalExperimentFlags": [],
  501. "consistencyTokenJars": []
  502. }
  503. },
  504. "browseId": `${channelId}`
  505. };
  506.  
  507. if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
  508. Object.assign(requestBody.context.client, {
  509. "hl": cfg.HL,
  510. "gl": cfg.GL,
  511. });
  512. }
  513.  
  514. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  515. "method": "POST",
  516. "mode": "same-origin",
  517. "credentials": "omit",
  518.  
  519. referrerPolicy: "no-referrer",
  520. cache: "default", // no effect on POST request
  521. // cache: "force-cache",
  522. redirect: "error", // there shall be no redirection in this API request
  523. integrity: "",
  524. keepalive: false,
  525. signal,
  526.  
  527. "headers": {
  528. "Content-Type": "application/json", // content type of the body data in POST request
  529. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  530. // X-Youtube-Bootstrap-Logged-In: false,
  531. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  532. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  533.  
  534. "Accept": "application/json",
  535. },
  536. "body": JSON.stringify(requestBody)
  537. })).then(res => {
  538. signal && signal.clearTimeout && signal.clearTimeout();
  539. signal = null;
  540. onDownloaded();
  541. onDownloaded = null;
  542. return res.json();
  543. }).then(resJson => {
  544. let resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  545. let title = resultInfo.title;
  546. if (title) {
  547.  
  548. resultInfo.title = '';
  549. resultInfo.langTitle = title;
  550.  
  551. if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
  552. let matched = false;
  553.  
  554. if (cfg.ownerProfileUrl.endsWith(`/channel/${channelId}`)) matched = true;
  555. else {
  556.  
  557. for (const ownerUrl of resultInfo.ownerUrls) {
  558. if (ownerUrl.endsWith(cfg.ownerProfileUrl)) {
  559. matched = true;
  560. break;
  561. }
  562. }
  563.  
  564.  
  565. }
  566.  
  567.  
  568. if (matched) {
  569. resultInfo.title = cfg.ownerChannelName;
  570. }
  571. }
  572.  
  573. }
  574.  
  575. onResulted(resultInfo);
  576. onResulted = null;
  577. }).catch(onError);
  578.  
  579. };
  580.  
  581. /**
  582. *
  583. * @param {string} channelId
  584. * @param {Function} onDownloaded
  585. * @param {Function} onResulted
  586. * @param {Function} onError
  587. */
  588. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  589.  
  590. let signal = timeoutSignal(4000);
  591. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  592. // YouTube RSS Response - public, max-age=900
  593.  
  594. "method": "GET",
  595. "mode": "same-origin",
  596. "credentials": "omit",
  597.  
  598. referrerPolicy: "no-referrer",
  599. cache: "default",
  600. // cache: "no-cache",
  601. redirect: "error", // there shall be no redirection in this API request
  602. integrity: "",
  603. keepalive: false,
  604. signal,
  605.  
  606. "headers": {
  607. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  608. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  609. // seems YouTube RSS Feeds server insists its own Cache-Control.
  610.  
  611. // "Content-Type": "text/xml; charset=UTF-8",
  612. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  613. // X-Youtube-Bootstrap-Logged-In: false,
  614. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  615. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  616.  
  617. "Accept": "text/xml",
  618. }
  619. }).then(res => {
  620. signal && signal.clearTimeout && signal.clearTimeout();
  621. signal = null;
  622. onDownloaded();
  623. onDownloaded = null;
  624. return res.text();
  625. }).then(resText => {
  626. let eIdx = resText.indexOf('<entry>');
  627. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  628.  
  629. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  630. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  631. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  632. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  633.  
  634.  
  635. let name, uri, mt;
  636.  
  637. // ===============================================================
  638.  
  639. /* removed in 2023.06.30 */
  640.  
  641.  
  642. // ===============================================================
  643.  
  644.  
  645. const wIdx1 = mText.indexOf('<author>');
  646. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  647.  
  648. if (wIdx1 > 0 && wIdx2 > 0) {
  649. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  650. const template = document.createElement('template');
  651. template.innerHTML = qText;
  652. /** @type {HTMLElement | null} */
  653. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  654. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  655. const nodeName = authorChild.nodeName;
  656. if (nodeName === 'NAME') name = authorChild.textContent;
  657. else if (nodeName === 'URI') {
  658. uri = authorChild.textContent;
  659. mt = obtainChannelId(uri);
  660. }
  661. }
  662. template.innerHTML = '';
  663. }
  664.  
  665. if (!name && !uri) {
  666.  
  667. // fallback
  668.  
  669. const parser = new DOMParser();
  670. const xmlDoc = parser.parseFromString(mText, "text/xml");
  671.  
  672. // const author = xmlDoc.querySelector("author");
  673.  
  674. // https://extendsclass.com/xpath-tester.html
  675.  
  676. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  677.  
  678. let authorChild;
  679. while ((authorChild = authorChilds.iterateNext()) !== null) {
  680. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  681. else if (authorChild.nodeName === 'uri') {
  682. uri = authorChild.textContent;
  683. mt = obtainChannelId(uri)
  684. }
  685. }
  686.  
  687. try {
  688. xmlDoc.firstChild.remove();
  689. } catch (e) { }
  690.  
  691. }
  692.  
  693.  
  694.  
  695.  
  696. let res = null;
  697.  
  698. if (name && uri && mt && mt === channelId) {
  699.  
  700.  
  701. let object = channelIdToHandle.get(mt);
  702.  
  703. if (object) {
  704.  
  705. const handleText = object.handleText;
  706.  
  707. if (handleText === name) channelIdToHandle.delete(mt);
  708. else {
  709. object.justPossible = false; // ignore @handle checking
  710.  
  711. res = {
  712. "title": name,
  713. "externalId": mt,
  714. "ownerUrls": [
  715. `http://www.youtube.com/${handleText}`
  716. ],
  717. "channelUrl": uri,
  718. "vanityChannelUrl": `http://www.youtube.com/${handleText}`
  719. };
  720.  
  721. if (USE_LANG_SPECIFIC_NAME) {
  722. const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
  723. if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
  724. }
  725.  
  726. }
  727. }
  728. }
  729.  
  730. onResulted(res);
  731. onResulted = null;
  732.  
  733. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  734. // onResulted(resultInfo);
  735. }).catch(onError);
  736.  
  737.  
  738.  
  739. }
  740.  
  741. /**
  742. *
  743. * @param {string} channelId
  744. */
  745. function stackNewRequest(channelId) {
  746.  
  747. mutex.add(lockResolve => {
  748.  
  749. let bResult = displayNameResStore.get(channelId);
  750. if (!(bResult instanceof AsyncValue)) {
  751. // resolved or removed
  752. lockResolve(); lockResolve = null;
  753. return;
  754. }
  755.  
  756. let setResult = (result) => {
  757. setResult = null;
  758. if (!result) {
  759. bResult.fetchingState = 0;
  760. bResult.setValue(null);
  761. displayNameResStore.delete(channelId); // create another network response in the next request
  762. } else {
  763. bResult.fetchingState = 4;
  764. bResult.setValue(result);
  765. displayNameResStore.set(channelId, result); // update store result to resolved value
  766. }
  767. bResult = null;
  768. }
  769.  
  770. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  771. // request is already done. no need to stack any request
  772. lockResolve(); lockResolve = null;
  773. return;
  774. }
  775.  
  776. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  777. // element has already been removed
  778. lockResolve(); lockResolve = null;
  779. setResult(null);
  780. return;
  781. }
  782.  
  783. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  784.  
  785. bResult.fetchingState = 2;
  786.  
  787.  
  788. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  789. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  790. const fetcher = USE_RSS_FETCHER && fetcherRSS && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  791. fetcher(channelId, () => {
  792. bResult.fetchingState = 3;
  793. lockResolve();
  794. lockResolve = null;
  795. }, resultInfo => {
  796.  
  797. if (!resultInfo) {
  798. // invalid json format
  799. setResult(null);
  800. return;
  801. }
  802.  
  803. cacheHandleToChannel(resultInfo, channelId);
  804.  
  805. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  806.  
  807. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  808.  
  809. setResult(displayNameRes);
  810. }, e => {
  811. lockResolve && lockResolve();
  812. lockResolve = null;
  813. console.warn(e);
  814. setResult && setResult(null);
  815. });
  816.  
  817. });
  818.  
  819. }
  820.  
  821. /**
  822. *
  823. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  824. * @returns Example: _\@yr__kd_
  825. */
  826. function urlToHandle(url) {
  827.  
  828. if (typeof url !== 'string') return '';
  829. let i = url.indexOf('.youtube.com/');
  830. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  831. else if (url.charAt(0) === '/') url = url.substring(1);
  832. return isDisplayAsHandle(url) ? url : '';
  833.  
  834. }
  835.  
  836. /**
  837. *
  838. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  839. * @returns {Promise<DisplayNameResultObject | null>}
  840. */
  841. async function getDisplayName(channelId) {
  842.  
  843. let cache = displayNameResStore.get(channelId);
  844. let isStackNewRequest = false;
  845.  
  846. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  847. let aResult;
  848.  
  849. if (cache instanceof AsyncValue) {
  850. aResult = cache;
  851. if (aResult.fetchingState >= 2) {
  852. // aResult.fetchingState
  853. // 2: network fetch started
  854. // 3: network fetch ended
  855. // isStackNewRequest = false;
  856. } else {
  857. // 0: invalid before
  858. // 1: scheduled but not yet fetch
  859. isStackNewRequest = true;
  860. }
  861. } else if (cache) {
  862. // resolved result
  863. return cache;
  864. } else {
  865. // else no cached value found
  866. /** @type {AsyncValue<DisplayNameResultObject>} */
  867. aResult = new AsyncValue();
  868. displayNameResStore.set(channelId, aResult);
  869. isStackNewRequest = true;
  870. }
  871.  
  872. if (isStackNewRequest) {
  873. aResult.fetchingState = 1;
  874. stackNewRequest(channelId);
  875. }
  876. return await aResult.getValue();
  877. }
  878.  
  879.  
  880. /**
  881. *
  882. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  883. * @returns
  884. */
  885. const obtainChannelId = (href) => {
  886. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  887. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  888. return !m ? '' : (m[1] || '');
  889. };
  890.  
  891.  
  892. /**
  893. *
  894. * @param {Element} ytElm
  895. */
  896. const resetWhenDataChanged = (ths) => {
  897. const cnt = ths.inst || ths || 0;
  898. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  899. if (ytElm instanceof Element) {
  900. const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  901. if ((anchors || 0).length >= 1 && ((ytElm.inst || ytElm).data || 0).jkrgx !== 1) {
  902. for (const anchor of anchors) {
  903. anchor.removeAttribute('jkrgy');
  904. }
  905. }
  906. }
  907. }
  908.  
  909. /**
  910. *
  911. * @param {Function} dataChanged original dataChanged function
  912. * @returns new dataChanged function
  913. */
  914. const dataChangeFuncProducer = (dataChanged) => {
  915. /** @this HTMLElement */
  916. return function () {
  917. resetWhenDataChanged(this);
  918. return dataChanged.apply(this, arguments);
  919. }
  920. };
  921.  
  922. /**
  923. *
  924. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  925. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  926. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  927. * @returns
  928. */
  929. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  930.  
  931. let currentHref = anchor.getAttribute('href');
  932. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  933.  
  934. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  935.  
  936. };
  937.  
  938. /**
  939. *
  940. * @param {string} currentDisplayed
  941. * @param {DisplayNameResultObject} fetchResult
  942. * @returns
  943. */
  944. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  945.  
  946. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  947.  
  948. const currentDisplayTrimmed = currentDisplayed.trim();
  949. let match = false;
  950. if (verified123) {
  951. match = true;
  952. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  953. match = true;
  954. } else if ((ownerUrls || 0).length >= 1) {
  955. for (const ownerUrl of ownerUrls) {
  956. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  957. match = true;
  958. break;
  959. }
  960. }
  961. }
  962. if (match) {
  963. return currentDisplayTrimmed;
  964. }
  965. return '';
  966.  
  967. };
  968.  
  969. /**
  970. *
  971. *
  972. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  973. - Is between 3-30 characters
  974. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  975. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  976. - Is not URL-like or phone number-like
  977. - Is not already being used
  978. - Follows YouTube's Community Guidelines
  979. ### Handle automatically generated by YouTube
  980. - `@user-XXXX`
  981. - without dot (.)
  982. *
  983. * @param {string} text
  984. * @returns
  985. */
  986. const isDisplayAsHandle = (text) => {
  987.  
  988. if (typeof text !== 'string') return false;
  989. if (text.length < 4) return false;
  990. if (text.indexOf('@') < 0) return false;
  991. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  992.  
  993. };
  994.  
  995. /**
  996. *
  997. * @param {Object[]} contentTexts
  998. * @param {number} idx
  999. * @returns
  1000. */
  1001. const contentTextProcess = (contentTexts, idx) => {
  1002. const contentText = contentTexts[idx];
  1003. const text = (contentText || 0).text;
  1004. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  1005. if (typeof url === 'string' && typeof text === 'string') {
  1006.  
  1007. if (!isDisplayAsHandle(text)) return null;
  1008. const channelId = obtainChannelId(url);
  1009.  
  1010. return getDisplayName(channelId).then(fetchResult => {
  1011. let resolveResult = null;
  1012. if (fetchResult) {
  1013. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1014.  
  1015. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1016. if (textTrimmed) {
  1017. resolveResult = (md) => {
  1018. let runs = ((md || 0).contentText || 0).runs;
  1019. if (!runs || !runs[idx]) return;
  1020. if (runs[idx].text !== text) return;
  1021. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1022. md.contentText = Object.assign({}, md.contentText);
  1023. };
  1024. }
  1025. }
  1026. return resolveResult; // function as a Promise
  1027. });
  1028. }
  1029.  
  1030. return null;
  1031. };
  1032.  
  1033. /**
  1034. *
  1035. * @param {ParentNode} parentNode
  1036. * @param {Function} callback
  1037. */
  1038. function findTextNodes(parentNode, callback) {
  1039. /**
  1040. *
  1041. * @param {Node} node
  1042. * @returns
  1043. */
  1044. function traverse(node) {
  1045. if (node.nodeType === Node.TEXT_NODE) {
  1046. let r = callback(node);
  1047. if (r === true) return true;
  1048. }
  1049.  
  1050. let childNode = nodeFirstChild(node);
  1051. while (childNode) {
  1052. let r = traverse(childNode);
  1053. if (r === true) return true;
  1054. childNode = nodeNextSibling(childNode);
  1055. }
  1056. }
  1057.  
  1058. traverse(parentNode);
  1059. }
  1060.  
  1061. function updatePinnedCommentBadge(md, title, langTitle) {
  1062.  
  1063.  
  1064. let setPinnedCommentBadge = false;
  1065. if (((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0).length === 2) {
  1066. setPinnedCommentBadge = true;
  1067. }
  1068. if (setPinnedCommentBadge) {
  1069. let idx = 0;
  1070. let jdx = -1;
  1071. for (const textRun of md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs) {
  1072. if (textRun.text === title) {
  1073. jdx = idx;
  1074. break;
  1075. }
  1076. idx++;
  1077. }
  1078. if (jdx >= 0) {
  1079. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  1080. runs[jdx] = Object.assign({}, runs[jdx], { text: langTitle });
  1081. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  1082. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  1083. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  1084. }
  1085. }
  1086.  
  1087. }
  1088.  
  1089. /**
  1090. *
  1091. * @param {ParentNode} parentNode
  1092. * @param {Object[]} contentTexts
  1093. * @param {number} aidx
  1094. * @returns
  1095. */
  1096. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  1097.  
  1098.  
  1099. let commentText = elementQS(parentNode, '.comment-text');
  1100. if (!commentText) return;
  1101. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  1102. let currentText = commentText.textContent;
  1103. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1104. if (!textMatch) return;
  1105.  
  1106. const contentText = contentTexts[aidx];
  1107.  
  1108. /** @type {string} */
  1109. const handleText = contentText.text.trim();
  1110. /** @type {string | null | undefined} */
  1111. let channelId;
  1112.  
  1113. let cache = handleToChannelId.get(handleText);
  1114.  
  1115. if (typeof cache === 'string') {
  1116. channelId = cache;
  1117. } else if (cache instanceof AsyncValue) {
  1118. channelId = await cache.getValue();
  1119. } else {
  1120. /** @type {AsyncValue<string>} */
  1121. const asyncValue = new AsyncValue();
  1122. handleToChannelId.set(handleText, asyncValue);
  1123. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1124. }
  1125.  
  1126. if (!channelId) return; // just in case
  1127.  
  1128. if (commentText.isConnected !== true) return; // already removed
  1129. if (commentText.textContent !== currentText) return; // already changed
  1130.  
  1131. const fetchResult = await getDisplayName(channelId);
  1132.  
  1133. if (fetchResult === null) return;
  1134.  
  1135. const { title, langTitle, externalId } = fetchResult;
  1136. const titleForDisplay = langTitle || title;
  1137. if (externalId !== channelId) return; // channel id must be the same
  1138.  
  1139. if (commentText.isConnected !== true) return; // already removed
  1140. if (commentText.textContent !== currentText) return; // already changed
  1141.  
  1142. let search = contentText.text;
  1143. if (typeof search === 'string') {
  1144.  
  1145. const searchTrimmed = search.trim();
  1146. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1147. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  1148.  
  1149. findTextNodes(commentText, (textnode) => {
  1150. if (textnode.nodeValue.indexOf(search) >= 0) {
  1151. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1152. return true;
  1153. }
  1154. });
  1155. }
  1156.  
  1157. }
  1158.  
  1159. }
  1160.  
  1161. /**
  1162. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1163. * @type { (anchor: HTMLElement, channelHref: string?, mt: string?) => Promise<void> }
  1164. */
  1165. const domCheckAsync = isMobile ? async (anchor, channelHref, mt) => {
  1166.  
  1167. try {
  1168. if (!channelHref || !mt) return;
  1169. let parentNode = nodeParent(anchor);
  1170. while (parentNode instanceof Node) {
  1171. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1172. parentNode = nodeParent(parentNode);
  1173. }
  1174. if (parentNode instanceof Node) { } else return;
  1175.  
  1176. let displayTextDOM = elementQS(parentNode, '.comment-header .comment-title');
  1177. if (!displayTextDOM) return;
  1178. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1179. let airaLabel = anchor.getAttribute('aria-label')
  1180. const parentNodeData = (parentNode.inst || parentNode).data;
  1181. let runs = ((parentNodeData || 0).authorText || 0).runs;
  1182.  
  1183. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  1184.  
  1185. if (!channelIdToHandle.has(mt)) {
  1186. channelIdToHandle.set(mt, {
  1187. handleText: airaLabel.trim(),
  1188. justPossible: true
  1189. });
  1190. }
  1191.  
  1192. const fetchResult = await getDisplayName(mt);
  1193.  
  1194. if (fetchResult === null) return;
  1195.  
  1196. const { title, langTitle, externalId } = fetchResult;
  1197. const titleForDisplay = langTitle || title;
  1198. if (externalId !== mt) return; // channel id must be the same
  1199.  
  1200. // anchor href might be changed by external
  1201. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1202.  
  1203. if (displayTextDOM.isConnected !== true) return; // already removed
  1204.  
  1205. let found = false;
  1206.  
  1207. findTextNodes(displayTextDOM, (textnode) => {
  1208. if (textnode.nodeValue === airaLabel) {
  1209. textnode.nodeValue = titleForDisplay;
  1210. found = true;
  1211. return true;
  1212. }
  1213. });
  1214.  
  1215. if (!found) return;
  1216. anchor.setAttribute('aria-label', titleForDisplay);
  1217. runs[0].text = titleForDisplay;
  1218.  
  1219. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  1220. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  1221. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  1222. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  1223. const tc = spanText ? spanText.textContent : '';
  1224. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  1225. if (tc && tc === spanText.textContent) {
  1226. let idx = tc.indexOf(title);
  1227. if (idx >= 0) {
  1228. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  1229. }
  1230. }
  1231. }
  1232.  
  1233. const contentTexts = (parentNodeData.contentText || 0).runs;
  1234. if (contentTexts && contentTexts.length >= 2) {
  1235. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1236. const contentText = contentTexts[aidx] || 0;
  1237. if (contentText.italics !== true) {
  1238. let isHandle = isDisplayAsHandle(contentText.text);
  1239. if (isHandle) {
  1240. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1241. }
  1242. }
  1243. }
  1244. }
  1245.  
  1246. }
  1247. } catch (e) {
  1248. console.warn(e);
  1249. }
  1250.  
  1251. } : async (anchor, channelHref, mt) => {
  1252.  
  1253. try {
  1254. if (!channelHref || !mt) return;
  1255. let parentNode = nodeParent(anchor);
  1256. while (parentNode instanceof Node) {
  1257. const cnt = parentNode.inst || parentNode;
  1258. if (typeof cnt.is === 'string' && typeof cnt.dataChanged === 'function') break;
  1259. parentNode = nodeParent(parentNode);
  1260. }
  1261. if (parentNode instanceof Node) { } else return;
  1262. const parentNodeController = parentNode.inst || parentNode;
  1263. const authorText = (parentNodeController.data || 0).authorText;
  1264. const currentDisplayed = (authorText || 0).simpleText;
  1265. if (typeof currentDisplayed !== 'string') return;
  1266. if (!isDisplayAsHandle(currentDisplayed)) return;
  1267.  
  1268. if (!channelIdToHandle.has(mt)) {
  1269. channelIdToHandle.set(mt, {
  1270. handleText: currentDisplayed.trim(),
  1271. justPossible: true
  1272. });
  1273. }
  1274.  
  1275. let oldDataChangedFn = parentNodeController.dataChanged;
  1276. if (typeof oldDataChangedFn === 'function' && !oldDataChangedFn.jkrgx) {
  1277. let newDataChangedFn = dataChangedFuncStore.get(oldDataChangedFn);
  1278. if (!newDataChangedFn) {
  1279. newDataChangedFn = dataChangeFuncProducer(oldDataChangedFn);
  1280. newDataChangedFn.jkrgx = 1;
  1281. dataChangedFuncStore.set(oldDataChangedFn, newDataChangedFn);
  1282. }
  1283. parentNodeController.dataChanged = newDataChangedFn;
  1284. }
  1285.  
  1286. oldDataChangedFn = parentNodeController.hostElement.dataChanged;
  1287. if (typeof oldDataChangedFn === 'function' && !oldDataChangedFn.jkrgx) {
  1288. let newDataChangedFn = dataChangedFuncStore.get(oldDataChangedFn);
  1289. if (!newDataChangedFn) {
  1290. newDataChangedFn = dataChangeFuncProducer(oldDataChangedFn);
  1291. newDataChangedFn.jkrgx = 1;
  1292. dataChangedFuncStore.set(oldDataChangedFn, newDataChangedFn);
  1293. }
  1294. parentNodeController.hostElement.dataChanged = newDataChangedFn;
  1295. }
  1296.  
  1297. const fetchResult = await getDisplayName(mt);
  1298.  
  1299. if (fetchResult === null) return;
  1300.  
  1301. const { title, langTitle, externalId } = fetchResult;
  1302. const titleForDisplay = langTitle || title;
  1303. if (externalId !== mt) return; // channel id must be the same
  1304.  
  1305. // anchor href might be changed by external
  1306. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1307.  
  1308. const parentNodeData = parentNodeController.data;
  1309. const funcPromises = [];
  1310.  
  1311. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1312.  
  1313. if (authorText.simpleText !== currentDisplayed) return;
  1314. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1315. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  1316. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  1317.  
  1318. // the inside hyperlinks will be only converted if its parent author name is handle
  1319. const contentTexts = (parentNodeData.contentText || 0).runs;
  1320. if (contentTexts && contentTexts.length >= 1) {
  1321. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1322. const r = contentTextProcess(contentTexts, aidx);
  1323. if (r instanceof Promise) funcPromises.push(r);
  1324. }
  1325. }
  1326.  
  1327. const md = Object.assign({}, parentNodeData);
  1328. let setBadge = false;
  1329. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  1330. setBadge = true;
  1331. }
  1332. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1333. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, titleForDisplay) });
  1334. if (setBadge) {
  1335. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  1336. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  1337. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: titleForDisplay });
  1338.  
  1339. }
  1340.  
  1341. if (UPDATE_PIN_NAME) {
  1342. updatePinnedCommentBadge(md, title, langTitle);
  1343. }
  1344.  
  1345. if (funcPromises.length >= 1) {
  1346. let funcs = await Promise.all(funcPromises);
  1347.  
  1348. for (const func of funcs) {
  1349. if (typeof func === 'function') {
  1350. func(md);
  1351. }
  1352. }
  1353. }
  1354.  
  1355. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1356. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  1357. }
  1358.  
  1359.  
  1360. }
  1361.  
  1362. }
  1363. } catch (e) {
  1364. console.warn(e);
  1365. }
  1366.  
  1367. }
  1368.  
  1369. /**
  1370. *
  1371. * @param {string} url
  1372. * @returns
  1373. */
  1374. const channelUrlUnify = (url) => {
  1375.  
  1376. if (typeof url !== 'string') return url; // type unchanged
  1377. let c0 = url.charAt(0);
  1378. if (c0 === '/') return url;
  1379. let i = url.indexOf('.youtube.com/');
  1380. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1381. else if (url.charAt(0) !== '/') url = '/' + url;
  1382. return url
  1383.  
  1384. }
  1385.  
  1386. const parentYtElement = (node, nodeName, maxN) => {
  1387. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1388. if (pDom.nodeName === nodeName) {
  1389. return pDom;
  1390. }
  1391. }
  1392. return null;
  1393. }
  1394.  
  1395. const checkShortsChannelName = (rchannelNameDOM) => {
  1396. let browseId = '';
  1397. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1398.  
  1399. if (pDom instanceof HTMLElement) {
  1400. const pDomController = pDom.inst || pDom;
  1401. const runs = (((pDomController.data || 0).channelTitleText || 0).runs || 0);
  1402. if (runs.length === 1) {
  1403. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1404. browseId = (browserEndpoint.browseId || '');
  1405. const currentDisplayText = runs[0].text || ''
  1406.  
  1407. if (/^UC[-_a-zA-Z0-9+=.]+$/.test(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1408.  
  1409. if (!channelIdToHandle.has(browseId)) {
  1410. channelIdToHandle.set(browseId, {
  1411. handleText: currentDisplayText.trim(),
  1412. justPossible: true
  1413. });
  1414. }
  1415.  
  1416.  
  1417. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1418. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1419. // anchorNode &&
  1420. getDisplayName(browseId).then(fetchResult => {
  1421.  
  1422. if (fetchResult === null) return;
  1423.  
  1424. const { title, langTitle, externalId } = fetchResult;
  1425. const titleForDisplay = langTitle || title;
  1426. if (externalId !== browseId) return; // channel id must be the same
  1427.  
  1428. let hDom = pDom;
  1429. const hDomHostElement = hDom.hostElement || hDom;
  1430. const hDomController = hDom.inst || hDom;
  1431. let hData = (hDomController || 0).data || 0;
  1432. const runs = (((hData || 0).channelTitleText || 0).runs || 0);
  1433. if (runs && runs.length === 1 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  1434.  
  1435. let runs2 = [Object.assign({}, runs[0], { text: titleForDisplay })];
  1436.  
  1437.  
  1438. /*
  1439. runs.push({text: title, bold: true, "fontColor": "black",
  1440. size: "SIZE_DEFAULT",
  1441. style: "STYLE_TEXT",
  1442. });
  1443. */
  1444.  
  1445. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: { runs: runs2 }, rSk0e: 1 });
  1446.  
  1447. byPassCheckStore.delete(rchannelNameDOM);
  1448. }
  1449.  
  1450.  
  1451.  
  1452. })
  1453. }
  1454.  
  1455.  
  1456. }
  1457. }
  1458. return browseId
  1459. }
  1460.  
  1461. let firstDOMCheck = false;
  1462. const firstDOMChecker = isMobile ? () => {
  1463.  
  1464. let playerMicroformatRenderer = null;
  1465. try {
  1466. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  1467. } catch (e) { }
  1468. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  1469. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  1470. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  1471. }
  1472.  
  1473. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1474. const channelNameCData = !channelNameDOM ? null : (channelNameDOM.inst || channelNameDOM || 0).data;
  1475.  
  1476. if (channelNameCData) {
  1477. let mainChannelUrl = null;
  1478. let mainFormattedNameUrl = null;
  1479. let mainChannelText = null;
  1480. let mainFormattedNameText = null;
  1481.  
  1482. try {
  1483. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl)
  1484. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  1485. mainChannelText = channelNameCData.channelName
  1486. mainFormattedNameText = channelNameCData.title.runs[0].text
  1487. } catch (e) { }
  1488.  
  1489. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1490.  
  1491.  
  1492. let channelId = obtainChannelId(mainChannelUrl);
  1493. if (channelId) {
  1494. if (mainChannelText.startsWith('@')) return;
  1495. if (mainChannelText.trim() !== mainChannelText) return;
  1496.  
  1497. displayNameResStore.set(channelId, {
  1498. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1499. externalId: `${channelId}`,
  1500. ownerUrls: [],
  1501. title: mainChannelText,
  1502. vanityChannelUrl: null,
  1503. verified123: true
  1504. });
  1505. }
  1506.  
  1507.  
  1508. }
  1509. }
  1510.  
  1511. } : () => {
  1512.  
  1513. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1514. const channelNameCnt = !channelNameDOM ? null : channelNameDOM.inst || channelNameDOM;
  1515. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  1516. if (channelNameCData) {
  1517. let mainChannelUrl = null;
  1518. let mainFormattedNameUrl = null;
  1519. let mainChannelText = null;
  1520. let mainFormattedNameText = null;
  1521. try {
  1522. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1523. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1524. mainChannelText = channelNameCData.channelName.runs[0].text
  1525. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  1526. } catch (e) { }
  1527.  
  1528. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1529.  
  1530. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.exec(mainChannelUrl);
  1531.  
  1532. if (m && m[1] && mainChannelText !== m[1]) {
  1533.  
  1534. const channelHandle = m[1];
  1535. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  1536. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  1537. }
  1538.  
  1539. } else {
  1540.  
  1541. let channelId = obtainChannelId(mainChannelUrl);
  1542. if (channelId) {
  1543. if (mainChannelText.startsWith('@')) return;
  1544. if (mainChannelText.trim() !== mainChannelText) return;
  1545.  
  1546. displayNameResStore.set(channelId, {
  1547. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1548. externalId: `${channelId}`,
  1549. ownerUrls: [],
  1550. title: mainChannelText,
  1551. vanityChannelUrl: null,
  1552. verified123: true
  1553. });
  1554. }
  1555.  
  1556. }
  1557. }
  1558. }
  1559.  
  1560. };
  1561.  
  1562. // let newAnchorAdded = false;
  1563. /*
  1564. const intersectionobserver = new IntersectionObserver((entries) => {
  1565. let anchorAppear = false;
  1566. for (const entry of entries) {
  1567. if (entry.isIntersecting === true) {
  1568. anchorAppear = true;
  1569. break;
  1570. }
  1571. }
  1572. if (anchorAppear && newAnchorAdded) {
  1573. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1574. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1575. }
  1576. }, {
  1577. rootMargin:"0px 0px 0px 0px",
  1578. threshold:1
  1579. })
  1580. */
  1581.  
  1582.  
  1583. /* globals WeakRef:false */
  1584.  
  1585. /** @type {(o: Object | null) => WeakRef | null} */
  1586. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1587.  
  1588. /** @type {(wr: Object | null) => Object | null} */
  1589. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1590.  
  1591. let doShortsChecking = false;
  1592. let doDescriptionChecking = true;
  1593.  
  1594. let lastNewAnchorLastWR = null;
  1595.  
  1596. const mutexForDOMMutations = new Mutex();
  1597.  
  1598. const byPassCheckStore = new WeakSet();
  1599.  
  1600. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  1601. for (const mutation of mutations) {
  1602. const target = mutation.target;
  1603. if (!target) continue;
  1604. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  1605. if (!rchannelNameElm) continue;
  1606. const rchannelNameCnt = rchannelNameElm.inst || rchannelNameElm;
  1607. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  1608. const channelId = rchannelNameElm.getAttribute('jkrgy');
  1609. if (channelId) {
  1610. if (byPassCheckStore.has(rchannelNameElm)) continue;
  1611. const object = channelIdToHandle.get(channelId);
  1612. if (object && object.handleText && !object.justPossible) {
  1613. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  1614. if (textDom) {
  1615. let t = textDom.textContent.trim()
  1616. if (t === object.handleText || t === '') {
  1617. rchannelNameElm.removeAttribute('jkrgy');
  1618. Promise.resolve().then(domChecker);
  1619. }
  1620. }
  1621. }
  1622. }
  1623. }
  1624. })
  1625.  
  1626. let domCheckScheduledForShorts = false;
  1627. const domCheckSelectorForShorts = [
  1628. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  1629. ].join(', ');
  1630. const domCheckerForShorts = () => {
  1631.  
  1632. if (domCheckScheduledForShorts) return;
  1633. if (document.querySelector(domCheckSelectorForShorts) === null) {
  1634. return;
  1635. }
  1636. domCheckScheduledForShorts = true;
  1637.  
  1638. mutexForDOMMutations.lockWith(lockResolve => {
  1639.  
  1640.  
  1641. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  1642.  
  1643.  
  1644. domCheckScheduledForShorts = false;
  1645.  
  1646. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  1647. if (nodes.length === 0) {
  1648. lockResolve();
  1649. return;
  1650. }
  1651.  
  1652. for (const node of nodes) {
  1653.  
  1654. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  1655. if (rchannelNameElm) {
  1656. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  1657. childList: true,
  1658. subtree: true
  1659. });
  1660. let channelId = '';
  1661. byPassCheckStore.add(rchannelNameElm);
  1662. channelId = checkShortsChannelName(rchannelNameElm);
  1663. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  1664. }
  1665.  
  1666. }
  1667.  
  1668. lockResolve();
  1669.  
  1670. // }, 80);
  1671.  
  1672.  
  1673. })
  1674.  
  1675. }
  1676.  
  1677. const domCheckerForDescriptionAnchor = (s) => {
  1678.  
  1679. findTextNodes(s, (textNode) => {
  1680. const p = textNode.nodeValue;
  1681. const index = p.indexOf('@');
  1682. if (index < 0) return;
  1683. const q = p.substring(index);
  1684. const b = isDisplayAsHandle(q);
  1685. if (b) {
  1686. const href = s.getAttribute('href')
  1687.  
  1688. const channelId = obtainChannelId(href);
  1689. if (channelId) {
  1690. let h = q.trim();
  1691.  
  1692. if (!channelIdToHandle.has(channelId)) {
  1693. channelIdToHandle.set(channelId, {
  1694. handleText: h,
  1695. justPossible: true
  1696. });
  1697. }
  1698.  
  1699. s.setAttribute('jkrgy', channelId);
  1700.  
  1701. getDisplayName(channelId).then(fetchResult => {
  1702.  
  1703. if (fetchResult === null) return;
  1704.  
  1705. const { title, langTitle, externalId } = fetchResult;
  1706. const titleForDisplay = langTitle || title;
  1707. if (externalId !== channelId) return; // channel id must be the same
  1708.  
  1709. const anchorElement = s;
  1710. const anchorTextNode = textNode;
  1711.  
  1712. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  1713.  
  1714. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  1715.  
  1716. }
  1717.  
  1718. });
  1719. }
  1720. }
  1721. return true;
  1722. });
  1723.  
  1724. }
  1725. const domCheckerForDescription = isMobile ? () => {
  1726. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  1727. 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])')) {
  1728. s.setAttribute('dxcPj', '');
  1729. domCheckerForDescriptionAnchor(s);
  1730. }
  1731. } : () => {
  1732. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  1733. 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])')) {
  1734. s.setAttribute('dxcPj', '');
  1735. domCheckerForDescriptionAnchor(s);
  1736. }
  1737. };
  1738.  
  1739. let domCheckScheduled = false;
  1740. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])';
  1741. const domChecker = () => {
  1742.  
  1743. doShortsChecking && domCheckerForShorts();
  1744. doDescriptionChecking && domCheckerForDescription();
  1745.  
  1746. if (domCheckScheduled) return;
  1747. if (document.querySelector(domCheckSelector) === null) {
  1748. return;
  1749. }
  1750. domCheckScheduled = true;
  1751.  
  1752. mutexForDOMMutations.lockWith(lockResolve => {
  1753. domCheckScheduled = false;
  1754.  
  1755. const newAnchors = document.querySelectorAll(domCheckSelector);
  1756. if (newAnchors.length === 0) {
  1757. lockResolve();
  1758. return;
  1759. }
  1760.  
  1761. const cNewAnchorFirst = newAnchors[0]; // non-null
  1762. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1763. /** @type {HTMLElement | null} */
  1764. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1765. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1766.  
  1767. if (!firstDOMCheck) {
  1768. firstDOMCheck = true;
  1769. USE_CHANNEL_META && firstDOMChecker();
  1770. }
  1771.  
  1772. Promise.resolve()
  1773. .then(() => {
  1774. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1775. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1776. mutex.nextIndex = 0;
  1777. }
  1778. }
  1779. }).then(() => {
  1780.  
  1781. // newAnchorAdded = true;
  1782. for (const anchor of newAnchors) {
  1783. // author-text or name
  1784. // normal url: /channel/xxxxxxx
  1785. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1786. const href = anchor.getAttribute('href');
  1787. const channelId = obtainChannelId(href); // string, can be empty
  1788. anchor.setAttribute('jkrgy', channelId);
  1789. // intersectionobserver.unobserve(anchor);
  1790. // intersectionobserver.observe(anchor); // force first occurance
  1791. domCheckAsync(anchor, href, channelId);
  1792. }
  1793.  
  1794. }).then(lockResolve).catch(e => {
  1795. lockResolve();
  1796. console.warn(e);
  1797. });
  1798.  
  1799. });
  1800.  
  1801.  
  1802. };
  1803.  
  1804.  
  1805. /** @type {MutationObserver | null} */
  1806. let domObserver = null;
  1807.  
  1808. /** @type {(callback: (event: Event)=>{})} */
  1809. const onPageFetched = isMobile ? (callback) => {
  1810.  
  1811. let state = 0;
  1812.  
  1813. window.addEventListener('state-change', function (evt) {
  1814. if (state === 1) return; // ignore intermediate events
  1815. state = 1; // before value: 0 or 2;
  1816. callback(evt);
  1817. }, false);
  1818.  
  1819. window.addEventListener('state-navigateend', function (evt) { // fallback
  1820. let inSeq = state === 1;
  1821. state = 2; // 2 when loaded
  1822. if (!inSeq) callback(evt);
  1823. }, false);
  1824.  
  1825. } : (callback) => {
  1826.  
  1827. let state = 0;
  1828.  
  1829. document.addEventListener('yt-page-data-fetched', function (evt) {
  1830. if (state === 1) return; // ignore intermediate events if any
  1831. state = 1; // before value: 0 or 2;
  1832. callback(evt);
  1833. }, false);
  1834.  
  1835. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1836. let inSeq = state === 1;
  1837. state = 2; // 2 when loaded
  1838. if (!inSeq) callback(evt);
  1839. }, false);
  1840.  
  1841. };
  1842.  
  1843. /**
  1844. *
  1845. * @param {Node} app
  1846. * @returns
  1847. */
  1848. function setupOnPageFetched(app) {
  1849.  
  1850. firstDOMCheck = false;
  1851.  
  1852. if (!cfg['INNERTUBE_API_KEY']) {
  1853. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1854. return;
  1855. }
  1856.  
  1857. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  1858. doShortsChecking = true;
  1859. } else {
  1860. doShortsChecking = false;
  1861. }
  1862.  
  1863. if (!domObserver) {
  1864. domObserver = new MutationObserver(domChecker);
  1865. } else {
  1866. domObserver.takeRecords();
  1867. domObserver.disconnect();
  1868. }
  1869.  
  1870. domObserver.observe(app, { childList: true, subtree: true });
  1871. domChecker();
  1872.  
  1873. }
  1874.  
  1875. /**
  1876. *
  1877. * @param {Object|null} dest
  1878. * @param {Object} ytcfg
  1879. * @param {string[]} keys
  1880. * @returns
  1881. */
  1882. function getYtConfig(dest, ytcfg, keys) {
  1883. dest = dest || {};
  1884. if (typeof ytcfg.get === 'function') { // mobile
  1885. for (const key of keys) {
  1886. dest[key] = ytcfg.get(key);
  1887. }
  1888. } else {
  1889. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  1890. for (const key of keys) {
  1891. dest[key] = cfgData[key];
  1892. }
  1893. }
  1894. return dest;
  1895. }
  1896.  
  1897. /** @type { (evt: Object) => Element | null } */
  1898. const getPageApp = isMobile
  1899. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  1900. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  1901.  
  1902. onPageFetched(async (evt) => {
  1903. const app = getPageApp(evt);
  1904. console.assert(app);
  1905. const ytcfg = ((window || 0).ytcfg || 0);
  1906. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  1907. setupOnPageFetched(app);
  1908. });
  1909.  
  1910. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });