Restore YouTube Username from Handle to Custom

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

当前为 2023-07-01 提交的版本,查看 最新版本

  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.7.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 55
  45. // @compatible chrome 61
  46. // @compatible opera 48
  47. // @compatible safari 11.1
  48. // @compatible edge 16
  49.  
  50. // @description To restore YouTube Username to the traditional custom name
  51. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  52. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  53. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  54.  
  55. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  56. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  57. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  58. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  59. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  60. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  61. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  62. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  63. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  64. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  65. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  66. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  67. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  68. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  69. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  70. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  71. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  72. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  73. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  74. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  75. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  76. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  77. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  78. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  79. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  80. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  81. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  82. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  83. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  84. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  85. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  86. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  87. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  88. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  89. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  90. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  91. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  92. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  93. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  94. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  95. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  96. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  97. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  98. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  99. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  100. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  101. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  102. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  103. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  104. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  105. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  106. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  107. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  108. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  109. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  110. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  111. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  112. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  113. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  114. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  115. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  116. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  117. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  118. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  119. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  120. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  121. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  122. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  123. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  124.  
  125. // ==/UserScript==
  126.  
  127. /* jshint esversion:8 */
  128.  
  129.  
  130. /**
  131. @typedef DisplayNameResultObject
  132. @type {Object}
  133. @property {string} title
  134. @property {string?} externalId
  135. @property {string[]} ownerUrls
  136. @property {string} channelUrl
  137. @property {string} vanityChannelUrl
  138. @property {boolean|undefined} verified123
  139.  
  140. */
  141.  
  142. /**
  143. @typedef ChannelIdToHandleResult
  144. @type {Object}
  145. @property {string} handleText
  146. @property {boolean} justPossible
  147. */
  148.  
  149. (function (__CONTEXT__) {
  150. 'use strict';
  151.  
  152. const USE_RSS_FETCHER = true;
  153. const USE_TIMEOUT_SIGNAL = false;
  154. const USE_CHANNEL_META = true;
  155. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  156.  
  157. const { Promise, fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  158.  
  159. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  160. let controller = new AbortController();
  161. const r = controller.signal;
  162. let cid = setTimeout(() => {
  163. if (cid >= 1) {
  164. cid = 0;
  165. controller && controller.abort();
  166. controller = null;
  167. }
  168. }, timeout);
  169. r.clearTimeout = () => {
  170. if (cid >= 1) {
  171. clearTimeout(cid);
  172. cid = 0;
  173. }
  174. }
  175. return r;
  176. } : () => { };
  177.  
  178. const fxOperator = (proto, propertyName) => {
  179. let propertyDescriptorGetter = null;
  180. try {
  181. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  182. // https://github.com/cyfung1031/userscript-supports/issues/9
  183. // .parentNode becomes DocumentFragment
  184. /**
  185. *
  186. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  187. *
  188. * e.g. ytd-comment-renderer#comment > div#body
  189. *
  190. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  191. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  192. *
  193. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  194. *
  195. * Alternative way: ytCustomElement.$.xxxxxxx
  196. *
  197. */
  198. } catch (e) { }
  199. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  200. };
  201.  
  202. const fxAPI = (proto, propertyName) => {
  203. const methodFunc = proto[propertyName];
  204. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  205. };
  206.  
  207. /** @type { (node: Node)=>Node | null } */
  208. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  209. /** @type { (node: Node)=>Node | null } */
  210. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  211. /** @type { (node: Node)=>Node | null } */
  212. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  213.  
  214. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  215. const elementQS = fxAPI(Element.prototype, 'querySelector');
  216. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  217. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  218.  
  219. /*
  220. init
  221. initialdata
  222. state-progress
  223. state-responsereceived
  224. player-autonav-pause
  225. state-change
  226. state-navigateend
  227. player-initialized
  228. renderer-module-load-start
  229. video-data-change
  230. player-state-change
  231. updateui
  232. renderer-module-load-end -> channel owner DOM available
  233. player-autonav-pause
  234. updateui
  235. renderer-module-load-start
  236. updateui
  237. renderer-module-load-end
  238. playing
  239. h5player.video-progress
  240. h5player.video-progress
  241. h5player.video-progress
  242. h5player.video-progress
  243. ...
  244. navigate new video
  245. state-navigatestart
  246. state-change => channel owener DOM vanished
  247. state-progress
  248. ...
  249. h5player.player-state-change
  250. h5player.video-data-change
  251. h5player.player-state-change
  252. h5player.muted-autoplay-change
  253. h5player.volume-change
  254. h5player.video-data-change
  255. h5player.volume-change
  256. ...
  257. state-progress
  258. ...
  259. state-progress => channel owner DOM appear [just before state-responsereceived]
  260. state-responsereceived
  261. video-data-change
  262. state-change
  263. state-navigateend
  264. UX interaction
  265. user-activity
  266. player-autonav-pause
  267. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  268. EventTarget.prototype.dispatchEvent = function (ev) {
  269. if (ev instanceof Event) {
  270. if (ev.type === 'video-progress') { } else {
  271. console.log(ev.type, this, ev.target)
  272. if (ev.target === null) {
  273. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  274. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  275. }
  276. }
  277. }
  278. return this.uhfsE.apply(this, arguments);
  279. }
  280. */
  281.  
  282. const isMobile = location.hostname === 'm.youtube.com';
  283.  
  284. const cfg = {};
  285. class Mutex {
  286.  
  287. constructor() {
  288. this.p = Promise.resolve()
  289. }
  290.  
  291. /**
  292. * @param {(lockResolve: () => void)} f
  293. */
  294. lockWith(f) {
  295. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  296. }
  297.  
  298. }
  299.  
  300. class OrderedMutex extends Mutex {
  301. constructor() {
  302. super();
  303. this.nextIndex = 0;
  304. this.arr = [];
  305. this.lockFunc = resolve => {
  306. if (this.arr.length >= 1) {
  307. let f = this.arr[0];
  308. if (typeof f === 'function') {
  309. this.arr.shift();
  310. if (this.nextIndex > 0) this.nextIndex--;
  311. f(resolve);
  312. return;
  313. } else {
  314. // reset if unknown error
  315. this.arr.length = 0;
  316. this.nextIndex = 0;
  317. }
  318. }
  319. resolve();
  320. };
  321. }
  322. /**
  323. * @param {(lockResolve: () => void)} f
  324. */
  325. add(f) {
  326. if (this.nextIndex === this.arr.length) {
  327. this.arr.push(f); this.nextIndex++;
  328. } else {
  329. this.arr.splice(this.nextIndex++, 0, f);
  330. }
  331. this.lockWith(this.lockFunc);
  332. }
  333. }
  334. // usage: run network request one by one
  335. const mutex = new OrderedMutex();
  336.  
  337. /**
  338. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  339. * @template T
  340. */
  341.  
  342. //
  343. /**
  344. * usage: cache the network result per web application instance.
  345. * @type {Map<string, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  346. const displayNameResStore = new Map();
  347.  
  348. /**
  349. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  350. * @type {WeakMap<Function, Function>} */
  351. const dataChangedFuncStore = new WeakMap();
  352.  
  353. /**
  354. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  355. * @type {Map<string, AsyncOrResolvedValue<string>>} */
  356. const handleToChannelId = new Map();
  357.  
  358. /**
  359. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  360. * @type {Map<string, ChannelIdToHandleResult>} */
  361. const channelIdToHandle = new Map();
  362.  
  363.  
  364. /**
  365. * AsyncValue
  366. * @class
  367. * @template T
  368. */
  369. class AsyncValue {
  370. constructor() {
  371. /** @type {T | null} */
  372. this.__value__ = null;
  373. /** @type {((value: any)=>void) | null} */
  374. this.__resolve__ = null;
  375. this.__promise__ = new Promise(resolve => {
  376. this.__resolve__ = resolve;
  377. });
  378. }
  379. /**
  380. *
  381. * @param {T} value
  382. */
  383. setValue(value) {
  384. const promise = this.__promise__;
  385. if (promise === null) throw 'Value has already been set.';
  386. this.__value__ = value;
  387. this.__promise__ = null;
  388. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  389. }
  390. /**
  391. *
  392. * @returns {Promise<T>}
  393. */
  394. async getValue() {
  395. const promise = this.__promise__;
  396. if (promise === null) return this.__value__;
  397. await promise; // promise become null
  398. this.__promise__ = null; // just in case
  399. this.__resolve__ = null;
  400. return this.__value__;
  401. }
  402. }
  403.  
  404. /**
  405. *
  406. * @param {DisplayNameResultObject} resultInfo
  407. * @param {string} channelId
  408. */
  409. const cacheHandleToChannel = (resultInfo, channelId) => {
  410.  
  411. const { vanityChannelUrl, ownerUrls } = resultInfo;
  412.  
  413. let handleText = urlToHandle(vanityChannelUrl || '');
  414.  
  415. if (handleText) {
  416. // match = true;
  417. } else if ((ownerUrls || 0).length >= 1) {
  418. for (const ownerUrl of ownerUrls) {
  419. handleText = urlToHandle(ownerUrl || '');
  420.  
  421. if (handleText) {
  422. // match = true;
  423. break;
  424. }
  425. }
  426. }
  427. if (handleText) {
  428.  
  429. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  430. if (asyncValue instanceof AsyncValue) {
  431. asyncValue.setValue(channelId);
  432. }
  433. handleToChannelId.set(handleText, channelId);
  434. }
  435.  
  436.  
  437. }
  438.  
  439. /**
  440. *
  441. * @param {string} channelId
  442. * @param {Function} onDownloaded
  443. * @param {Function} onResulted
  444. * @param {Function} onError
  445. */
  446. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  447.  
  448. let signal = timeoutSignal(4000);
  449.  
  450. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  451. "method": "POST",
  452. "mode": "same-origin",
  453. "credentials": "omit",
  454.  
  455. referrerPolicy: "no-referrer",
  456. cache: "default", // no effect on POST request
  457. // cache: "force-cache",
  458. redirect: "error", // there shall be no redirection in this API request
  459. integrity: "",
  460. keepalive: false,
  461. signal,
  462.  
  463. "headers": {
  464. "Content-Type": "application/json", // content type of the body data in POST request
  465. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  466. // X-Youtube-Bootstrap-Logged-In: false,
  467. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  468. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  469.  
  470. "Accept": "application/json",
  471. },
  472. "body": JSON.stringify({
  473. "context": {
  474. "client": {
  475. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  476. "clientName": "MWEB", // "WEB", "MWEB"
  477. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  478. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  479. "playerType": "UNIPLAYER",
  480. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  481. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  482. "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",
  483. "mainAppWebInfo": {
  484. "graftUrl": `/channel/${channelId}`,
  485. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  486. "isWebNativeShareAvailable": true
  487. }
  488. },
  489. "user": {
  490. "lockedSafetyMode": false
  491. },
  492. "request": {
  493. "useSsl": true,
  494. "internalExperimentFlags": [],
  495. "consistencyTokenJars": []
  496. }
  497. },
  498. "browseId": `${channelId}`
  499. })
  500. })).then(res => {
  501. signal && signal.clearTimeout && signal.clearTimeout();
  502. signal = null;
  503. onDownloaded();
  504. onDownloaded = null;
  505. return res.json();
  506. }).then(resJson => {
  507. let resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  508. onResulted(resultInfo);
  509. onResulted = null;
  510. }).catch(onError);
  511.  
  512. };
  513.  
  514. /**
  515. *
  516. * @param {string} channelId
  517. * @param {Function} onDownloaded
  518. * @param {Function} onResulted
  519. * @param {Function} onError
  520. */
  521. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  522.  
  523. let signal = timeoutSignal(4000);
  524. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  525. // YouTube RSS Response - public, max-age=900
  526.  
  527. "method": "GET",
  528. "mode": "same-origin",
  529. "credentials": "omit",
  530.  
  531. referrerPolicy: "no-referrer",
  532. cache: "default",
  533. // cache: "no-cache",
  534. redirect: "error", // there shall be no redirection in this API request
  535. integrity: "",
  536. keepalive: false,
  537. signal,
  538.  
  539. "headers": {
  540. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  541. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  542. // seems YouTube RSS Feeds server insists its own Cache-Control.
  543.  
  544. // "Content-Type": "text/xml; charset=UTF-8",
  545. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  546. // X-Youtube-Bootstrap-Logged-In: false,
  547. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  548. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  549.  
  550. "Accept": "text/xml",
  551. }
  552. }).then(res => {
  553. signal && signal.clearTimeout && signal.clearTimeout();
  554. signal = null;
  555. onDownloaded();
  556. onDownloaded = null;
  557. return res.text();
  558. }).then(resText => {
  559. let eIdx = resText.indexOf('<entry>');
  560. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  561.  
  562. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  563. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  564. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  565. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  566.  
  567.  
  568. let name, uri, mt;
  569.  
  570. // ===============================================================
  571.  
  572. /* removed in 2023.06.30 */
  573.  
  574.  
  575. // ===============================================================
  576.  
  577.  
  578. const wIdx1 = mText.indexOf('<author>');
  579. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  580.  
  581. if (wIdx1 > 0 && wIdx2 > 0) {
  582. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  583. const template = document.createElement('template');
  584. template.innerHTML = qText;
  585. /** @type {HTMLElement | null} */
  586. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  587. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  588. const nodeName = authorChild.nodeName;
  589. if (nodeName === 'NAME') name = authorChild.textContent;
  590. else if (nodeName === 'URI') {
  591. uri = authorChild.textContent;
  592. mt = obtainChannelId(uri);
  593. }
  594. }
  595. template.innerHTML = '';
  596. }
  597.  
  598. if (!name && !uri) {
  599.  
  600. // fallback
  601.  
  602. const parser = new DOMParser();
  603. const xmlDoc = parser.parseFromString(mText, "text/xml");
  604.  
  605. // const author = xmlDoc.querySelector("author");
  606.  
  607. // https://extendsclass.com/xpath-tester.html
  608.  
  609. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  610.  
  611. let authorChild;
  612. while ((authorChild = authorChilds.iterateNext()) !== null) {
  613. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  614. else if (authorChild.nodeName === 'uri') {
  615. uri = authorChild.textContent;
  616. mt = obtainChannelId(uri)
  617. }
  618. }
  619.  
  620. try {
  621. xmlDoc.firstChild.remove();
  622. } catch (e) { }
  623.  
  624. }
  625.  
  626.  
  627.  
  628.  
  629. let res = null;
  630.  
  631. if (name && uri && mt && mt === channelId) {
  632.  
  633.  
  634. let object = channelIdToHandle.get(mt);
  635.  
  636. if (object) {
  637.  
  638. if (object.handleText === name) channelIdToHandle.delete(mt);
  639. else {
  640. object.justPossible = false; // ignore @handle checking
  641.  
  642. res = {
  643. "title": name,
  644. "externalId": mt,
  645. "ownerUrls": [
  646. `http://www.youtube.com/${object.handleText}`
  647. ],
  648. "channelUrl": uri,
  649. "vanityChannelUrl": `http://www.youtube.com/${object.handleText}`
  650. };
  651.  
  652. }
  653. }
  654. }
  655.  
  656. onResulted(res);
  657. onResulted = null;
  658.  
  659. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  660. // onResulted(resultInfo);
  661. }).catch(onError);
  662.  
  663.  
  664.  
  665. }
  666.  
  667. /**
  668. *
  669. * @param {string} channelId
  670. */
  671. function stackNewRequest(channelId) {
  672.  
  673. mutex.add(lockResolve => {
  674.  
  675. let bResult = displayNameResStore.get(channelId);
  676. if (!(bResult instanceof AsyncValue)) {
  677. // resolved or removed
  678. lockResolve(); lockResolve = null;
  679. return;
  680. }
  681.  
  682. let setResult = (result) => {
  683. setResult = null;
  684. if (!result) {
  685. bResult.fetchingState = 0;
  686. bResult.setValue(null);
  687. displayNameResStore.delete(channelId); // create another network response in the next request
  688. } else {
  689. bResult.fetchingState = 4;
  690. bResult.setValue(result);
  691. displayNameResStore.set(channelId, result); // update store result to resolved value
  692. }
  693. bResult = null;
  694. }
  695.  
  696. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  697. // request is already done. no need to stack any request
  698. lockResolve(); lockResolve = null;
  699. return;
  700. }
  701.  
  702. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  703. // element has already been removed
  704. lockResolve(); lockResolve = null;
  705. setResult(null);
  706. return;
  707. }
  708.  
  709. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  710.  
  711. bResult.fetchingState = 2;
  712.  
  713.  
  714. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  715. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  716. const fetcher = USE_RSS_FETCHER && fetcherRSS && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  717. fetcher(channelId, () => {
  718. bResult.fetchingState = 3;
  719. lockResolve();
  720. lockResolve = null;
  721. }, resultInfo => {
  722.  
  723. if (!resultInfo) {
  724. // invalid json format
  725. setResult(null);
  726. return;
  727. }
  728.  
  729. cacheHandleToChannel(resultInfo, channelId);
  730.  
  731. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  732.  
  733. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  734.  
  735. setResult(displayNameRes);
  736. }, e => {
  737. lockResolve && lockResolve();
  738. lockResolve = null;
  739. console.warn(e);
  740. setResult && setResult(null);
  741. });
  742.  
  743. });
  744.  
  745. }
  746.  
  747. /**
  748. *
  749. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  750. * @returns Example: _\@yr__kd_
  751. */
  752. function urlToHandle(url) {
  753.  
  754. if (typeof url !== 'string') return '';
  755. let i = url.indexOf('.youtube.com/');
  756. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  757. else if (url.charAt(0) === '/') url = url.substring(1);
  758. return isDisplayAsHandle(url) ? url : '';
  759.  
  760. }
  761.  
  762. /**
  763. *
  764. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  765. * @returns {Promise<DisplayNameResultObject | null>}
  766. */
  767. async function getDisplayName(channelId) {
  768.  
  769. let cache = displayNameResStore.get(channelId);
  770. let isStackNewRequest = false;
  771.  
  772. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  773. let aResult;
  774.  
  775. if (cache instanceof AsyncValue) {
  776. aResult = cache;
  777. if (aResult.fetchingState >= 2) {
  778. // aResult.fetchingState
  779. // 2: network fetch started
  780. // 3: network fetch ended
  781. // isStackNewRequest = false;
  782. } else {
  783. // 0: invalid before
  784. // 1: scheduled but not yet fetch
  785. isStackNewRequest = true;
  786. }
  787. } else if (cache) {
  788. // resolved result
  789. return cache;
  790. } else {
  791. // else no cached value found
  792. /** @type {AsyncValue<DisplayNameResultObject>} */
  793. aResult = new AsyncValue();
  794. displayNameResStore.set(channelId, aResult);
  795. isStackNewRequest = true;
  796. }
  797.  
  798. if (isStackNewRequest) {
  799. aResult.fetchingState = 1;
  800. stackNewRequest(channelId);
  801. }
  802. return await aResult.getValue();
  803. }
  804.  
  805.  
  806. /**
  807. *
  808. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  809. * @returns
  810. */
  811. const obtainChannelId = (href) => {
  812. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  813. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  814. return !m ? '' : (m[1] || '');
  815. };
  816.  
  817.  
  818. /**
  819. *
  820. * @param {Element} ytElm
  821. */
  822. const resetWhenDataChanged = (ytElm) => {
  823. if (ytElm instanceof Element) {
  824. const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  825. if ((anchors || 0).length >= 1 && (ytElm.data || 0).jkrgx !== 1) {
  826. for (const anchor of anchors) {
  827. anchor.removeAttribute('jkrgy');
  828. }
  829. }
  830. }
  831. }
  832.  
  833. /**
  834. *
  835. * @param {Function} dataChanged original dataChanged function
  836. * @returns new dataChanged function
  837. */
  838. const dataChangeFuncProducer = (dataChanged) => {
  839. /** @this HTMLElement */
  840. return function () {
  841. resetWhenDataChanged(this);
  842. return dataChanged.apply(this, arguments);
  843. }
  844. };
  845.  
  846. /**
  847. *
  848. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  849. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  850. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  851. * @returns
  852. */
  853. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  854.  
  855. let currentHref = anchor.getAttribute('href');
  856. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  857.  
  858. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  859.  
  860. };
  861.  
  862. /**
  863. *
  864. * @param {string} currentDisplayed
  865. * @param {DisplayNameResultObject} fetchResult
  866. * @returns
  867. */
  868. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  869.  
  870. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  871.  
  872. const currentDisplayTrimmed = currentDisplayed.trim();
  873. let match = false;
  874. if (verified123) {
  875. match = true;
  876. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  877. match = true;
  878. } else if ((ownerUrls || 0).length >= 1) {
  879. for (const ownerUrl of ownerUrls) {
  880. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  881. match = true;
  882. break;
  883. }
  884. }
  885. }
  886. if (match) {
  887. return currentDisplayTrimmed;
  888. }
  889. return '';
  890.  
  891. };
  892.  
  893. /**
  894. *
  895. *
  896. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  897. - Is between 3-30 characters
  898. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  899. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  900. - Is not URL-like or phone number-like
  901. - Is not already being used
  902. - Follows YouTube's Community Guidelines
  903. ### Handle automatically generated by YouTube
  904. - `@user-XXXX`
  905. - without dot (.)
  906. *
  907. * @param {string} text
  908. * @returns
  909. */
  910. const isDisplayAsHandle = (text) => {
  911.  
  912. if (typeof text !== 'string') return false;
  913. if (text.length < 4) return false;
  914. if (text.indexOf('@') < 0) return false;
  915. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  916.  
  917. };
  918.  
  919. /**
  920. *
  921. * @param {Object[]} contentTexts
  922. * @param {number} idx
  923. * @returns
  924. */
  925. const contentTextProcess = (contentTexts, idx) => {
  926. const contentText = contentTexts[idx];
  927. const text = (contentText || 0).text;
  928. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  929. if (typeof url === 'string' && typeof text === 'string') {
  930.  
  931. if (!isDisplayAsHandle(text)) return null;
  932. const channelId = obtainChannelId(url);
  933.  
  934. return getDisplayName(channelId).then(fetchResult => {
  935. let resolveResult = null;
  936. if (fetchResult) {
  937. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  938.  
  939. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  940. if (textTrimmed) {
  941. resolveResult = (md) => {
  942. let runs = ((md || 0).contentText || 0).runs;
  943. if (!runs || !runs[idx]) return;
  944. if (runs[idx].text !== text) return;
  945. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  946. md.contentText = Object.assign({}, md.contentText);
  947. };
  948. }
  949. }
  950. return resolveResult; // function as a Promise
  951. });
  952. }
  953.  
  954. return null;
  955. };
  956.  
  957. /**
  958. *
  959. * @param {ParentNode} parentNode
  960. * @param {Function} callback
  961. */
  962. function findTextNodes(parentNode, callback) {
  963. /**
  964. *
  965. * @param {Node} node
  966. * @returns
  967. */
  968. function traverse(node) {
  969. if (node.nodeType === Node.TEXT_NODE) {
  970. let r = callback(node);
  971. if (r === true) return true;
  972. }
  973.  
  974. let childNode = nodeFirstChild(node);
  975. while (childNode) {
  976. let r = traverse(childNode);
  977. if (r === true) return true;
  978. childNode = nodeNextSibling(childNode);
  979. }
  980. }
  981.  
  982. traverse(parentNode);
  983. }
  984.  
  985. /**
  986. *
  987. * @param {ParentNode} parentNode
  988. * @param {Object[]} contentTexts
  989. * @param {number} aidx
  990. * @returns
  991. */
  992. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  993.  
  994.  
  995. let commentText = elementQS(parentNode, '.comment-text');
  996. if (!commentText) return;
  997. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  998. let currentText = commentText.textContent;
  999. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1000. if (!textMatch) return;
  1001.  
  1002. const contentText = contentTexts[aidx];
  1003.  
  1004. /** @type {string} */
  1005. const handleText = contentText.text.trim();
  1006. /** @type {string | null | undefined} */
  1007. let channelId;
  1008.  
  1009. let cache = handleToChannelId.get(handleText);
  1010.  
  1011. if (typeof cache === 'string') {
  1012. channelId = cache;
  1013. } else if (cache instanceof AsyncValue) {
  1014. channelId = await cache.getValue();
  1015. } else {
  1016. /** @type {AsyncValue<string>} */
  1017. const asyncValue = new AsyncValue();
  1018. handleToChannelId.set(handleText, asyncValue);
  1019. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1020. }
  1021.  
  1022. if (!channelId) return; // just in case
  1023.  
  1024. if (commentText.isConnected !== true) return; // already removed
  1025. if (commentText.textContent !== currentText) return; // already changed
  1026.  
  1027. const fetchResult = await getDisplayName(channelId);
  1028.  
  1029. if (fetchResult === null) return;
  1030.  
  1031. const { title, externalId } = fetchResult;
  1032. if (externalId !== channelId) return; // channel id must be the same
  1033.  
  1034. let search = contentText.text;
  1035. if (typeof search === 'string') {
  1036.  
  1037. const searchTrimmed = search.trim();
  1038. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1039. contentText.text = search.replace(searchTrimmed, "@" + title);
  1040.  
  1041. findTextNodes(commentText, (textnode) => {
  1042. if (textnode.nodeValue.indexOf(search) >= 0) {
  1043. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1044. return true;
  1045. }
  1046. });
  1047. }
  1048.  
  1049. }
  1050.  
  1051. }
  1052.  
  1053. /**
  1054. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1055. * @type { (anchor: HTMLElement, channelHref: string?, mt: string?) => Promise<void> }
  1056. */
  1057. const domCheckAsync = isMobile ? async (anchor, channelHref, mt) => {
  1058.  
  1059. try {
  1060. if (!channelHref || !mt) return;
  1061. let parentNode = nodeParent(anchor);
  1062. while (parentNode instanceof Node) {
  1063. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1064. parentNode = nodeParent(parentNode);
  1065. }
  1066. if (parentNode instanceof Node) { } else return;
  1067.  
  1068. let displayTextDOM = elementQS(parentNode, '.comment-header .comment-title');
  1069. if (!displayTextDOM) return;
  1070. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1071. let airaLabel = anchor.getAttribute('aria-label')
  1072. const parentNodeData = parentNode.data;
  1073. let runs = ((parentNodeData || 0).authorText || 0).runs;
  1074.  
  1075. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  1076.  
  1077. if (!channelIdToHandle.has(mt)) {
  1078. channelIdToHandle.set(mt, {
  1079. handleText: airaLabel.trim(),
  1080. justPossible: true
  1081. })
  1082. }
  1083.  
  1084. const fetchResult = await getDisplayName(mt);
  1085.  
  1086. if (fetchResult === null) return;
  1087.  
  1088. const { title, externalId } = fetchResult;
  1089.  
  1090. if (externalId !== mt) return; // channel id must be the same
  1091.  
  1092. // anchor href might be changed by external
  1093. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1094.  
  1095. let found = false;
  1096.  
  1097. findTextNodes(displayTextDOM, (textnode) => {
  1098. if (textnode.nodeValue === airaLabel) {
  1099. textnode.nodeValue = title;
  1100. found = true;
  1101. return true;
  1102. }
  1103. });
  1104.  
  1105. if (!found) return;
  1106. anchor.setAttribute('aria-label', title);
  1107. runs[0].text = title;
  1108.  
  1109.  
  1110. const contentTexts = (parentNodeData.contentText || 0).runs;
  1111. if (contentTexts && contentTexts.length >= 2) {
  1112. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1113. const contentText = contentTexts[aidx] || 0;
  1114. if (contentText.italics !== true) {
  1115. let isHandle = isDisplayAsHandle(contentText.text);
  1116. if (isHandle) {
  1117. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1118. }
  1119. }
  1120. }
  1121. }
  1122.  
  1123. }
  1124. } catch (e) {
  1125. console.warn(e);
  1126. }
  1127.  
  1128. } : async (anchor, channelHref, mt) => {
  1129.  
  1130. try {
  1131. if (!channelHref || !mt) return;
  1132. let parentNode = nodeParent(anchor);
  1133. while (parentNode instanceof Node) {
  1134. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  1135. parentNode = nodeParent(parentNode);
  1136. }
  1137. if (parentNode instanceof Node) { } else return;
  1138. const authorText = (parentNode.data || 0).authorText;
  1139. const currentDisplayed = (authorText || 0).simpleText;
  1140. if (typeof currentDisplayed !== 'string') return;
  1141. if (!isDisplayAsHandle(currentDisplayed)) return;
  1142.  
  1143. if (!channelIdToHandle.has(mt)) {
  1144. channelIdToHandle.set(mt, {
  1145. handleText: currentDisplayed.trim(),
  1146. justPossible: true
  1147. })
  1148. }
  1149.  
  1150. const oldDataChanged = parentNode.dataChanged;
  1151. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  1152. let newDataChanged = dataChangedFuncStore.get(oldDataChanged);
  1153. if (!newDataChanged) {
  1154. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  1155. newDataChanged.jkrgx = 1;
  1156. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  1157. }
  1158. parentNode.dataChanged = newDataChanged;
  1159. }
  1160.  
  1161. const fetchResult = await getDisplayName(mt);
  1162.  
  1163. if (fetchResult === null) return;
  1164.  
  1165. const { title, externalId } = fetchResult;
  1166.  
  1167. if (externalId !== mt) return; // channel id must be the same
  1168.  
  1169. // anchor href might be changed by external
  1170. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1171.  
  1172. const parentNodeData = parentNode.data;
  1173. const funcPromises = [];
  1174.  
  1175. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1176.  
  1177. if (authorText.simpleText !== currentDisplayed) return;
  1178. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1179. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  1180. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  1181.  
  1182. // the inside hyperlinks will be only converted if its parent author name is handle
  1183. const contentTexts = (parentNodeData.contentText || 0).runs;
  1184. if (contentTexts && contentTexts.length >= 1) {
  1185. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1186. const r = contentTextProcess(contentTexts, aidx);
  1187. if (r instanceof Promise) funcPromises.push(r);
  1188. }
  1189. }
  1190.  
  1191. const md = Object.assign({}, parentNodeData);
  1192. let setBadge = false;
  1193. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  1194. setBadge = true;
  1195. }
  1196. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1197. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  1198. if (setBadge) {
  1199. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  1200. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  1201. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  1202.  
  1203. }
  1204. if (funcPromises.length >= 1) {
  1205. let funcs = await Promise.all(funcPromises);
  1206.  
  1207. for (const func of funcs) {
  1208. if (typeof func === 'function') {
  1209. func(md);
  1210. }
  1211. }
  1212. }
  1213. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  1214.  
  1215.  
  1216. }
  1217.  
  1218. }
  1219. } catch (e) {
  1220. console.warn(e);
  1221. }
  1222.  
  1223. }
  1224.  
  1225. /**
  1226. *
  1227. * @param {string} url
  1228. * @returns
  1229. */
  1230. const channelUrlUnify = (url) => {
  1231.  
  1232. if (typeof url !== 'string') return url; // type unchanged
  1233. let c0 = url.charAt(0);
  1234. if (c0 === '/') return url;
  1235. let i = url.indexOf('.youtube.com/');
  1236. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1237. else if (url.charAt(0) !== '/') url = '/' + url;
  1238. return url
  1239.  
  1240. }
  1241.  
  1242. const parentYtElement = (node, nodeName, maxN) => {
  1243. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1244. if (pDom.nodeName === nodeName) {
  1245. return pDom;
  1246. }
  1247. }
  1248. return null;
  1249. }
  1250.  
  1251. const checkShortsChannelName = (rchannelNameDOM) => {
  1252. let browseId = '';
  1253. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1254.  
  1255. if (pDom instanceof HTMLElement) {
  1256. const runs = (((pDom.data || 0).channelTitleText || 0).runs || 0);
  1257. if (runs.length === 1) {
  1258. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1259. browseId = (browserEndpoint.browseId || '');
  1260. const currentDisplayText = runs[0].text || ''
  1261.  
  1262. if (/^UC[-_a-zA-Z0-9+=.]+$/.test(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1263.  
  1264. if (!channelIdToHandle.has(browseId)) {
  1265. channelIdToHandle.set(browseId, {
  1266. handleText: currentDisplayText.trim(),
  1267. justPossible: true
  1268. })
  1269. }
  1270.  
  1271.  
  1272. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1273. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1274. // anchorNode &&
  1275. getDisplayName(browseId).then(fetchResult => {
  1276.  
  1277. if (fetchResult === null) return;
  1278.  
  1279. const { title, externalId } = fetchResult;
  1280. if (externalId !== browseId) return; // channel id must be the same
  1281.  
  1282. let hDom = pDom;
  1283. let hData = (hDom || 0).data || 0;
  1284. const runs = (((hData || 0).channelTitleText || 0).runs || 0);
  1285. if (runs && runs.length === 1 && (runs[0] || 0).text === currentDisplayText) {
  1286.  
  1287. let runs2 = [Object.assign({}, runs[0], { text: title })];
  1288.  
  1289.  
  1290. /*
  1291. runs.push({text: title, bold: true, "fontColor": "black",
  1292. size: "SIZE_DEFAULT",
  1293. style: "STYLE_TEXT",
  1294. });
  1295. */
  1296.  
  1297. hDom.data = Object.assign({}, hDom.data, { channelTitleText: { runs: runs2 }, rSk0e: 1 });
  1298.  
  1299. byPassCheckStore.delete(rchannelNameDOM);
  1300. }
  1301.  
  1302.  
  1303.  
  1304. })
  1305. }
  1306.  
  1307.  
  1308. }
  1309. }
  1310. return browseId
  1311. }
  1312.  
  1313. let firstDOMCheck = false;
  1314. const firstDOMChecker = isMobile ? () => {
  1315.  
  1316. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1317. const channelNameDOMData = (channelNameDOM || 0).data;
  1318.  
  1319. if (channelNameDOMData) {
  1320. let mainChannelUrl = null;
  1321. let mainFormattedNameUrl = null;
  1322. let mainChannelText = null;
  1323. let mainFormattedNameText = null;
  1324.  
  1325. try {
  1326. mainChannelUrl = channelUrlUnify(channelNameDOMData.channelUrl)
  1327. mainFormattedNameUrl = channelUrlUnify(channelNameDOMData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  1328. mainChannelText = channelNameDOMData.channelName
  1329. mainFormattedNameText = channelNameDOMData.title.runs[0].text
  1330. } catch (e) { }
  1331.  
  1332. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1333.  
  1334.  
  1335. let channelId = obtainChannelId(mainChannelUrl);
  1336. if (channelId) {
  1337. if (mainChannelText.startsWith('@')) return;
  1338. if (mainChannelText.trim() !== mainChannelText) return;
  1339.  
  1340. displayNameResStore.set(channelId, {
  1341. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1342. externalId: `${channelId}`,
  1343. ownerUrls: [],
  1344. title: mainChannelText,
  1345. vanityChannelUrl: null,
  1346. verified123: true
  1347. });
  1348. }
  1349.  
  1350.  
  1351. }
  1352. }
  1353.  
  1354. } : () => {
  1355.  
  1356. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1357. const channelNameDOMData = (channelNameDOM || 0).__data;
  1358. if (channelNameDOMData) {
  1359. let mainChannelUrl = null;
  1360. let mainFormattedNameUrl = null;
  1361. let mainChannelText = null;
  1362. let mainFormattedNameText = null;
  1363.  
  1364. try {
  1365. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1366. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1367. mainChannelText = channelNameDOMData.channelName.runs[0].text
  1368. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  1369. } catch (e) { }
  1370.  
  1371. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1372.  
  1373. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1374.  
  1375. if (m && m[1] && mainChannelText !== m[1]) {
  1376.  
  1377. let channelId = obtainChannelId(mainChannelUrl);
  1378. if (channelId) {
  1379. if (mainChannelText.startsWith('@')) return;
  1380. if (mainChannelText.trim() !== mainChannelText) return;
  1381.  
  1382. displayNameResStore.set(channelId, {
  1383. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1384. externalId: `${channelId}`,
  1385. ownerUrls: [],
  1386. title: mainChannelText,
  1387. vanityChannelUrl: null,
  1388. verified123: true
  1389. });
  1390. }
  1391.  
  1392. }
  1393. }
  1394. }
  1395.  
  1396. };
  1397.  
  1398. // let newAnchorAdded = false;
  1399. /*
  1400. const intersectionobserver = new IntersectionObserver((entries) => {
  1401. let anchorAppear = false;
  1402. for (const entry of entries) {
  1403. if (entry.isIntersecting === true) {
  1404. anchorAppear = true;
  1405. break;
  1406. }
  1407. }
  1408. if (anchorAppear && newAnchorAdded) {
  1409. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1410. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1411. }
  1412. }, {
  1413. rootMargin:"0px 0px 0px 0px",
  1414. threshold:1
  1415. })
  1416. */
  1417.  
  1418.  
  1419. /* globals WeakRef:false */
  1420.  
  1421. /** @type {(o: Object | null) => WeakRef | null} */
  1422. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1423.  
  1424. /** @type {(wr: Object | null) => Object | null} */
  1425. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1426.  
  1427. let doShortsChecking = false;
  1428.  
  1429. let lastNewAnchorLastWR = null;
  1430.  
  1431. let domCheckTimeStamp = 0;
  1432.  
  1433. const mutexForDOMMutations = new Mutex();
  1434.  
  1435. const byPassCheckStore = new WeakSet();
  1436.  
  1437. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  1438. for (const mutation of mutations) {
  1439. const target = mutation.target;
  1440. if (!target) continue;
  1441. const rchannelName = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  1442. if (!rchannelName) continue;
  1443. if ((rchannelName.data || 0).rSk0e) continue;
  1444. const channelId = rchannelName.getAttribute('jkrgy');
  1445. if (channelId) {
  1446. if (byPassCheckStore.has(rchannelName)) continue;
  1447. const object = channelIdToHandle.get(channelId);
  1448. if (object && object.handleText && !object.justPossible) {
  1449. const textDom = ((rchannelName.$ || 0).text || 0);
  1450. if (textDom) {
  1451. let t = textDom.textContent.trim()
  1452. if (t === object.handleText || t === '') {
  1453. rchannelName.removeAttribute('jkrgy');
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }
  1459. })
  1460.  
  1461. let domCheckScheduledForShorts = false;
  1462. const domCheckSelectorForShorts = [
  1463. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  1464. ].join(', ');
  1465. const domCheckerForShorts = () => {
  1466.  
  1467. if (domCheckScheduledForShorts) return;
  1468. if (document.querySelector(domCheckSelectorForShorts) === null) {
  1469. return;
  1470. }
  1471. domCheckScheduledForShorts = true;
  1472.  
  1473. mutexForDOMMutations.lockWith(lockResolve => {
  1474.  
  1475.  
  1476. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  1477.  
  1478.  
  1479. domCheckScheduledForShorts = false;
  1480.  
  1481. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  1482. if (nodes.length === 0) {
  1483. lockResolve();
  1484. return;
  1485. }
  1486.  
  1487. for (const node of nodes) {
  1488.  
  1489. const rchannelName = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  1490. if (rchannelName) {
  1491. mutObserverForShortsChannelName.observe(rchannelName, {
  1492. childList: true,
  1493. subtree: true
  1494. });
  1495. let channelId = '';
  1496. byPassCheckStore.add(rchannelName);
  1497. channelId = checkShortsChannelName(rchannelName);
  1498. rchannelName.setAttribute('jkrgy', channelId || '');
  1499. }
  1500.  
  1501. }
  1502.  
  1503. lockResolve();
  1504.  
  1505. // }, 80);
  1506.  
  1507.  
  1508. })
  1509.  
  1510. }
  1511.  
  1512. let domCheckScheduled = false;
  1513. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])';
  1514. const domChecker = () => {
  1515.  
  1516. doShortsChecking && domCheckerForShorts();
  1517.  
  1518. if (domCheckScheduled) return;
  1519. if (document.querySelector(domCheckSelector) === null) {
  1520. return;
  1521. }
  1522. domCheckScheduled = true;
  1523.  
  1524. mutexForDOMMutations.lockWith(lockResolve => {
  1525. domCheckScheduled = false;
  1526.  
  1527. const newAnchors = document.querySelectorAll(domCheckSelector);
  1528. if (newAnchors.length === 0) {
  1529. lockResolve();
  1530. return;
  1531. }
  1532.  
  1533. const cNewAnchorFirst = newAnchors[0]; // non-null
  1534. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1535. /** @type {HTMLElement | null} */
  1536. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1537. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1538.  
  1539. const ltDOMCheck = domCheckTimeStamp;
  1540. const ctDOMCheck = Date.now();
  1541. domCheckTimeStamp = ctDOMCheck;
  1542.  
  1543. if (!firstDOMCheck) {
  1544. firstDOMCheck = true;
  1545. USE_CHANNEL_META && firstDOMChecker();
  1546. }
  1547.  
  1548. const isDocumentModifying = ctDOMCheck - ltDOMCheck < 230;
  1549.  
  1550. Promise.resolve()
  1551. .then(() => {
  1552. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1553.  
  1554. if (isDocumentModifying) {
  1555.  
  1556. } else {
  1557. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1558. mutex.nextIndex = 0;
  1559. }
  1560. }
  1561.  
  1562. /*
  1563. if (mutex.nextIndex === 0) {
  1564. // no change
  1565. } else if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  1566. mutex.nextIndex = 0; // highest priority
  1567. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  1568. mutex.nextIndex = Math.floor(mutex.nextIndex / 2); // relatively higher priority
  1569. }
  1570. */
  1571. }
  1572. }).then(() => {
  1573.  
  1574. // newAnchorAdded = true;
  1575. for (const anchor of newAnchors) {
  1576. // author-text or name
  1577. // normal url: /channel/xxxxxxx
  1578. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1579. const href = anchor.getAttribute('href');
  1580. const channelId = obtainChannelId(href); // string, can be empty
  1581. anchor.setAttribute('jkrgy', channelId);
  1582. // intersectionobserver.unobserve(anchor);
  1583. // intersectionobserver.observe(anchor); // force first occurance
  1584. domCheckAsync(anchor, href, channelId);
  1585. }
  1586.  
  1587. }).then(lockResolve).catch(e => {
  1588. lockResolve();
  1589. console.warn(e);
  1590. });
  1591.  
  1592. });
  1593.  
  1594.  
  1595. };
  1596.  
  1597.  
  1598. /** @type {MutationObserver | null} */
  1599. let domObserver = null;
  1600.  
  1601. /** @type {(callback: (event: Event)=>{})} */
  1602. const onPageFetched = isMobile ? (callback) => {
  1603.  
  1604. let state = 0;
  1605.  
  1606. window.addEventListener('state-change', function (evt) {
  1607. if (state === 1) return; // ignore intermediate events
  1608. state = 1; // before value: 0 or 2;
  1609. callback(evt);
  1610. }, false);
  1611.  
  1612. window.addEventListener('state-navigateend', function (evt) { // fallback
  1613. let inSeq = state === 1;
  1614. state = 2; // 2 when loaded
  1615. if (!inSeq) callback(evt);
  1616. }, false);
  1617.  
  1618. } : (callback) => {
  1619.  
  1620. let state = 0;
  1621.  
  1622. document.addEventListener('yt-page-data-fetched', function (evt) {
  1623. if (state === 1) return; // ignore intermediate events if any
  1624. state = 1; // before value: 0 or 2;
  1625. callback(evt);
  1626. }, false);
  1627.  
  1628. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1629. let inSeq = state === 1;
  1630. state = 2; // 2 when loaded
  1631. if (!inSeq) callback(evt);
  1632. }, false);
  1633.  
  1634. };
  1635.  
  1636. /**
  1637. *
  1638. * @param {Node} app
  1639. * @returns
  1640. */
  1641. function setupOnPageFetched(app) {
  1642.  
  1643. firstDOMCheck = false;
  1644.  
  1645. if (!cfg['INNERTUBE_API_KEY']) {
  1646. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1647. return;
  1648. }
  1649.  
  1650. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  1651. doShortsChecking = true;
  1652. } else {
  1653. doShortsChecking = false;
  1654. }
  1655.  
  1656. if (!domObserver) {
  1657. domObserver = new MutationObserver(domChecker);
  1658. } else {
  1659. domObserver.takeRecords();
  1660. domObserver.disconnect();
  1661. }
  1662.  
  1663. domObserver.observe(app, { childList: true, subtree: true });
  1664. domChecker();
  1665.  
  1666. }
  1667.  
  1668. /**
  1669. *
  1670. * @param {Object|null} dest
  1671. * @param {Object} ytcfg
  1672. * @param {string[]} keys
  1673. * @returns
  1674. */
  1675. function getYtConfig(dest, ytcfg, keys) {
  1676. dest = dest || {};
  1677. if (typeof ytcfg.get === 'function') { // mobile
  1678. for (const key of keys) {
  1679. dest[key] = ytcfg.get(key);
  1680. }
  1681. } else {
  1682. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  1683. for (const key of keys) {
  1684. dest[key] = cfgData[key];
  1685. }
  1686. }
  1687. return dest;
  1688. }
  1689.  
  1690. /** @type { (evt: Object) => Element | null } */
  1691. const getPageApp = isMobile
  1692. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  1693. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  1694.  
  1695. onPageFetched(async (evt) => {
  1696. const app = getPageApp(evt);
  1697. console.assert(app);
  1698. const ytcfg = ((window || 0).ytcfg || 0);
  1699. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']);
  1700. setupOnPageFetched(app);
  1701. });
  1702.  
  1703. })({ Promise, fetch, JSON, Request, AbortController, setTimeout, clearTimeout });