Restore YouTube Username from Handle to Custom

To restore YouTube Username to the traditional custom name

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

  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.1.12
  30. // @license MIT License
  31. // @description To restore YouTube Username to the traditional custom name
  32. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  33.  
  34. // @author CY Fung
  35. // @match https://www.youtube.com/*
  36. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  37. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
  38. // @supportURL https://github.com/cyfung1031/userscript-supports
  39. // @run-at document-start
  40. // @grant none
  41. // @unwrap
  42. // @allFrames
  43. // @inject-into page
  44. // ==/UserScript==
  45.  
  46. /* jshint esversion:8 */
  47.  
  48. (function () {
  49. 'use strict';
  50.  
  51. const cfg = {};
  52. class Mutex {
  53.  
  54. constructor() {
  55. this.p = Promise.resolve()
  56. }
  57.  
  58. lockWith(f) {
  59. this.p = this.p.then(() => new Promise(f)).catch(console.warn)
  60. }
  61.  
  62. }
  63. const mutex = new Mutex();
  64.  
  65. const displayNameCacheStore = new Map();
  66.  
  67. const promisesStore = {};
  68.  
  69. function createNetworkPromise(channelId) {
  70.  
  71. return new Promise(networkResolve => {
  72.  
  73.  
  74. mutex.lockWith(lockResolve => {
  75.  
  76.  
  77.  
  78. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  79.  
  80.  
  81. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  82. "method": "POST",
  83. "mode": "same-origin",
  84. "credentials": "same-origin",
  85.  
  86. // (-- reference: https://ja.javascript.info/fetch-api
  87. referrerPolicy: "no-referrer",
  88. cache: "default",
  89. redirect: "error",
  90. integrity: "",
  91. keepalive: false,
  92. signal: undefined,
  93. window: window,
  94. // --)
  95.  
  96. "headers": {
  97. "Content-Type": "application/json"
  98. },
  99. "body": JSON.stringify({
  100. "context": {
  101. "client": {
  102. "clientName": "MWEB",
  103. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  104. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  105. "playerType": "UNIPLAYER",
  106. "platform": "MOBILE",
  107. "clientFormFactor": "SMALL_FORM_FACTOR",
  108. "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",
  109. "mainAppWebInfo": {
  110. "graftUrl": `/channel/${channelId}`,
  111. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  112. "isWebNativeShareAvailable": true
  113. }
  114. },
  115. "user": {
  116. "lockedSafetyMode": false
  117. },
  118. "request": {
  119. "useSsl": true,
  120. "internalExperimentFlags": [],
  121. "consistencyTokenJars": []
  122. }
  123. },
  124. "browseId": `${channelId}`
  125. })
  126. })).then(res => {
  127. lockResolve();
  128. return res.json();
  129. }).then(res => {
  130. networkResolve(res);
  131. })
  132.  
  133.  
  134.  
  135. });
  136.  
  137. })
  138.  
  139. }
  140.  
  141. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : requestAnimationFrame;
  142.  
  143. function getDisplayName(channelId) {
  144.  
  145. return new Promise(resolve => {
  146.  
  147. let cachedResult = displayNameCacheStore.get(channelId);
  148. if (cachedResult) {
  149. resolve(cachedResult);
  150. return;
  151. }
  152.  
  153. if (!promisesStore[channelId]) promisesStore[channelId] = createNetworkPromise(channelId);
  154.  
  155. promisesStore[channelId].then(res => {
  156.  
  157. queueMicrotask_(() => {
  158. promisesStore[channelId] = null;
  159. delete promisesStore[channelId];
  160. });
  161.  
  162. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  163.  
  164. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl };
  165. displayNameCacheStore.set(channelId, displayNameRes);
  166.  
  167. resolve(displayNameRes);
  168.  
  169. });
  170.  
  171. });
  172. }
  173.  
  174. const dataChangedFuncStore = new WeakMap();
  175.  
  176.  
  177. const dataChangeFuncProducer = (dataChanged) => {
  178.  
  179. return function () {
  180. let p = this.querySelector('#author-text[href^="/channel/"], #name[href^="/channel/"]');
  181. if (p && (this.data || 0).jkrgx !== 1) {
  182. p.classList.remove('jkrgx');
  183. }
  184. return dataChanged.apply(this, arguments)
  185. }
  186.  
  187.  
  188. }
  189.  
  190. const domCheck = async (anchor) => {
  191.  
  192.  
  193. let channelHref = anchor.getAttribute('href');
  194. if (!channelHref) return;
  195. let parentNode = anchor.parentNode;
  196. while (parentNode instanceof Node) {
  197. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  198. parentNode = parentNode.parentNode
  199. }
  200. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  201. let authorText = (parentNode.data || 0).authorText;
  202. if (authorText && typeof authorText.simpleText === 'string') { } else return;
  203. const currentDisplayed = authorText.simpleText;
  204. if (!/\s*\@[a-zA-Z0-9_\-]+\s*/.test(currentDisplayed)) return;
  205.  
  206. let m = /\/channel\/([^\/\?\#]+)/.exec(channelHref);
  207. if (!m || !m[1]) return;
  208.  
  209. let oldDataChanged = parentNode.dataChanged;
  210. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  211. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  212. if (!newDataChanged) {
  213. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  214. newDataChanged.jkrgx = 1;
  215. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  216. }
  217. parentNode.dataChanged = newDataChanged;
  218. }
  219.  
  220. const fetchResult = await getDisplayName(m[1]);
  221.  
  222.  
  223. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  224.  
  225. if (anchor.getAttribute('href') !== `/channel/${externalId}`) return;
  226. const parentNodeData = parentNode.data
  227. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData) {
  228.  
  229.  
  230. if (authorText.simpleText !== currentDisplayed) return;
  231. let currentDisplayTrimmed = currentDisplayed.trim();
  232. let match = false;
  233. for (const ownerUrl of ownerUrls) {
  234.  
  235. if (ownerUrl.endsWith(`/${currentDisplayTrimmed}`)) {
  236. match = true;
  237. break;
  238. }
  239. }
  240. let cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  241. if (match && currentDisplayed !== title && cSimpleText) {
  242. let md = Object.assign({}, parentNodeData);
  243. let setBadge = false;
  244. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  245. setBadge = true;
  246. }
  247. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  248. md.authorText = Object.assign({}, md.authorText, { simpleText: title });
  249. if (setBadge) {
  250. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  251. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  252. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  253.  
  254. }
  255. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  256. }
  257.  
  258. }
  259.  
  260.  
  261. }
  262.  
  263. const domChecker = () => {
  264.  
  265. for (const anchor of document.querySelectorAll('#author-text[href^="/channel/"]:not(.jkrgx), #name[href^="/channel/"]:not(.jkrgx)')) {
  266. anchor.classList.add('jkrgx');
  267. domCheck(anchor);
  268. }
  269.  
  270. };
  271.  
  272.  
  273. /** @type {MutationObserver | null} */
  274. let domObserver = null;
  275.  
  276. document.addEventListener('yt-page-data-fetched', function (evt) {
  277.  
  278. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  279. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  280. cfg[key] = cfgData[key];
  281. }
  282.  
  283. if (!cfg['INNERTUBE_API_KEY']) return;
  284.  
  285. if (!domObserver) {
  286. domObserver = new MutationObserver(domChecker);
  287. } else {
  288. domObserver.takeRecords();
  289. domObserver.disconnect();
  290. }
  291.  
  292. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  293. domChecker();
  294.  
  295. });
  296.  
  297.  
  298. })();