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