Restore YouTube Username from Handle to Custom

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

当前为 2023-06-30 提交的版本,查看 最新版本

  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.6.2
  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.  
  155. const { Promise, fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  156.  
  157. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  158. const controller = new AbortController();
  159. let cid = setTimeout(() => {
  160. if (cid >= 1) {
  161. cid = 0;
  162. controller.abort();
  163. }
  164. }, timeout);
  165. let r = controller.signal;
  166. r.clearTimeout = () => {
  167. if (cid >= 1) {
  168. clearTimeout(cid);
  169. cid = 0;
  170. }
  171. }
  172. return r;
  173.  
  174. } : () => { };
  175.  
  176. const fxOperator = (proto, propertyName) => {
  177. let propertyDescriptorGetter = null;
  178. try {
  179. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  180. // https://github.com/cyfung1031/userscript-supports/issues/9
  181. // .parentNode becomes DocumentFragment
  182. /**
  183. *
  184. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  185. *
  186. * e.g. ytd-comment-renderer#comment > div#body
  187. *
  188. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  189. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  190. *
  191. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  192. *
  193. * Alternative way: ytCustomElement.$.xxxxxxx
  194. *
  195. */
  196. } catch (e) { }
  197. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  198. };
  199.  
  200. const fxAPI = (proto, propertyName) => {
  201. const methodFunc = proto[propertyName];
  202. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  203. };
  204.  
  205. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  206. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  207. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  208.  
  209. const elementQS = fxAPI(Element.prototype, 'querySelector');
  210. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  211.  
  212. /*
  213.  
  214.  
  215. init
  216.  
  217. initialdata
  218. state-progress
  219. state-responsereceived
  220. player-autonav-pause
  221. state-change
  222. state-navigateend
  223. player-initialized
  224. renderer-module-load-start
  225. video-data-change
  226. player-state-change
  227. updateui
  228. renderer-module-load-end -> channel owner DOM available
  229. player-autonav-pause
  230. updateui
  231. renderer-module-load-start
  232. updateui
  233. renderer-module-load-end
  234.  
  235.  
  236. playing
  237.  
  238. h5player.video-progress
  239. h5player.video-progress
  240. h5player.video-progress
  241. h5player.video-progress
  242. ...
  243.  
  244.  
  245.  
  246.  
  247. navigate new video
  248.  
  249. state-navigatestart
  250. state-change => channel owener DOM vanished
  251. state-progress
  252. ...
  253. h5player.player-state-change
  254. h5player.video-data-change
  255. h5player.player-state-change
  256. h5player.muted-autoplay-change
  257. h5player.volume-change
  258. h5player.video-data-change
  259. h5player.volume-change
  260. ...
  261.  
  262. state-progress
  263. ...
  264.  
  265. state-progress => channel owner DOM appear [just before state-responsereceived]
  266. state-responsereceived
  267.  
  268. video-data-change
  269. state-change
  270. state-navigateend
  271.  
  272.  
  273.  
  274.  
  275. UX interaction
  276.  
  277. user-activity
  278. player-autonav-pause
  279.  
  280.  
  281.  
  282.  
  283.  
  284. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  285.  
  286. EventTarget.prototype.dispatchEvent = function (ev) {
  287. if (ev instanceof Event) {
  288. if (ev.type === 'video-progress') { } else {
  289. console.log(ev.type, this, ev.target)
  290. if (ev.target === null) {
  291. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  292. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  293. }
  294. }
  295. }
  296. return this.uhfsE.apply(this, arguments);
  297. }
  298.  
  299.  
  300.  
  301. */
  302.  
  303. const isMobile = location.hostname === 'm.youtube.com';
  304.  
  305. const cfg = {};
  306. class Mutex {
  307.  
  308. constructor() {
  309. this.p = Promise.resolve()
  310. }
  311.  
  312. /**
  313. * @param {(lockResolve: () => void)} f
  314. */
  315. lockWith(f) {
  316. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  317. }
  318.  
  319. }
  320.  
  321. class OrderedMutex extends Mutex {
  322. constructor() {
  323. super();
  324. this.nextIndex = 0;
  325. this.arr = [];
  326. this.lockFunc = resolve => {
  327. if (this.arr.length >= 1) {
  328. let f = this.arr[0];
  329. if (typeof f === 'function') {
  330. this.arr.shift();
  331. if (this.nextIndex > 0) this.nextIndex--;
  332. f(resolve);
  333. return;
  334. } else {
  335. // reset if unknown error
  336. this.arr.length = 0;
  337. this.nextIndex = 0;
  338. }
  339. }
  340. resolve();
  341. };
  342. }
  343. /**
  344. * @param {(lockResolve: () => void)} f
  345. */
  346. add(f) {
  347. if (this.nextIndex === this.arr.length) {
  348. this.arr.push(f); this.nextIndex++;
  349. } else {
  350. this.arr.splice(this.nextIndex++, 0, f);
  351. }
  352. this.lockWith(this.lockFunc);
  353. }
  354. }
  355. // usage: run network request one by one
  356. const mutex = new OrderedMutex();
  357.  
  358. //
  359. /**
  360. * usage: cache the network result per web application instance.
  361. * @type {Map<string, AsyncValue | Object>} */
  362. const displayNameResStore = new Map();
  363.  
  364. /**
  365. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  366. * @type {WeakMap<Function, Function>} */
  367. const dataChangedFuncStore = new WeakMap();
  368.  
  369. /**
  370. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  371. * @type {Map<string, AsyncValue | string>} */
  372. const handleToChannelId = new Map();
  373.  
  374. /**
  375. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  376. * @type {Map<string, ChannelIdToHandleResult>} */
  377. const channelIdToHandle = new Map();
  378.  
  379. class AsyncValue {
  380. constructor() {
  381. this.__value__ = null;
  382. this.__resolve__ = null;
  383. this.__promise__ = new Promise(resolve => {
  384. this.__resolve__ = resolve;
  385. });
  386. }
  387. setValue(value) {
  388. const promise = this.__promise__;
  389. if (promise === null) throw 'Value has already been set.';
  390. this.__value__ = value;
  391. this.__promise__ = null;
  392. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  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. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  440.  
  441. const signal = timeoutSignal(4000);
  442.  
  443. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  444. "method": "POST",
  445. "mode": "same-origin",
  446. "credentials": "omit",
  447.  
  448. referrerPolicy: "no-referrer",
  449. cache: "default", // no effect on POST request
  450. // cache: "force-cache",
  451. redirect: "error", // there shall be no redirection in this API request
  452. integrity: "",
  453. keepalive: false,
  454. signal,
  455.  
  456. "headers": {
  457. "Content-Type": "application/json", // content type of the body data in POST request
  458. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  459. // X-Youtube-Bootstrap-Logged-In: false,
  460. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  461. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  462.  
  463. "Accept": "application/json",
  464. },
  465. "body": JSON.stringify({
  466. "context": {
  467. "client": {
  468. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  469. "clientName": "MWEB", // "WEB", "MWEB"
  470. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  471. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  472. "playerType": "UNIPLAYER",
  473. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  474. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  475. "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",
  476. "mainAppWebInfo": {
  477. "graftUrl": `/channel/${channelId}`,
  478. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  479. "isWebNativeShareAvailable": true
  480. }
  481. },
  482. "user": {
  483. "lockedSafetyMode": false
  484. },
  485. "request": {
  486. "useSsl": true,
  487. "internalExperimentFlags": [],
  488. "consistencyTokenJars": []
  489. }
  490. },
  491. "browseId": `${channelId}`
  492. })
  493. })).then(res => {
  494. signal && signal.clearTimeout && signal.clearTimeout();
  495. onDownloaded();
  496. return res.json();
  497. }).then(resJson => {
  498. let resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  499. onResulted(resultInfo);
  500. }).catch(onError);
  501.  
  502. };
  503.  
  504. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  505.  
  506. const signal = timeoutSignal(4000);
  507. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  508. // YouTube RSS Response - public, max-age=900
  509.  
  510. "method": "GET",
  511. "mode": "same-origin",
  512. "credentials": "omit",
  513.  
  514. referrerPolicy: "no-referrer",
  515. cache: "default",
  516. // cache: "no-cache",
  517. redirect: "error", // there shall be no redirection in this API request
  518. integrity: "",
  519. keepalive: false,
  520. signal,
  521.  
  522. "headers": {
  523. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  524. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  525. // seems YouTube RSS Feeds server insists its own Cache-Control.
  526.  
  527. // "Content-Type": "text/xml; charset=UTF-8",
  528. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  529. // X-Youtube-Bootstrap-Logged-In: false,
  530. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  531. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  532.  
  533. "Accept": "text/xml",
  534. }
  535. }).then(res => {
  536. signal && signal.clearTimeout && signal.clearTimeout();
  537. onDownloaded();
  538. return res.text();
  539. }).then(resText => {
  540. let eIdx = resText.indexOf('<entry>');
  541. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  542.  
  543. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  544. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  545. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  546. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  547.  
  548.  
  549. let name, uri, mt;
  550.  
  551. // ===============================================================
  552.  
  553. /* removed in 2023.06.30 */
  554.  
  555.  
  556. // ===============================================================
  557.  
  558.  
  559. const wIdx1 = mText.indexOf('<author>');
  560. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  561.  
  562. if (wIdx1 > 0 && wIdx2 > 0) {
  563. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  564. const template = document.createElement('template');
  565. template.innerHTML = qText;
  566. /** @type {HTMLElement | null} */
  567. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  568. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  569. const nodeName = authorChild.nodeName;
  570. if (nodeName === 'NAME') name = authorChild.textContent;
  571. else if (nodeName === 'URI') {
  572. uri = authorChild.textContent;
  573. mt = obtainChannelId(uri);
  574. }
  575. }
  576. }
  577.  
  578. if (!name && !uri) {
  579.  
  580. // fallback
  581.  
  582. const parser = new DOMParser();
  583. const xmlDoc = parser.parseFromString(mText, "text/xml");
  584.  
  585. // const author = xmlDoc.querySelector("author");
  586.  
  587. // https://extendsclass.com/xpath-tester.html
  588.  
  589. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  590.  
  591. let authorChild;
  592. while ((authorChild = authorChilds.iterateNext()) !== null) {
  593. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  594. else if (authorChild.nodeName === 'uri') {
  595. uri = authorChild.textContent;
  596. mt = obtainChannelId(uri)
  597. }
  598. }
  599.  
  600. try {
  601. xmlDoc.firstChild.remove();
  602. } catch (e) { }
  603.  
  604. }
  605.  
  606.  
  607.  
  608.  
  609. let res = null;
  610.  
  611. if (name && uri && mt && mt === channelId) {
  612.  
  613.  
  614. let object = channelIdToHandle.get(mt);
  615.  
  616. if (object) {
  617.  
  618. if (object.handleText === name) channelIdToHandle.delete(mt);
  619. else {
  620. object.justPossible = false; // ignore @handle checking
  621.  
  622. res = {
  623. "title": name,
  624. "externalId": mt,
  625. "ownerUrls": [
  626. `http://www.youtube.com/${object.handleText}`
  627. ],
  628. "channelUrl": uri,
  629. "vanityChannelUrl": `http://www.youtube.com/${object.handleText}`
  630. };
  631.  
  632. }
  633. }
  634. }
  635.  
  636. onResulted(res);
  637.  
  638. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  639. // onResulted(resultInfo);
  640. }).catch(onError);
  641.  
  642.  
  643.  
  644. }
  645.  
  646. /**
  647. *
  648. * @param {string} channelId
  649. */
  650. function stackNewRequest(channelId) {
  651.  
  652. mutex.add(lockResolve => {
  653.  
  654. let bResult = displayNameResStore.get(channelId);
  655. if (!(bResult instanceof AsyncValue)) {
  656. // resolved or removed
  657. lockResolve(); lockResolve = null;
  658. return;
  659. }
  660.  
  661. let setResult = (result) => {
  662. setResult = null;
  663. if (!result) {
  664. bResult.fetchingState = 0;
  665. bResult.setValue(null);
  666. displayNameResStore.delete(channelId); // create another network response in the next request
  667. } else {
  668. bResult.fetchingState = 4;
  669. bResult.setValue(result);
  670. displayNameResStore.set(channelId, result); // update store result to resolved value
  671. }
  672. bResult = null;
  673. }
  674.  
  675. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  676. // request is already done. no need to stack any request
  677. lockResolve(); lockResolve = null;
  678. return;
  679. }
  680.  
  681. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  682. // element has already been removed
  683. lockResolve(); lockResolve = null;
  684. setResult(null);
  685. return;
  686. }
  687.  
  688. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  689.  
  690. bResult.fetchingState = 2;
  691.  
  692.  
  693. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  694. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  695. const fetcher = USE_RSS_FETCHER && fetcherRSS && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  696. fetcher(channelId, () => {
  697. bResult.fetchingState = 3;
  698. lockResolve();
  699. lockResolve = null;
  700. }, resultInfo => {
  701.  
  702. if (!resultInfo) {
  703. // invalid json format
  704. setResult(null);
  705. return;
  706. }
  707.  
  708. cacheHandleToChannel(resultInfo, channelId);
  709.  
  710. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  711.  
  712. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  713.  
  714. setResult(displayNameRes);
  715. }, e => {
  716. lockResolve && lockResolve();
  717. console.warn(e);
  718. setResult && setResult(null);
  719. });
  720.  
  721. });
  722.  
  723. }
  724.  
  725. /**
  726. *
  727. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  728. * @returns Example: _\@yr__kd_
  729. */
  730. function urlToHandle(url) {
  731.  
  732. if (typeof url !== 'string') return '';
  733. let i = url.indexOf('.youtube.com/');
  734. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  735. else if (url.charAt(0) === '/') url = url.substring(1);
  736. return isDisplayAsHandle(url) ? url : '';
  737.  
  738. }
  739.  
  740. /**
  741. *
  742. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  743. * @returns {Promise<DisplayNameResultObject | null>}
  744. */
  745. async function getDisplayName(channelId) {
  746.  
  747. let cache = displayNameResStore.get(channelId);
  748. let isStackNewRequest = false;
  749.  
  750. /** @type {AsyncValue | null | undefined} */
  751. let aResult;
  752.  
  753. if (cache instanceof AsyncValue) {
  754. aResult = cache;
  755. if (aResult.fetchingState >= 2) {
  756. // aResult.fetchingState
  757. // 2: network fetch started
  758. // 3: network fetch ended
  759. // isStackNewRequest = false;
  760. } else {
  761. // 0: invalid before
  762. // 1: scheduled but not yet fetch
  763. isStackNewRequest = true;
  764. }
  765. } else if (cache) {
  766. // resolved result
  767. return cache;
  768. } else {
  769. // else no cached value found
  770. aResult = new AsyncValue();
  771. displayNameResStore.set(channelId, aResult);
  772. isStackNewRequest = true;
  773. }
  774.  
  775. if (isStackNewRequest) {
  776. aResult.fetchingState = 1;
  777. stackNewRequest(channelId);
  778. }
  779. return await aResult.getValue();
  780. }
  781.  
  782.  
  783. /**
  784. *
  785. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  786. * @returns
  787. */
  788. const obtainChannelId = (href) => {
  789. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  790. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  791. return !m ? '' : (m[1] || '');
  792. };
  793.  
  794.  
  795. /**
  796. *
  797. * @param {Element} Node
  798. */
  799. const resetWhenDataChanged = (ytElm) => {
  800. if (ytElm instanceof Element) {
  801. const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  802. if ((anchors || 0).length >= 1 && (ytElm.data || 0).jkrgx !== 1) {
  803. for (const anchor of anchors) {
  804. anchor.removeAttribute('jkrgy');
  805. }
  806. }
  807. }
  808. }
  809.  
  810. /**
  811. *
  812. * @param {Function} dataChanged original dataChanged function
  813. * @returns new dataChanged function
  814. */
  815. const dataChangeFuncProducer = (dataChanged) => {
  816. return function () {
  817. resetWhenDataChanged(this);
  818. return dataChanged.apply(this, arguments);
  819. }
  820. };
  821.  
  822. /**
  823. *
  824. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  825. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  826. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  827. * @returns
  828. */
  829. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  830.  
  831. let currentHref = anchor.getAttribute('href');
  832. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  833.  
  834. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  835.  
  836. };
  837.  
  838. /**
  839. *
  840. * @param {string} currentDisplayed
  841. * @param {DisplayNameResultObject} fetchResult
  842. * @returns
  843. */
  844. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  845.  
  846. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  847.  
  848. const currentDisplayTrimmed = currentDisplayed.trim();
  849. let match = false;
  850. if (verified123) {
  851. match = true;
  852. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  853. match = true;
  854. } else if ((ownerUrls || 0).length >= 1) {
  855. for (const ownerUrl of ownerUrls) {
  856. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  857. match = true;
  858. break;
  859. }
  860. }
  861. }
  862. if (match) {
  863. return currentDisplayTrimmed;
  864. }
  865. return '';
  866.  
  867. };
  868.  
  869. /**
  870. *
  871. *
  872.  
  873. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  874.  
  875. - Is between 3-30 characters
  876. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  877. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  878. - Is not URL-like or phone number-like
  879. - Is not already being used
  880. - Follows YouTube's Community Guidelines
  881.  
  882. ### Handle automatically generated by YouTube
  883. - `@user-XXXX`
  884. - without dot (.)
  885. *
  886. * @param {string} text
  887. * @returns
  888. */
  889. const isDisplayAsHandle = (text) => {
  890.  
  891. if (typeof text !== 'string') return false;
  892. if (text.length < 4) return false;
  893. if (text.indexOf('@') < 0) return false;
  894. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  895.  
  896. };
  897.  
  898. /**
  899. *
  900. * @param {Object[]} contentTexts
  901. * @param {number} idx
  902. * @returns
  903. */
  904. const contentTextProcess = (contentTexts, idx) => {
  905. const contentText = contentTexts[idx];
  906. const text = (contentText || 0).text;
  907. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  908. if (typeof url === 'string' && typeof text === 'string') {
  909.  
  910. if (!isDisplayAsHandle(text)) return null;
  911. const channelId = obtainChannelId(url);
  912.  
  913. return getDisplayName(channelId).then(fetchResult => {
  914. let resolveResult = null;
  915. if (fetchResult) {
  916. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  917.  
  918. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  919. if (textTrimmed) {
  920. resolveResult = (md) => {
  921. let runs = ((md || 0).contentText || 0).runs;
  922. if (!runs || !runs[idx]) return;
  923. if (runs[idx].text !== text) return;
  924. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  925. md.contentText = Object.assign({}, md.contentText);
  926. };
  927. }
  928. }
  929. return (resolveResult); // function as a Promise
  930. });
  931. }
  932.  
  933. return null;
  934. };
  935.  
  936. /**
  937. *
  938. * @param {ParentNode} parentNode
  939. * @param {Function} callback
  940. */
  941. function findTextNodes(parentNode, callback) {
  942. /**
  943. *
  944. * @param {Node} node
  945. * @returns
  946. */
  947. function traverse(node) {
  948. if (node.nodeType === Node.TEXT_NODE) {
  949. let r = callback(node);
  950. if (r === true) return true;
  951. }
  952.  
  953. let childNode = nodeFirstChild(node);
  954. while (childNode) {
  955. let r = traverse(childNode);
  956. if (r === true) return true;
  957. childNode = nodeNextSibling(childNode);
  958. }
  959. }
  960.  
  961. traverse(parentNode);
  962. }
  963.  
  964. /**
  965. *
  966. * @param {ParentNode} parentNode
  967. * @param {Object[]} contentTexts
  968. * @param {number} aidx
  969. * @returns
  970. */
  971. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  972.  
  973.  
  974. let commentText = elementQS(parentNode, '.comment-text');
  975. if (!commentText) return;
  976. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  977. let currentText = commentText.textContent;
  978. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  979. if (!textMatch) return;
  980.  
  981. const contentText = contentTexts[aidx];
  982.  
  983. /** @type {string} */
  984. const handleText = contentText.text.trim();
  985. /** @type {string | null | undefined} */
  986. let channelId;
  987.  
  988. let cache = handleToChannelId.get(handleText);
  989.  
  990. if (typeof cache === 'string') {
  991. channelId = cache;
  992. } else if (cache instanceof AsyncValue) {
  993. channelId = await cache.getValue();
  994. } else {
  995. const asyncValue = new AsyncValue();
  996. handleToChannelId.set(handleText, asyncValue);
  997. channelId = await asyncValue.getValue(); // note: it could be never resolved
  998. }
  999.  
  1000. if (!channelId) return; // just in case
  1001.  
  1002. if (commentText.isConnected !== true) return; // already removed
  1003. if (commentText.textContent !== currentText) return; // already changed
  1004.  
  1005. const fetchResult = await getDisplayName(channelId);
  1006.  
  1007. if (fetchResult === null) return;
  1008.  
  1009. const { title, externalId } = fetchResult;
  1010. if (externalId !== channelId) return; // channel id must be the same
  1011.  
  1012. let search = contentText.text;
  1013. if (typeof search === 'string') {
  1014.  
  1015. const searchTrimmed = search.trim();
  1016. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1017. contentText.text = search.replace(searchTrimmed, "@" + title);
  1018.  
  1019. findTextNodes(commentText, (textnode) => {
  1020. if (textnode.nodeValue.indexOf(search) >= 0) {
  1021. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1022. return true;
  1023. }
  1024. });
  1025. }
  1026.  
  1027. }
  1028.  
  1029. }
  1030.  
  1031. /**
  1032. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1033. * @type {(anchor: HTMLElement, channelHref: string?, mt: string?)}
  1034. */
  1035. const domCheckAsync = isMobile ? async (anchor, channelHref, mt) => {
  1036.  
  1037. try {
  1038. if (!channelHref || !mt) return;
  1039. let parentNode = nodeParent(anchor);
  1040. while (parentNode instanceof Node) {
  1041. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1042. parentNode = nodeParent(parentNode);
  1043. }
  1044. if (parentNode instanceof Node) { } else return;
  1045.  
  1046. let displayTextDOM = elementQS(parentNode, '.comment-header .comment-title');
  1047. if (!displayTextDOM) return;
  1048. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1049. let airaLabel = anchor.getAttribute('aria-label')
  1050. const parentNodeData = parentNode.data;
  1051. let runs = ((parentNodeData || 0).authorText || 0).runs;
  1052.  
  1053. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  1054.  
  1055. if (!channelIdToHandle.has(mt)) {
  1056. channelIdToHandle.set(mt, {
  1057. handleText: airaLabel.trim(),
  1058. justPossible: true
  1059. })
  1060. }
  1061.  
  1062. const fetchResult = await getDisplayName(mt);
  1063.  
  1064. if (fetchResult === null) return;
  1065.  
  1066. const { title, externalId } = fetchResult;
  1067.  
  1068. if (externalId !== mt) return; // channel id must be the same
  1069.  
  1070. // anchor href might be changed by external
  1071. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1072.  
  1073. let found = false;
  1074.  
  1075. findTextNodes(displayTextDOM, (textnode) => {
  1076. if (textnode.nodeValue === airaLabel) {
  1077. textnode.nodeValue = title;
  1078. found = true;
  1079. return true;
  1080. }
  1081. });
  1082.  
  1083. if (!found) return;
  1084. anchor.setAttribute('aria-label', title);
  1085. runs[0].text = title;
  1086.  
  1087.  
  1088. const contentTexts = (parentNodeData.contentText || 0).runs;
  1089. if (contentTexts && contentTexts.length >= 2) {
  1090. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1091. const contentText = contentTexts[aidx] || 0;
  1092. if (contentText.italics !== true) {
  1093. let isHandle = isDisplayAsHandle(contentText.text);
  1094. if (isHandle) {
  1095. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1096. }
  1097. }
  1098. }
  1099. }
  1100.  
  1101. }
  1102. } catch (e) {
  1103. console.warn(e);
  1104. }
  1105.  
  1106. } : async (anchor, channelHref, mt) => {
  1107.  
  1108. try {
  1109. if (!channelHref || !mt) return;
  1110. let parentNode = nodeParent(anchor);
  1111. while (parentNode instanceof Node) {
  1112. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  1113. parentNode = nodeParent(parentNode);
  1114. }
  1115. if (parentNode instanceof Node) { } else return;
  1116. const authorText = (parentNode.data || 0).authorText;
  1117. const currentDisplayed = (authorText || 0).simpleText;
  1118. if (typeof currentDisplayed !== 'string') return;
  1119. if (!isDisplayAsHandle(currentDisplayed)) return;
  1120.  
  1121. if (!channelIdToHandle.has(mt)) {
  1122. channelIdToHandle.set(mt, {
  1123. handleText: currentDisplayed.trim(),
  1124. justPossible: true
  1125. })
  1126. }
  1127.  
  1128. const oldDataChanged = parentNode.dataChanged;
  1129. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  1130. let newDataChanged = dataChangedFuncStore.get(oldDataChanged);
  1131. if (!newDataChanged) {
  1132. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  1133. newDataChanged.jkrgx = 1;
  1134. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  1135. }
  1136. parentNode.dataChanged = newDataChanged;
  1137. }
  1138.  
  1139. const fetchResult = await getDisplayName(mt);
  1140.  
  1141. if (fetchResult === null) return;
  1142.  
  1143. const { title, externalId } = fetchResult;
  1144.  
  1145. if (externalId !== mt) return; // channel id must be the same
  1146.  
  1147. // anchor href might be changed by external
  1148. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1149.  
  1150. const parentNodeData = parentNode.data;
  1151. const funcPromises = [];
  1152.  
  1153. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1154.  
  1155. if (authorText.simpleText !== currentDisplayed) return;
  1156. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1157. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  1158. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  1159.  
  1160. // the inside hyperlinks will be only converted if its parent author name is handle
  1161. const contentTexts = (parentNodeData.contentText || 0).runs;
  1162. if (contentTexts && contentTexts.length >= 1) {
  1163. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1164. const r = contentTextProcess(contentTexts, aidx);
  1165. if (r instanceof Promise) funcPromises.push(r);
  1166. }
  1167. }
  1168.  
  1169. const md = Object.assign({}, parentNodeData);
  1170. let setBadge = false;
  1171. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  1172. setBadge = true;
  1173. }
  1174. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1175. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  1176. if (setBadge) {
  1177. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  1178. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  1179. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  1180.  
  1181. }
  1182. if (funcPromises.length >= 1) {
  1183. let funcs = await Promise.all(funcPromises);
  1184.  
  1185. for (const func of funcs) {
  1186. if (typeof func === 'function') {
  1187. func(md);
  1188. }
  1189. }
  1190. }
  1191. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  1192. }
  1193.  
  1194. }
  1195. } catch (e) {
  1196. console.warn(e);
  1197. }
  1198.  
  1199. }
  1200.  
  1201. /**
  1202. *
  1203. * @param {string} url
  1204. * @returns
  1205. */
  1206. const channelUrlUnify = (url) => {
  1207.  
  1208. if (typeof url !== 'string') return url; // type unchanged
  1209. let c0 = url.charAt(0);
  1210. if (c0 === '/') return url;
  1211. let i = url.indexOf('.youtube.com/');
  1212. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1213. else if (url.charAt(0) !== '/') url = '/' + url;
  1214. return url
  1215.  
  1216. }
  1217.  
  1218. let firstDOMCheck = false;
  1219. const firstDOMChecker = isMobile ? () => {
  1220.  
  1221. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1222. const channelNameDOMData = (channelNameDOM || 0).data;
  1223.  
  1224. if (channelNameDOMData) {
  1225. let mainChannelUrl = null;
  1226. let mainFormattedNameUrl = null;
  1227. let mainChannelText = null;
  1228. let mainFormattedNameText = null;
  1229.  
  1230. try {
  1231. mainChannelUrl = channelUrlUnify(channelNameDOMData.channelUrl)
  1232. mainFormattedNameUrl = channelUrlUnify(channelNameDOMData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  1233. mainChannelText = channelNameDOMData.channelName
  1234. mainFormattedNameText = channelNameDOMData.title.runs[0].text
  1235. } catch (e) { }
  1236.  
  1237. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1238.  
  1239.  
  1240. let channelId = obtainChannelId(mainChannelUrl);
  1241. if (channelId) {
  1242. if (mainChannelText.startsWith('@')) return;
  1243. if (mainChannelText.trim() !== mainChannelText) return;
  1244.  
  1245. displayNameResStore.set(channelId, {
  1246. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1247. externalId: `${channelId}`,
  1248. ownerUrls: [],
  1249. title: mainChannelText,
  1250. vanityChannelUrl: null,
  1251. verified123: true
  1252. });
  1253. }
  1254.  
  1255.  
  1256. }
  1257. }
  1258.  
  1259. } : () => {
  1260.  
  1261. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1262. const channelNameDOMData = (channelNameDOM || 0).__data;
  1263. if (channelNameDOMData) {
  1264. let mainChannelUrl = null;
  1265. let mainFormattedNameUrl = null;
  1266. let mainChannelText = null;
  1267. let mainFormattedNameText = null;
  1268.  
  1269. try {
  1270. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1271. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1272. mainChannelText = channelNameDOMData.channelName.runs[0].text
  1273. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  1274. } catch (e) { }
  1275.  
  1276. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1277.  
  1278. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1279.  
  1280. if (m && m[1] && mainChannelText !== m[1]) {
  1281.  
  1282. let channelId = obtainChannelId(mainChannelUrl);
  1283. if (channelId) {
  1284. if (mainChannelText.startsWith('@')) return;
  1285. if (mainChannelText.trim() !== mainChannelText) return;
  1286.  
  1287. displayNameResStore.set(channelId, {
  1288. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1289. externalId: `${channelId}`,
  1290. ownerUrls: [],
  1291. title: mainChannelText,
  1292. vanityChannelUrl: null,
  1293. verified123: true
  1294. });
  1295. }
  1296.  
  1297. }
  1298. }
  1299. }
  1300.  
  1301.  
  1302.  
  1303.  
  1304. };
  1305.  
  1306. // let newAnchorAdded = false;
  1307. /*
  1308.  
  1309. const intersectionobserver = new IntersectionObserver((entries) => {
  1310. let anchorAppear = false;
  1311. for (const entry of entries) {
  1312. if (entry.isIntersecting === true) {
  1313. anchorAppear = true;
  1314. break;
  1315. }
  1316. }
  1317. if (anchorAppear && newAnchorAdded) {
  1318. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1319. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1320. }
  1321. }, {
  1322. rootMargin:"0px 0px 0px 0px",
  1323. threshold:1
  1324. })
  1325. */
  1326.  
  1327.  
  1328. /* globals WeakRef:false */
  1329.  
  1330. /** @type {(o: Object | null) => WeakRef | null} */
  1331. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1332.  
  1333. /** @type {(wr: Object | null) => Object | null} */
  1334. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1335.  
  1336. let lastNewAnchorLastWR = null;
  1337.  
  1338. let domCheckTimeStamp = 0;
  1339.  
  1340. const mutexForDOMMutations = new Mutex();
  1341. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])';
  1342.  
  1343. let domCheckScheduled = false;
  1344. const domChecker = () => {
  1345.  
  1346. if (domCheckScheduled) return;
  1347. if (document.querySelector(domCheckSelector) === null) {
  1348. return;
  1349. }
  1350. domCheckScheduled = true;
  1351.  
  1352. mutexForDOMMutations.lockWith(lockResolve => {
  1353. domCheckScheduled = false;
  1354.  
  1355. const newAnchors = document.querySelectorAll(domCheckSelector);
  1356. if (newAnchors.length === 0) {
  1357. lockResolve();
  1358. return;
  1359. }
  1360.  
  1361. const cNewAnchorFirst = newAnchors[0]; // non-null
  1362. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1363. /** @type {HTMLElement | null} */
  1364. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1365. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1366.  
  1367. const ltDOMCheck = domCheckTimeStamp;
  1368. const ctDOMCheck = Date.now();
  1369. domCheckTimeStamp = ctDOMCheck;
  1370.  
  1371. if (!firstDOMCheck) {
  1372. firstDOMCheck = true;
  1373. firstDOMChecker();
  1374. }
  1375.  
  1376. const isDocumentModifying = ctDOMCheck - ltDOMCheck < 230;
  1377.  
  1378. Promise.resolve()
  1379. .then(() => {
  1380. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1381.  
  1382. if (isDocumentModifying) {
  1383.  
  1384. } else {
  1385. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1386. mutex.nextIndex = 0;
  1387. }
  1388. }
  1389.  
  1390. /*
  1391. if (mutex.nextIndex === 0) {
  1392. // no change
  1393. } else if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  1394. mutex.nextIndex = 0; // highest priority
  1395. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  1396. mutex.nextIndex = Math.floor(mutex.nextIndex / 2); // relatively higher priority
  1397. }
  1398. */
  1399. }
  1400. }).then(() => {
  1401.  
  1402. // newAnchorAdded = true;
  1403. for (const anchor of newAnchors) {
  1404. // author-text or name
  1405. // normal url: /channel/xxxxxxx
  1406. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1407. const href = anchor.getAttribute('href');
  1408. const channelId = obtainChannelId(href); // string, can be empty
  1409. anchor.setAttribute('jkrgy', channelId);
  1410. // intersectionobserver.unobserve(anchor);
  1411. // intersectionobserver.observe(anchor); // force first occurance
  1412. domCheckAsync(anchor, href, channelId);
  1413. }
  1414.  
  1415. }).then(lockResolve).catch(e => {
  1416. lockResolve();
  1417. console.warn(e);
  1418. });
  1419.  
  1420. });
  1421.  
  1422.  
  1423. };
  1424.  
  1425.  
  1426. /** @type {MutationObserver | null} */
  1427. let domObserver = null;
  1428.  
  1429. /** @type {(callback: (event: Event)=>{})} */
  1430. const onPageFetched = isMobile ? (callback) => {
  1431.  
  1432. let state = 0;
  1433.  
  1434. window.addEventListener('state-change', function (evt) {
  1435. if (state === 1) return; // ignore intermediate events
  1436. state = 1; // before value: 0 or 2;
  1437. callback(evt);
  1438. }, false);
  1439.  
  1440. window.addEventListener('state-navigateend', function (evt) { // fallback
  1441. let inSeq = state === 1;
  1442. state = 2; // 2 when loaded
  1443. if (!inSeq) callback(evt);
  1444. }, false);
  1445.  
  1446. } : (callback) => {
  1447.  
  1448. let state = 0;
  1449.  
  1450. document.addEventListener('yt-page-data-fetched', function (evt) {
  1451. if (state === 1) return; // ignore intermediate events if any
  1452. state = 1; // before value: 0 or 2;
  1453. callback(evt);
  1454. }, false);
  1455.  
  1456. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1457. let inSeq = state === 1;
  1458. state = 2; // 2 when loaded
  1459. if (!inSeq) callback(evt);
  1460. }, false);
  1461.  
  1462. };
  1463.  
  1464. /**
  1465. *
  1466. * @param {Node} app
  1467. * @returns
  1468. */
  1469. function setupOnPageFetched(app) {
  1470.  
  1471. firstDOMCheck = false;
  1472.  
  1473. if (!cfg['INNERTUBE_API_KEY']) {
  1474. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1475. return;
  1476. }
  1477.  
  1478. if (!domObserver) {
  1479. domObserver = new MutationObserver(domChecker);
  1480. } else {
  1481. domObserver.takeRecords();
  1482. domObserver.disconnect();
  1483. }
  1484.  
  1485. domObserver.observe(app, { childList: true, subtree: true });
  1486. domChecker();
  1487.  
  1488. }
  1489.  
  1490. /**
  1491. *
  1492. * @param {Object|null} dest
  1493. * @param {Object} ytcfg
  1494. * @param {string[]} keys
  1495. * @returns
  1496. */
  1497. function getYtConfig(dest, ytcfg, keys) {
  1498. dest = dest || {};
  1499. if (typeof ytcfg.get === 'function') { // mobile
  1500. for (const key of keys) {
  1501. dest[key] = ytcfg.get(key);
  1502. }
  1503. } else {
  1504. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  1505. for (const key of keys) {
  1506. dest[key] = cfgData[key];
  1507. }
  1508. }
  1509. return dest;
  1510. }
  1511.  
  1512. /** @type { (evt: Object) => Element | null } */
  1513. const getPageApp = isMobile
  1514. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  1515. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  1516.  
  1517. onPageFetched(async (evt) => {
  1518. const app = getPageApp(evt);
  1519. console.assert(app);
  1520. const ytcfg = ((window || 0).ytcfg || 0);
  1521. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']);
  1522. setupOnPageFetched(app);
  1523. });
  1524.  
  1525. })({ Promise, fetch, JSON, Request, AbortController, setTimeout, clearTimeout });