Restore YouTube Username from Handle to Custom

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

目前为 2023-06-28 提交的版本。查看 最新版本

  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.19
  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. *
  598. * @param {Element} Node
  599. */
  600. const resetWhenDataChanged = (ytElm) => {
  601. if (ytElm instanceof Element) {
  602. const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  603. if ((anchors || 0).length >= 1 && (ytElm.data || 0).jkrgx !== 1) {
  604. for (const anchor of anchors) {
  605. anchor.removeAttribute('jkrgy');
  606. }
  607. }
  608. }
  609. }
  610.  
  611. /**
  612. *
  613. * @param {Function} dataChanged original dataChanged function
  614. * @returns new dataChanged function
  615. */
  616. const dataChangeFuncProducer = (dataChanged) => {
  617. return function () {
  618. resetWhenDataChanged(this);
  619. return dataChanged.apply(this, arguments);
  620. }
  621. };
  622.  
  623. /**
  624. *
  625. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  626. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  627. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  628. * @returns
  629. */
  630. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  631.  
  632. let currentHref = anchor.getAttribute('href');
  633. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  634.  
  635. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  636.  
  637. };
  638.  
  639. /**
  640. *
  641. * @param {string} currentDisplayed
  642. * @param {DisplayNameResultObject} fetchResult
  643. * @returns
  644. */
  645. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  646.  
  647. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  648.  
  649. const currentDisplayTrimmed = currentDisplayed.trim();
  650. let match = false;
  651. if (verified123) {
  652. match = true;
  653. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  654. match = true;
  655. } else if ((ownerUrls || 0).length >= 1) {
  656. for (const ownerUrl of ownerUrls) {
  657. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  658. match = true;
  659. break;
  660. }
  661. }
  662. }
  663. if (match) {
  664. return currentDisplayTrimmed;
  665. }
  666. return '';
  667.  
  668. };
  669.  
  670. /**
  671. *
  672. *
  673.  
  674. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  675.  
  676. - Is between 3-30 characters
  677. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  678. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  679. - Is not URL-like or phone number-like
  680. - Is not already being used
  681. - Follows YouTube's Community Guidelines
  682.  
  683. ### Handle automatically generated by YouTube
  684. - `@user-XXXX`
  685. - without dot (.)
  686. *
  687. * @param {string} text
  688. * @returns
  689. */
  690. const isDisplayAsHandle = (text) => {
  691.  
  692. if (typeof text !== 'string') return false;
  693. if (text.length < 4) return false;
  694. if (text.indexOf('@') < 0) return false;
  695. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  696.  
  697. };
  698.  
  699. /**
  700. *
  701. * @param {Object[]} contentTexts
  702. * @param {number} idx
  703. * @returns
  704. */
  705. const contentTextProcess = (contentTexts, idx) => {
  706. const contentText = contentTexts[idx];
  707. const text = (contentText || 0).text;
  708. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  709. if (typeof url === 'string' && typeof text === 'string') {
  710.  
  711. if (!isDisplayAsHandle(text)) return null;
  712. const channelId = obtainChannelId(url);
  713.  
  714. return getDisplayName(channelId).then(fetchResult => {
  715. let resolveResult = null;
  716. if (fetchResult) {
  717. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  718.  
  719. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  720. if (textTrimmed) {
  721. resolveResult = (md) => {
  722. let runs = ((md || 0).contentText || 0).runs;
  723. if (!runs || !runs[idx]) return;
  724. if (runs[idx].text !== text) return;
  725. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  726. md.contentText = Object.assign({}, md.contentText);
  727. };
  728. }
  729. }
  730. return (resolveResult); // function as a Promise
  731. });
  732. }
  733.  
  734. return null;
  735. };
  736.  
  737. /**
  738. *
  739. * @param {ParentNode} parentNode
  740. * @param {Function} callback
  741. */
  742. function findTextNodes(parentNode, callback) {
  743. /**
  744. *
  745. * @param {Node} node
  746. * @returns
  747. */
  748. function traverse(node) {
  749. if (node.nodeType === Node.TEXT_NODE) {
  750. let r = callback(node);
  751. if (r === true) return true;
  752. }
  753.  
  754. let childNode = nodeFirstChild(node);
  755. while (childNode) {
  756. let r = traverse(childNode);
  757. if (r === true) return true;
  758. childNode = nodeNextSibling(childNode);
  759. }
  760. }
  761.  
  762. traverse(parentNode);
  763. }
  764.  
  765. /**
  766. *
  767. * @param {ParentNode} parentNode
  768. * @param {Object[]} contentTexts
  769. * @param {number} aidx
  770. * @returns
  771. */
  772. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  773.  
  774.  
  775. let commentText = elementQS(parentNode, '.comment-text');
  776. if (!commentText) return;
  777. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  778. let currentText = commentText.textContent;
  779. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  780. if (!textMatch) return;
  781.  
  782. const contentText = contentTexts[aidx];
  783.  
  784. /** @type {string} */
  785. const handleText = contentText.text.trim();
  786. /** @type {string | null | undefined} */
  787. let channelId;
  788.  
  789. let cache = handleToChannelId.get(handleText);
  790.  
  791. if (typeof cache === 'string') {
  792. channelId = cache;
  793. } else if (cache instanceof AsyncValue) {
  794. channelId = await cache.getValue();
  795. } else {
  796. const asyncValue = new AsyncValue();
  797. handleToChannelId.set(handleText, asyncValue);
  798. channelId = await asyncValue.getValue(); // note: it could be never resolved
  799. }
  800.  
  801. if (!channelId) return; // just in case
  802.  
  803. if (commentText.isConnected !== true) return; // already removed
  804. if (commentText.textContent !== currentText) return; // already changed
  805.  
  806. const fetchResult = await getDisplayName(channelId);
  807.  
  808. if (fetchResult === null) return;
  809.  
  810. const { title, externalId } = fetchResult;
  811. if (externalId !== channelId) return; // channel id must be the same
  812.  
  813. let search = contentText.text;
  814. if (typeof search === 'string') {
  815.  
  816. const searchTrimmed = search.trim();
  817. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  818. contentText.text = search.replace(searchTrimmed, "@" + title);
  819.  
  820. findTextNodes(commentText, (textnode) => {
  821. if (textnode.nodeValue.indexOf(search) >= 0) {
  822. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  823. return true;
  824. }
  825. });
  826. }
  827.  
  828. }
  829.  
  830. }
  831.  
  832. /**
  833. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  834. * @type {(anchor: HTMLElement, channelHref: string?, mt: string?)}
  835. */
  836. const domCheckAsync = isMobile ? async (anchor, channelHref, mt) => {
  837.  
  838. try {
  839. if (!channelHref || !mt) return;
  840. let parentNode = nodeParent(anchor);
  841. while (parentNode instanceof Node) {
  842. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  843. parentNode = nodeParent(parentNode);
  844. }
  845. if (parentNode instanceof Node) { } else return;
  846.  
  847. let displayTextDOM = elementQS(parentNode, '.comment-header .comment-title');
  848. if (!displayTextDOM) return;
  849. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  850. let airaLabel = anchor.getAttribute('aria-label')
  851. const parentNodeData = parentNode.data;
  852. let runs = ((parentNodeData || 0).authorText || 0).runs;
  853.  
  854. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  855.  
  856. const fetchResult = await getDisplayName(mt);
  857.  
  858. if (fetchResult === null) return;
  859.  
  860. const { title, externalId } = fetchResult;
  861.  
  862. if (externalId !== mt) return; // channel id must be the same
  863.  
  864. // anchor href might be changed by external
  865. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  866.  
  867. let found = false;
  868.  
  869. findTextNodes(displayTextDOM, (textnode) => {
  870. if (textnode.nodeValue === airaLabel) {
  871. textnode.nodeValue = title;
  872. found = true;
  873. return true;
  874. }
  875. });
  876.  
  877. if (!found) return;
  878. anchor.setAttribute('aria-label', title);
  879. runs[0].text = title;
  880.  
  881.  
  882. const contentTexts = (parentNodeData.contentText || 0).runs;
  883. if (contentTexts && contentTexts.length >= 2) {
  884. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  885. const contentText = contentTexts[aidx] || 0;
  886. if (contentText.italics !== true) {
  887. let isHandle = isDisplayAsHandle(contentText.text);
  888. if (isHandle) {
  889. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  890. }
  891. }
  892. }
  893. }
  894.  
  895. }
  896. } catch (e) {
  897. console.warn(e);
  898. }
  899.  
  900. } : async (anchor, channelHref, mt) => {
  901.  
  902. try {
  903. if (!channelHref || !mt) return;
  904. let parentNode = nodeParent(anchor);
  905. while (parentNode instanceof Node) {
  906. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  907. parentNode = nodeParent(parentNode);
  908. }
  909. if (parentNode instanceof Node) { } else return;
  910. const authorText = (parentNode.data || 0).authorText;
  911. const currentDisplayed = (authorText || 0).simpleText;
  912. if (typeof currentDisplayed !== 'string') return;
  913. if (!isDisplayAsHandle(currentDisplayed)) return;
  914.  
  915. const oldDataChanged = parentNode.dataChanged;
  916. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  917. let newDataChanged = dataChangedFuncStore.get(oldDataChanged);
  918. if (!newDataChanged) {
  919. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  920. newDataChanged.jkrgx = 1;
  921. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  922. }
  923. parentNode.dataChanged = newDataChanged;
  924. }
  925.  
  926. const fetchResult = await getDisplayName(mt);
  927.  
  928. if (fetchResult === null) return;
  929.  
  930. const { title, externalId } = fetchResult;
  931.  
  932. if (externalId !== mt) return; // channel id must be the same
  933.  
  934. // anchor href might be changed by external
  935. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  936.  
  937. const parentNodeData = parentNode.data;
  938. const funcPromises = [];
  939.  
  940. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  941.  
  942. if (authorText.simpleText !== currentDisplayed) return;
  943. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  944. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  945. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  946.  
  947. // the inside hyperlinks will be only converted if its parent author name is handle
  948. const contentTexts = (parentNodeData.contentText || 0).runs;
  949. if (contentTexts && contentTexts.length >= 1) {
  950. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  951. const r = contentTextProcess(contentTexts, aidx);
  952. if (r instanceof Promise) funcPromises.push(r);
  953. }
  954. }
  955.  
  956. const md = Object.assign({}, parentNodeData);
  957. let setBadge = false;
  958. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  959. setBadge = true;
  960. }
  961. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  962. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  963. if (setBadge) {
  964. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  965. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  966. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  967.  
  968. }
  969. if (funcPromises.length >= 1) {
  970. let funcs = await Promise.all(funcPromises);
  971.  
  972. for (const func of funcs) {
  973. if (typeof func === 'function') {
  974. func(md);
  975. }
  976. }
  977. }
  978. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  979. }
  980.  
  981. }
  982. } catch (e) {
  983. console.warn(e);
  984. }
  985.  
  986. }
  987.  
  988. /**
  989. *
  990. * @param {string} url
  991. * @returns
  992. */
  993. const channelUrlUnify = (url) => {
  994.  
  995. if (typeof url !== 'string') return url; // type unchanged
  996. let c0 = url.charAt(0);
  997. if (c0 === '/') return url;
  998. let i = url.indexOf('.youtube.com/');
  999. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1000. else if (url.charAt(0) !== '/') url = '/' + url;
  1001. return url
  1002.  
  1003. }
  1004.  
  1005. let firstDOMCheck = false;
  1006. const firstDOMChecker = isMobile ? () => {
  1007.  
  1008. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1009. const channelNameDOMData = (channelNameDOM || 0).data;
  1010.  
  1011. if (channelNameDOMData) {
  1012. let mainChannelUrl = null;
  1013. let mainFormattedNameUrl = null;
  1014. let mainChannelText = null;
  1015. let mainFormattedNameText = null;
  1016.  
  1017. try {
  1018. mainChannelUrl = channelUrlUnify(channelNameDOMData.channelUrl)
  1019. mainFormattedNameUrl = channelUrlUnify(channelNameDOMData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  1020. mainChannelText = channelNameDOMData.channelName
  1021. mainFormattedNameText = channelNameDOMData.title.runs[0].text
  1022. } catch (e) { }
  1023.  
  1024. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1025.  
  1026.  
  1027. let channelId = obtainChannelId(mainChannelUrl);
  1028. if (channelId) {
  1029. if (mainChannelText.startsWith('@')) return;
  1030. if (mainChannelText.trim() !== mainChannelText) return;
  1031.  
  1032. displayNameResStore.set(channelId, {
  1033. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1034. externalId: `${channelId}`,
  1035. ownerUrls: [],
  1036. title: mainChannelText,
  1037. vanityChannelUrl: null,
  1038. verified123: true
  1039. });
  1040. }
  1041.  
  1042.  
  1043. }
  1044. }
  1045.  
  1046. } : () => {
  1047.  
  1048. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1049. const channelNameDOMData = (channelNameDOM || 0).__data;
  1050. if (channelNameDOMData) {
  1051. let mainChannelUrl = null;
  1052. let mainFormattedNameUrl = null;
  1053. let mainChannelText = null;
  1054. let mainFormattedNameText = null;
  1055.  
  1056. try {
  1057. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1058. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1059. mainChannelText = channelNameDOMData.channelName.runs[0].text
  1060. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  1061. } catch (e) { }
  1062.  
  1063. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1064.  
  1065. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1066.  
  1067. if (m && m[1] && mainChannelText !== m[1]) {
  1068.  
  1069. let channelId = obtainChannelId(mainChannelUrl);
  1070. if (channelId) {
  1071. if (mainChannelText.startsWith('@')) return;
  1072. if (mainChannelText.trim() !== mainChannelText) return;
  1073.  
  1074. displayNameResStore.set(channelId, {
  1075. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1076. externalId: `${channelId}`,
  1077. ownerUrls: [],
  1078. title: mainChannelText,
  1079. vanityChannelUrl: null,
  1080. verified123: true
  1081. });
  1082. }
  1083.  
  1084. }
  1085. }
  1086. }
  1087.  
  1088.  
  1089.  
  1090.  
  1091. };
  1092.  
  1093. // let newAnchorAdded = false;
  1094. /*
  1095.  
  1096. const intersectionobserver = new IntersectionObserver((entries) => {
  1097. let anchorAppear = false;
  1098. for (const entry of entries) {
  1099. if (entry.isIntersecting === true) {
  1100. anchorAppear = true;
  1101. break;
  1102. }
  1103. }
  1104. if (anchorAppear && newAnchorAdded) {
  1105. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1106. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1107. }
  1108. }, {
  1109. rootMargin:"0px 0px 0px 0px",
  1110. threshold:1
  1111. })
  1112. */
  1113.  
  1114.  
  1115. /* globals WeakRef:false */
  1116.  
  1117. /** @type {(o: Object | null) => WeakRef | null} */
  1118. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1119.  
  1120. /** @type {(wr: Object | null) => Object | null} */
  1121. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1122.  
  1123. let lastNewAnchorLastWR = null;
  1124.  
  1125. let domCheckTimeStamp = 0;
  1126.  
  1127. const mutexForDOMMutations = new Mutex();
  1128. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])';
  1129.  
  1130. let domCheckScheduled = false;
  1131. const domChecker = () => {
  1132.  
  1133. if(domCheckScheduled) return;
  1134. const newAnchors = document.querySelectorAll(domCheckSelector);
  1135. if (newAnchors.length === 0) {
  1136. return;
  1137. }
  1138. domCheckScheduled = true;
  1139.  
  1140. mutexForDOMMutations.lockWith(lockResolve => {
  1141. domCheckScheduled = false;
  1142.  
  1143. const newAnchors = document.querySelectorAll(domCheckSelector);
  1144. if (newAnchors.length === 0) {
  1145. lockResolve();
  1146. return;
  1147. }
  1148.  
  1149. const cNewAnchorFirst = newAnchors[0]; // non-null
  1150. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1151. /** @type {HTMLElement | null} */
  1152. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1153. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1154.  
  1155. const ltDOMCheck = domCheckTimeStamp;
  1156. const ctDOMCheck = Date.now();
  1157. domCheckTimeStamp = ctDOMCheck;
  1158.  
  1159. if (!firstDOMCheck) {
  1160. firstDOMCheck = true;
  1161. firstDOMChecker();
  1162. }
  1163.  
  1164. const isDocumentModifying = ctDOMCheck - ltDOMCheck < 230;
  1165.  
  1166. Promise.resolve()
  1167. .then(() => {
  1168. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1169.  
  1170. if (isDocumentModifying) {
  1171.  
  1172. } else {
  1173. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1174. mutex.nextIndex = 0;
  1175. }
  1176. }
  1177.  
  1178. /*
  1179. if (mutex.nextIndex === 0) {
  1180. // no change
  1181. } else if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  1182. mutex.nextIndex = 0; // highest priority
  1183. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  1184. mutex.nextIndex = Math.floor(mutex.nextIndex / 2); // relatively higher priority
  1185. }
  1186. */
  1187. }
  1188. }).then(() => {
  1189.  
  1190. // newAnchorAdded = true;
  1191. for (const anchor of newAnchors) {
  1192. // author-text or name
  1193. // normal url: /channel/xxxxxxx
  1194. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1195. const href = anchor.getAttribute('href');
  1196. const channelId = obtainChannelId(href); // string, can be empty
  1197. anchor.setAttribute('jkrgy', channelId);
  1198. // intersectionobserver.unobserve(anchor);
  1199. // intersectionobserver.observe(anchor); // force first occurance
  1200. domCheckAsync(anchor, href, channelId);
  1201. }
  1202.  
  1203. }).then(lockResolve).catch(e => {
  1204. lockResolve();
  1205. console.warn(e);
  1206. });
  1207.  
  1208. });
  1209.  
  1210.  
  1211. };
  1212.  
  1213.  
  1214. /** @type {MutationObserver | null} */
  1215. let domObserver = null;
  1216.  
  1217. /** @type {(callback: (event: Event)=>{})} */
  1218. const onPageFetched = isMobile ? (callback) => {
  1219.  
  1220. let state = 0;
  1221.  
  1222. window.addEventListener('state-change', function (evt) {
  1223. if (state === 1) return; // ignore intermediate events
  1224. state = 1; // before value: 0 or 2;
  1225. callback(evt);
  1226. }, false);
  1227.  
  1228. window.addEventListener('state-navigateend', function (evt) { // fallback
  1229. let inSeq = state === 1;
  1230. state = 2; // 2 when loaded
  1231. if (!inSeq) callback(evt);
  1232. }, false);
  1233.  
  1234. } : (callback) => {
  1235.  
  1236. let state = 0;
  1237.  
  1238. document.addEventListener('yt-page-data-fetched', function (evt) {
  1239. if (state === 1) return; // ignore intermediate events if any
  1240. state = 1; // before value: 0 or 2;
  1241. callback(evt);
  1242. }, false);
  1243.  
  1244. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1245. let inSeq = state === 1;
  1246. state = 2; // 2 when loaded
  1247. if (!inSeq) callback(evt);
  1248. }, false);
  1249.  
  1250. };
  1251.  
  1252. /**
  1253. *
  1254. * @param {Node} app
  1255. * @returns
  1256. */
  1257. function setupOnPageFetched(app) {
  1258.  
  1259. firstDOMCheck = false;
  1260.  
  1261. if (!cfg['INNERTUBE_API_KEY']) {
  1262. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1263. return;
  1264. }
  1265.  
  1266. if (!domObserver) {
  1267. domObserver = new MutationObserver(domChecker);
  1268. } else {
  1269. domObserver.takeRecords();
  1270. domObserver.disconnect();
  1271. }
  1272.  
  1273. domObserver.observe(app, { childList: true, subtree: true });
  1274. domChecker();
  1275.  
  1276. }
  1277.  
  1278. /**
  1279. *
  1280. * @param {Object|null} dest
  1281. * @param {Object} ytcfg
  1282. * @param {string[]} keys
  1283. * @returns
  1284. */
  1285. function getYtConfig(dest, ytcfg, keys) {
  1286. dest = dest || {};
  1287. if (typeof ytcfg.get === 'function') { // mobile
  1288. for (const key of keys) {
  1289. dest[key] = ytcfg.get(key);
  1290. }
  1291. } else {
  1292. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  1293. for (const key of keys) {
  1294. dest[key] = cfgData[key];
  1295. }
  1296. }
  1297. return dest;
  1298. }
  1299.  
  1300. /** @type { (evt: Object) => Element | null } */
  1301. const getPageApp = isMobile
  1302. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  1303. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  1304.  
  1305. onPageFetched(async (evt) => {
  1306. const app = getPageApp(evt);
  1307. console.assert(app);
  1308. const ytcfg = ((window || 0).ytcfg || 0);
  1309. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']);
  1310. setupOnPageFetched(app);
  1311. });
  1312.  
  1313. })({ Promise, fetch });