Restore YouTube Username from Handle to Custom

將 YouTube 使用者名稱從 Handle 恢復為自訂名稱

目前為 2023-12-02 提交的版本,檢視 最新版本

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

QingJ © 2025

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