Restore YouTube Username from Handle to Custom

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

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址