Restore YouTube Username from Handle to Custom

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

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

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