Greasy Fork 还支持 简体中文。

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