Restore YouTube Username from Handle to Custom

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

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

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