Restore YouTube Username from Handle to Custom

To restore YouTube Username to the traditional custom name

目前为 2023-06-16 提交的版本,查看 最新版本

  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.17
  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://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. "Accept-Encoding": "gzip, deflate, br"
  99. },
  100. "body": JSON.stringify({
  101. "context": {
  102. "client": {
  103. "clientName": "MWEB",
  104. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  105. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  106. "playerType": "UNIPLAYER",
  107. "platform": "MOBILE",
  108. "clientFormFactor": "SMALL_FORM_FACTOR",
  109. "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",
  110. "mainAppWebInfo": {
  111. "graftUrl": `/channel/${channelId}`,
  112. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  113. "isWebNativeShareAvailable": true
  114. }
  115. },
  116. "user": {
  117. "lockedSafetyMode": false
  118. },
  119. "request": {
  120. "useSsl": true,
  121. "internalExperimentFlags": [],
  122. "consistencyTokenJars": []
  123. }
  124. },
  125. "browseId": `${channelId}`
  126. })
  127. })).then(res => {
  128. lockResolve();
  129. return res.json();
  130. }).then(res => {
  131. networkResolve(res);
  132. }).catch(e => {
  133. lockResolve();
  134. console.warn(e);
  135. })
  136.  
  137.  
  138.  
  139. });
  140.  
  141. })
  142.  
  143. }
  144.  
  145. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : requestAnimationFrame;
  146.  
  147. function getDisplayName(channelId) {
  148.  
  149. return new Promise(resolve => {
  150.  
  151. let cachedResult = displayNameCacheStore.get(channelId);
  152. if (cachedResult) {
  153. resolve(cachedResult);
  154. return;
  155. }
  156.  
  157. if (!promisesStore[channelId]) promisesStore[channelId] = createNetworkPromise(channelId);
  158.  
  159. promisesStore[channelId].then(res => {
  160.  
  161. queueMicrotask_(() => {
  162. promisesStore[channelId] = null;
  163. delete promisesStore[channelId];
  164. });
  165.  
  166. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  167.  
  168. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl };
  169. displayNameCacheStore.set(channelId, displayNameRes);
  170.  
  171. resolve(displayNameRes);
  172.  
  173. }).catch(console.warn);
  174.  
  175. }).catch(console.warn);
  176. }
  177.  
  178. const dataChangedFuncStore = new WeakMap();
  179.  
  180.  
  181. const dataChangeFuncProducer = (dataChanged) => {
  182.  
  183. return function () {
  184. let p = this.querySelector('#author-text[href^="/channel/"], #name[href^="/channel/"]');
  185. if (p && (this.data || 0).jkrgx !== 1) {
  186. p.classList.remove('jkrgx');
  187. }
  188. return dataChanged.apply(this, arguments)
  189. }
  190.  
  191.  
  192. }
  193.  
  194. const domCheck = async (anchor) => {
  195.  
  196. try {
  197.  
  198. let channelHref = anchor.getAttribute('href');
  199. if (!channelHref) return;
  200. let parentNode = anchor.parentNode;
  201. while (parentNode instanceof Node) {
  202. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  203. parentNode = parentNode.parentNode
  204. }
  205. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  206. let authorText = (parentNode.data || 0).authorText;
  207. const currentDisplayed = (authorText||0).simpleText;
  208. if (typeof currentDisplayed !== 'string') return;
  209. if (!/^\s*@[a-zA-Z0-9_\-.]{3,30}\s*$/.test(currentDisplayed)) return;
  210. /* https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid
  211.  
  212. Handle naming guidelines
  213.  
  214. Is between 3-30 characters
  215. Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  216. Your handle can also include: underscores (_), hyphens (-), dots (.)
  217. Is not URL-like or phone number-like
  218. Is not already being used
  219. Follows YouTube's Community Guidelines
  220.  
  221. // auto handle - without dot (.)
  222.  
  223. */
  224.  
  225. let m = /\/channel\/([^/?#]+)/.exec(channelHref);
  226. if (!m || !m[1]) return;
  227.  
  228. let oldDataChanged = parentNode.dataChanged;
  229. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  230. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  231. if (!newDataChanged) {
  232. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  233. newDataChanged.jkrgx = 1;
  234. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  235. }
  236. parentNode.dataChanged = newDataChanged;
  237. }
  238.  
  239. const fetchResult = await getDisplayName(m[1]);
  240.  
  241.  
  242. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  243.  
  244. if (anchor.getAttribute('href') !== `/channel/${externalId}`) return;
  245. const parentNodeData = parentNode.data
  246. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData) {
  247.  
  248.  
  249. if (authorText.simpleText !== currentDisplayed) return;
  250. let currentDisplayTrimmed = currentDisplayed.trim();
  251. let match = false;
  252. if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  253. match = true;
  254. } else if ((ownerUrls || 0).length >= 1) {
  255. for (const ownerUrl of ownerUrls) {
  256. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  257. match = true;
  258. break;
  259. }
  260. }
  261. }
  262. let cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  263. if (match && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  264. let md = Object.assign({}, parentNodeData);
  265. let setBadge = false;
  266. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  267. setBadge = true;
  268. }
  269. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  270. md.authorText = Object.assign({}, md.authorText, { simpleText: title });
  271. if (setBadge) {
  272. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  273. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  274. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  275.  
  276. }
  277. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  278. }
  279.  
  280. }
  281. } catch (e) {
  282. console.warn(e);
  283. }
  284.  
  285.  
  286. }
  287.  
  288. const domChecker = () => {
  289.  
  290. for (const anchor of document.querySelectorAll('#author-text[href^="/channel/"]:not(.jkrgx), #name[href^="/channel/"]:not(.jkrgx)')) {
  291. anchor.classList.add('jkrgx');
  292. domCheck(anchor);
  293. }
  294.  
  295. };
  296.  
  297.  
  298. /** @type {MutationObserver | null} */
  299. let domObserver = null;
  300.  
  301. document.addEventListener('yt-page-data-fetched', function (evt) {
  302.  
  303. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  304. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  305. cfg[key] = cfgData[key];
  306. }
  307.  
  308. if (!cfg['INNERTUBE_API_KEY']) return;
  309.  
  310. if (!domObserver) {
  311. domObserver = new MutationObserver(domChecker);
  312. } else {
  313. domObserver.takeRecords();
  314. domObserver.disconnect();
  315. }
  316.  
  317. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  318. domChecker();
  319.  
  320. });
  321.  
  322.  
  323. })();