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.2.5
  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. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  77. // element has already been removed
  78. lockResolve(null);
  79. }
  80.  
  81. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  82.  
  83.  
  84. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  85. "method": "POST",
  86. "mode": "same-origin",
  87. "credentials": "same-origin",
  88.  
  89. // (-- reference: https://javascript.info/fetch-api
  90. referrerPolicy: "no-referrer",
  91. cache: "default",
  92. redirect: "error",
  93. integrity: "",
  94. keepalive: false,
  95. signal: undefined,
  96. window: window,
  97. // --)
  98.  
  99. "headers": {
  100. "Content-Type": "application/json",
  101. "Accept-Encoding": "gzip, deflate, br"
  102. },
  103. "body": JSON.stringify({
  104. "context": {
  105. "client": {
  106. "clientName": "MWEB",
  107. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  108. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  109. "playerType": "UNIPLAYER",
  110. "platform": "MOBILE",
  111. "clientFormFactor": "SMALL_FORM_FACTOR",
  112. "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",
  113. "mainAppWebInfo": {
  114. "graftUrl": `/channel/${channelId}`,
  115. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  116. "isWebNativeShareAvailable": true
  117. }
  118. },
  119. "user": {
  120. "lockedSafetyMode": false
  121. },
  122. "request": {
  123. "useSsl": true,
  124. "internalExperimentFlags": [],
  125. "consistencyTokenJars": []
  126. }
  127. },
  128. "browseId": `${channelId}`
  129. })
  130. })).then(res => {
  131. lockResolve();
  132. return res.json();
  133. }).then(res => {
  134. networkResolve(res);
  135. }).catch(e => {
  136. lockResolve();
  137. console.warn(e);
  138. networkResolve(null);
  139. })
  140.  
  141.  
  142.  
  143. });
  144.  
  145. })
  146.  
  147. }
  148.  
  149. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : requestAnimationFrame;
  150.  
  151. function getDisplayName(channelId) {
  152.  
  153. return new Promise(resolve => {
  154.  
  155. let cachedResult = displayNameCacheStore.get(channelId);
  156. if (cachedResult) {
  157. resolve(cachedResult);
  158. return;
  159. }
  160.  
  161. if (!promisesStore[channelId]) promisesStore[channelId] = createNetworkPromise(channelId);
  162.  
  163. promisesStore[channelId].then(res => {
  164. // res might be null
  165.  
  166. queueMicrotask_(() => {
  167. promisesStore[channelId] = null;
  168. delete promisesStore[channelId];
  169. });
  170.  
  171. let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  172.  
  173. if (!resultInfo) {
  174. resolve(null);
  175. } else {
  176.  
  177. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  178.  
  179. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl };
  180. displayNameCacheStore.set(channelId, displayNameRes);
  181.  
  182. resolve(displayNameRes);
  183.  
  184. }
  185.  
  186.  
  187. }).catch(console.warn);
  188.  
  189. }).catch(console.warn);
  190. }
  191.  
  192. const dataChangedFuncStore = new WeakMap();
  193.  
  194. const obtainChannelId = (href) => {
  195. let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  196. return !m ? '' : (m[1] || '');
  197. }
  198.  
  199. const dataChangeFuncProducer = (dataChanged) => {
  200.  
  201. return function () {
  202. let anchor = null;
  203. try {
  204. anchor = HTMLElement.prototype.querySelector.call(this, 'a[id][href*="channel/"][jkrgy]');
  205. } catch (e) { }
  206. if (anchor !== null && (this.data || 0).jkrgx !== 1) {
  207. anchor.removeAttribute('jkrgy');
  208. }
  209. return dataChanged.apply(this, arguments)
  210. }
  211.  
  212.  
  213. }
  214.  
  215. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  216.  
  217. // https://www.youtube.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos /channel/UCRmLncxsQFcOOC8OhzUIfxQ UCRmLncxsQFcOOC8OhzUIfxQ
  218.  
  219.  
  220. let currentHref = anchor.getAttribute('href');
  221. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  222.  
  223. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  224.  
  225. }
  226.  
  227. const domCheck = async (anchor, channelHref, mt) => {
  228.  
  229. try {
  230. if (!channelHref || !mt) return;
  231. let parentNode = anchor.parentNode;
  232. while (parentNode instanceof Node) {
  233. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  234. parentNode = parentNode.parentNode
  235. }
  236. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  237. const authorText = (parentNode.data || 0).authorText;
  238. const currentDisplayed = (authorText || 0).simpleText;
  239. if (typeof currentDisplayed !== 'string') return;
  240. if (!/^\s*@[a-zA-Z0-9_\-.]{3,30}\s*$/.test(currentDisplayed)) return;
  241. /* https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid
  242.  
  243. Handle naming guidelines
  244.  
  245. Is between 3-30 characters
  246. Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  247. Your handle can also include: underscores (_), hyphens (-), dots (.)
  248. Is not URL-like or phone number-like
  249. Is not already being used
  250. Follows YouTube's Community Guidelines
  251.  
  252. // auto handle - without dot (.)
  253.  
  254. */
  255.  
  256. const oldDataChanged = parentNode.dataChanged;
  257. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  258. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  259. if (!newDataChanged) {
  260. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  261. newDataChanged.jkrgx = 1;
  262. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  263. }
  264. parentNode.dataChanged = newDataChanged;
  265. }
  266.  
  267. const fetchResult = await getDisplayName(mt);
  268.  
  269. if (fetchResult === null) return;
  270.  
  271. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  272.  
  273. if (externalId !== mt) return; // channel id must be the same
  274.  
  275. // anchor href might be changed by external
  276. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  277.  
  278. const parentNodeData = parentNode.data
  279. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData) {
  280.  
  281.  
  282. if (authorText.simpleText !== currentDisplayed) return;
  283. const currentDisplayTrimmed = currentDisplayed.trim();
  284. let match = false;
  285. if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  286. match = true;
  287. } else if ((ownerUrls || 0).length >= 1) {
  288. for (const ownerUrl of ownerUrls) {
  289. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  290. match = true;
  291. break;
  292. }
  293. }
  294. }
  295. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  296. if (match && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  297. const md = Object.assign({}, parentNodeData);
  298. let setBadge = false;
  299. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  300. setBadge = true;
  301. }
  302. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  303. md.authorText = Object.assign({}, md.authorText, { simpleText: title });
  304. if (setBadge) {
  305. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  306. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  307. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  308.  
  309. }
  310. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  311. }
  312.  
  313. }
  314. } catch (e) {
  315. console.warn(e);
  316. }
  317.  
  318.  
  319. }
  320.  
  321. const domChecker = () => {
  322.  
  323. const newAnchors = document.querySelectorAll('a[id][href*="channel/"]:not([jkrgy])');
  324. for (const anchor of newAnchors) {
  325. // author-text or name
  326. // normal url: /channel/xxxxxxx
  327. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  328. const href = anchor.getAttribute('href');
  329. const channelId = obtainChannelId(href); // string, can be empty
  330. anchor.setAttribute('jkrgy', channelId);
  331. domCheck(anchor, href, channelId);
  332. }
  333.  
  334. };
  335.  
  336.  
  337. /** @type {MutationObserver | null} */
  338. let domObserver = null;
  339.  
  340. document.addEventListener('yt-page-data-fetched', function (evt) {
  341.  
  342. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  343. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  344. cfg[key] = cfgData[key];
  345. }
  346.  
  347. if (!cfg['INNERTUBE_API_KEY']) {
  348. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  349. return;
  350. }
  351.  
  352. if (!domObserver) {
  353. domObserver = new MutationObserver(domChecker);
  354. } else {
  355. domObserver.takeRecords();
  356. domObserver.disconnect();
  357. }
  358.  
  359. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  360. domChecker();
  361.  
  362. });
  363.  
  364.  
  365. })();