Restore YouTube Username from Handle to Custom

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

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

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