Greasy Fork 还支持 简体中文。

Restore YouTube Username from Handle to Custom

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

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

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