Restore YouTube Username from Handle to Custom

將 YouTube 使用者名稱從 Handle 恢復為自訂名稱

目前為 2023-06-17 提交的版本,檢視 最新版本

  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.4.1
  30. // @license MIT License
  31.  
  32. // @author CY Fung
  33. // @match https://www.youtube.com/*
  34. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  35. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
  36. // @supportURL https://github.com/cyfung1031/userscript-supports
  37. // @run-at document-start
  38. // @grant none
  39. // @unwrap
  40. // @allFrames
  41. // @inject-into page
  42.  
  43. // @description To restore YouTube Username to the traditional custom name
  44. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  45. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  46. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  47.  
  48. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  49. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  50. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  51. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  52. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  53. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  54. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  55. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  56. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  57. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  58. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  59. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  60. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  61. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  62. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  63. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  64. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  65. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  66. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  67. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  68. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  69. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  70. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  71. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  72. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  73. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  74. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  75. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  76. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  77. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  78. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  79. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  80. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  81. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  82. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  83. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  84. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  85. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  86. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  87. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  88. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  89. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  90. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  91. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  92. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  93. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  94. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  95. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  96. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  97. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  98. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  99. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  100. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  101. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  102. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  103. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  104. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  105. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  106. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  107. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  108. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  109. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  110. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  111. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  112. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  113. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  114. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  115. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  116. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  117.  
  118. // ==/UserScript==
  119.  
  120. /* jshint esversion:8 */
  121.  
  122. (function () {
  123. 'use strict';
  124.  
  125. const cfg = {};
  126. class Mutex {
  127.  
  128. constructor() {
  129. this.p = Promise.resolve()
  130. }
  131.  
  132. lockWith(f) {
  133. this.p = this.p.then(() => new Promise(f)).catch(console.warn)
  134. }
  135.  
  136. }
  137.  
  138. class OrderedMutex extends Mutex {
  139. constructor() {
  140. super();
  141. this.nextIndex = 0;
  142. this.arr = [];
  143. this.lockFunc = resolve => {
  144. if (this.arr.length >= 1) {
  145. let f = this.arr[0];
  146. if (typeof f === 'function') {
  147. this.arr.shift();
  148. if (this.nextIndex > 0) this.nextIndex--;
  149. f(resolve);
  150. return;
  151. } else {
  152. // reset if unknown error
  153. this.arr.length = 0;
  154. this.nextIndex = 0;
  155. }
  156. }
  157. resolve();
  158. };
  159. }
  160. add(f) {
  161. if (this.nextIndex === this.arr.length) {
  162. this.arr.push(f); this.nextIndex++;
  163. } else {
  164. this.arr.splice(this.nextIndex++, 0, f);
  165. }
  166. this.lockWith(this.lockFunc);
  167. }
  168. }
  169. const mutex = new OrderedMutex();
  170.  
  171. const displayNameCacheStore = new Map();
  172.  
  173. const promisesStore = {};
  174.  
  175. function createNetworkPromise(channelId) {
  176.  
  177. return new Promise(networkResolve => {
  178.  
  179.  
  180. mutex.add(lockResolve => {
  181.  
  182. let fetchedResult = displayNameCacheStore.get(channelId);
  183. if (fetchedResult) {
  184. lockResolve();
  185. networkResolve(fetchedResult);
  186. return;
  187. }
  188.  
  189. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  190. // element has already been removed
  191. lockResolve();
  192. networkResolve(null);
  193. return;
  194. }
  195.  
  196. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  197.  
  198.  
  199. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  200. "method": "POST",
  201. "mode": "same-origin",
  202. "credentials": "same-origin",
  203.  
  204. // (-- reference: https://javascript.info/fetch-api
  205. referrerPolicy: "no-referrer",
  206. cache: "default",
  207. redirect: "error",
  208. integrity: "",
  209. keepalive: false,
  210. signal: undefined,
  211. window: window,
  212. // --)
  213.  
  214. "headers": {
  215. "Content-Type": "application/json",
  216. "Accept-Encoding": "gzip, deflate, br"
  217. },
  218. "body": JSON.stringify({
  219. "context": {
  220. "client": {
  221. "clientName": "MWEB",
  222. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  223. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  224. "playerType": "UNIPLAYER",
  225. "platform": "MOBILE",
  226. "clientFormFactor": "SMALL_FORM_FACTOR",
  227. "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",
  228. "mainAppWebInfo": {
  229. "graftUrl": `/channel/${channelId}`,
  230. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  231. "isWebNativeShareAvailable": true
  232. }
  233. },
  234. "user": {
  235. "lockedSafetyMode": false
  236. },
  237. "request": {
  238. "useSsl": true,
  239. "internalExperimentFlags": [],
  240. "consistencyTokenJars": []
  241. }
  242. },
  243. "browseId": `${channelId}`
  244. })
  245. })).then(res => {
  246. lockResolve();
  247. return res.json();
  248. }).then(res => {
  249. networkResolve(res);
  250. }).catch(e => {
  251. lockResolve();
  252. console.warn(e);
  253. networkResolve(null);
  254. })
  255.  
  256.  
  257.  
  258. });
  259.  
  260. })
  261.  
  262. }
  263.  
  264. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : requestAnimationFrame;
  265.  
  266. function getDisplayName(channelId) {
  267.  
  268. return new Promise(resolve => {
  269.  
  270. let cachedResult = displayNameCacheStore.get(channelId);
  271. if (cachedResult) {
  272. resolve(cachedResult);
  273. return;
  274. }
  275.  
  276. if (!promisesStore[channelId]) promisesStore[channelId] = createNetworkPromise(channelId);
  277.  
  278. promisesStore[channelId].then(res => {
  279. // res might be null
  280.  
  281. queueMicrotask_(() => {
  282. promisesStore[channelId] = null;
  283. delete promisesStore[channelId];
  284. });
  285.  
  286. if ('verified123' in (res || 0)) {
  287. resolve(res); // fetchedResult
  288. return;
  289. }
  290.  
  291. let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  292.  
  293. if (!resultInfo) {
  294. resolve(null);
  295. } else {
  296.  
  297. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  298.  
  299. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  300. displayNameCacheStore.set(channelId, displayNameRes);
  301.  
  302. resolve(displayNameRes);
  303.  
  304. }
  305.  
  306.  
  307. }).catch(console.warn);
  308.  
  309. }).catch(console.warn);
  310. }
  311.  
  312. const dataChangedFuncStore = new WeakMap();
  313.  
  314. const obtainChannelId = (href) => {
  315. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  316. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  317. return !m ? '' : (m[1] || '');
  318. };
  319.  
  320. const dataChangeFuncProducer = (dataChanged) => {
  321.  
  322. return function () {
  323. let anchors = null;
  324. try {
  325. anchors = HTMLElement.prototype.querySelectorAll.call(this, 'a[id][href*="channel/"][jkrgy]');
  326. } catch (e) { }
  327. if ((anchors || 0).length >= 1 && (this.data || 0).jkrgx !== 1) {
  328. for (const anchor of anchors) {
  329. anchor.removeAttribute('jkrgy');
  330. }
  331. }
  332. return dataChanged.apply(this, arguments)
  333. }
  334.  
  335.  
  336. };
  337.  
  338. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  339.  
  340. // https://www.youtube.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos /channel/UCRmLncxsQFcOOC8OhzUIfxQ UCRmLncxsQFcOOC8OhzUIfxQ
  341.  
  342.  
  343. let currentHref = anchor.getAttribute('href');
  344. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  345.  
  346. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  347.  
  348. };
  349.  
  350. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  351.  
  352. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  353.  
  354. const currentDisplayTrimmed = currentDisplayed.trim();
  355. let match = false;
  356. if (verified123) {
  357. match = true;
  358. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  359. match = true;
  360. } else if ((ownerUrls || 0).length >= 1) {
  361. for (const ownerUrl of ownerUrls) {
  362. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  363. match = true;
  364. break;
  365. }
  366. }
  367. }
  368. if (match) {
  369. return currentDisplayTrimmed;
  370. }
  371. return '';
  372.  
  373. };
  374.  
  375. const isDisplayAsHandle = (text) => {
  376.  
  377. if (typeof text !== 'string') return false;
  378. if (text.length < 4) return false;
  379. if (text.indexOf('@') < 0) return false;
  380. return /^\s*@[a-zA-Z0-9_\-.]{3,30}\s*$/.test(text);
  381.  
  382.  
  383. /* https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid
  384.  
  385. Handle naming guidelines
  386.  
  387. Is between 3-30 characters
  388. Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  389. Your handle can also include: underscores (_), hyphens (-), dots (.)
  390. Is not URL-like or phone number-like
  391. Is not already being used
  392. Follows YouTube's Community Guidelines
  393.  
  394. // auto handle - without dot (.)
  395.  
  396. */
  397.  
  398. };
  399.  
  400. const contentTextProcess = (contentTexts, idx) => {
  401. const contentText = contentTexts[idx];
  402. const text = (contentText || 0).text;
  403. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  404. if (typeof url === 'string' && typeof text === 'string') {
  405.  
  406. if (!isDisplayAsHandle(text)) return null;
  407. const channelId = obtainChannelId(url);
  408.  
  409. return getDisplayName(channelId).then(fetchResult => {
  410. let resolveResult = null;
  411. if (fetchResult) {
  412. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  413.  
  414. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  415. if (textTrimmed) {
  416. resolveResult = (md) => {
  417. let runs = ((md || 0).contentText || 0).runs;
  418. if (!runs || !runs[idx]) return;
  419. if (runs[idx].text !== text) return;
  420. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  421. md.contentText = Object.assign({}, md.contentText);
  422. };
  423. }
  424. }
  425. return (resolveResult); // function as a Promise
  426. });
  427. }
  428.  
  429. return null;
  430. };
  431.  
  432. const domCheck = async (anchor, channelHref, mt) => {
  433.  
  434. try {
  435. if (!channelHref || !mt) return;
  436. let parentNode = anchor.parentNode;
  437. while (parentNode instanceof Node) {
  438. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  439. parentNode = parentNode.parentNode
  440. }
  441. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  442. const authorText = (parentNode.data || 0).authorText;
  443. const currentDisplayed = (authorText || 0).simpleText;
  444. if (typeof currentDisplayed !== 'string') return;
  445. if (!isDisplayAsHandle(currentDisplayed)) return;
  446.  
  447. const oldDataChanged = parentNode.dataChanged;
  448. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  449. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  450. if (!newDataChanged) {
  451. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  452. newDataChanged.jkrgx = 1;
  453. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  454. }
  455. parentNode.dataChanged = newDataChanged;
  456. }
  457.  
  458. const fetchResult = await getDisplayName(mt);
  459.  
  460. if (fetchResult === null) return;
  461.  
  462. const { title, externalId } = fetchResult;
  463.  
  464. if (externalId !== mt) return; // channel id must be the same
  465.  
  466. // anchor href might be changed by external
  467. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  468.  
  469. const parentNodeData = parentNode.data
  470. const funcPromises = [];
  471. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  472.  
  473. if (authorText.simpleText !== currentDisplayed) return;
  474. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  475. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  476. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  477.  
  478. // the inside hyperlinks will be only converted if its parent author name is handle
  479. const contentTexts = (parentNodeData.contentText || 0).runs;
  480. if (contentTexts && contentTexts.length >= 1) {
  481. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  482. const r = contentTextProcess(contentTexts, aidx);
  483. if (r instanceof Promise) funcPromises.push(r);
  484. }
  485. }
  486.  
  487. const md = Object.assign({}, parentNodeData);
  488. let setBadge = false;
  489. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  490. setBadge = true;
  491. }
  492. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  493. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  494. if (setBadge) {
  495. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  496. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  497. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  498.  
  499. }
  500. if (funcPromises.length >= 1) {
  501. let funcs = await Promise.all(funcPromises);
  502.  
  503. for (const func of funcs) {
  504. if (typeof func === 'function') {
  505. func(md);
  506. }
  507. }
  508. }
  509. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  510. }
  511.  
  512. }
  513. } catch (e) {
  514. console.warn(e);
  515. }
  516.  
  517.  
  518. }
  519.  
  520. let firstDOMCheck = false;
  521. const firstDOMChecker = () => {
  522.  
  523. let channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  524. let channelNameDOMData = (channelNameDOM || 0).__data;
  525. if (channelNameDOMData) {
  526. let mainChannelUrl = null;
  527. let mainFormattedNameUrl = null;
  528. let mainChannelText = null;
  529. let mainFormattedNameText = null;
  530.  
  531. try {
  532. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  533. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  534. mainChannelText = channelNameDOMData.channelName.runs[0].text
  535. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  536. } catch (e) { }
  537.  
  538. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  539.  
  540. let m = /^\/(@[a-zA-Z0-9_\-.]{3,30})$/.test(mainChannelUrl);
  541.  
  542. if (m && m[1] && mainChannelText !== m[1]) {
  543.  
  544. let channelId = obtainChannelId(mainChannelUrl);
  545. if (channelId) {
  546. if (mainChannelText.startsWith('@')) return;
  547. if (mainChannelText.trim() !== mainChannelText) return;
  548.  
  549. displayNameCacheStore.set(channelId, {
  550. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  551. externalId: `${channelId}`,
  552. ownerUrls: [],
  553. title: mainChannelText,
  554. vanityChannelUrl: null,
  555. verified123: true
  556. });
  557. }
  558.  
  559. }
  560. }
  561. }
  562.  
  563.  
  564. };
  565.  
  566. // let newAnchorAdded = false;
  567. /*
  568.  
  569. const intersectionobserver = new IntersectionObserver((entries) => {
  570. let anchorAppear = false;
  571. for (const entry of entries) {
  572. if (entry.isIntersecting === true) {
  573. anchorAppear = true;
  574. break;
  575. }
  576. }
  577. if (anchorAppear && newAnchorAdded) {
  578. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  579. mutex.nextIndex = 0; // higher pirority for new elements being shown
  580. }
  581. }, {
  582. rootMargin:"0px 0px 0px 0px",
  583. threshold:1
  584. })
  585. */
  586.  
  587.  
  588. /* globals WeakRef:false */
  589.  
  590. /** @type {(o: Object | null) => WeakRef | null} */
  591. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  592.  
  593. /** @type {(wr: Object | null) => Object | null} */
  594. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  595.  
  596. let lastNewAnchorLastWR = null;
  597.  
  598. const domChecker = () => {
  599.  
  600. const newAnchors = document.querySelectorAll('a[id][href*="channel/"]:not([jkrgy])');
  601. if (newAnchors.length === 0) return;
  602. const cNewAnchorFirst = newAnchors[0]; // non-null
  603. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  604. /** @type {HTMLElement | null} */
  605. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  606. if (lastNewAnchorLast) {
  607. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  608. mutex.nextIndex = 0; // highest priority
  609. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  610. mutex.nextIndex = Math.floor(mutex.arr.length / 2); // relatively higher priority
  611. }
  612. }
  613. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  614. // newAnchorAdded = true;
  615. for (const anchor of newAnchors) {
  616. // author-text or name
  617. // normal url: /channel/xxxxxxx
  618. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  619. const href = anchor.getAttribute('href');
  620. const channelId = obtainChannelId(href); // string, can be empty
  621. anchor.setAttribute('jkrgy', channelId);
  622. if (!firstDOMCheck) {
  623. firstDOMCheck = true;
  624. firstDOMChecker();
  625. }
  626. // intersectionobserver.unobserve(anchor);
  627. // intersectionobserver.observe(anchor); // force first occurance
  628. domCheck(anchor, href, channelId);
  629. }
  630.  
  631. };
  632.  
  633.  
  634. /** @type {MutationObserver | null} */
  635. let domObserver = null;
  636.  
  637. document.addEventListener('yt-page-data-fetched', function (evt) {
  638.  
  639. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  640. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  641. cfg[key] = cfgData[key];
  642. }
  643.  
  644. if (!cfg['INNERTUBE_API_KEY']) {
  645. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  646. return;
  647. }
  648.  
  649. if (!domObserver) {
  650. domObserver = new MutationObserver(domChecker);
  651. } else {
  652. domObserver.takeRecords();
  653. domObserver.disconnect();
  654. }
  655.  
  656. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  657. domChecker();
  658.  
  659. });
  660.  
  661.  
  662. })();