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.3.0
  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 verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  228.  
  229. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  230.  
  231. const currentDisplayTrimmed = currentDisplayed.trim();
  232. let match = false;
  233. if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  234. match = true;
  235. } else if ((ownerUrls || 0).length >= 1) {
  236. for (const ownerUrl of ownerUrls) {
  237. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  238. match = true;
  239. break;
  240. }
  241. }
  242. }
  243. if (match) {
  244. return currentDisplayTrimmed;
  245. }
  246. return '';
  247.  
  248. }
  249.  
  250. const isDisplayAsHandle = (text) => {
  251.  
  252. if (typeof text !== 'string') return false;
  253. if (text.length < 4) return false;
  254. if (text.indexOf('@') < 0) return false;
  255. return /^\s*@[a-zA-Z0-9_\-.]{3,30}\s*$/.test(text);
  256.  
  257.  
  258. /* https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid
  259.  
  260. Handle naming guidelines
  261.  
  262. Is between 3-30 characters
  263. Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  264. Your handle can also include: underscores (_), hyphens (-), dots (.)
  265. Is not URL-like or phone number-like
  266. Is not already being used
  267. Follows YouTube's Community Guidelines
  268.  
  269. // auto handle - without dot (.)
  270.  
  271. */
  272.  
  273. }
  274.  
  275. const contentTextProcess = (contentTexts, idx) => {
  276. const contentText = contentTexts[idx];
  277. const text = (contentText || 0).text;
  278. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  279. if (typeof url === 'string' && typeof text === 'string') {
  280.  
  281. if (!isDisplayAsHandle(text)) return null;
  282. const channelId = obtainChannelId(url);
  283.  
  284. return getDisplayName(channelId).then(fetchResult => {
  285. let resolveResult = null;
  286. if (fetchResult) {
  287. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  288.  
  289. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  290. if (textTrimmed) {
  291. resolveResult = (md) => {
  292. let runs = ((md || 0).contentText || 0).runs;
  293. if (!runs || !runs[idx]) return;
  294. if (runs[idx].text !== text) return;
  295. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  296. md.contentText = Object.assign({}, md.contentText);
  297. };
  298. }
  299. }
  300. return (resolveResult); // function as a Promise
  301. });
  302. }
  303.  
  304. return null;
  305. }
  306.  
  307. const domCheck = async (anchor, channelHref, mt) => {
  308.  
  309. try {
  310. if (!channelHref || !mt) return;
  311. let parentNode = anchor.parentNode;
  312. while (parentNode instanceof Node) {
  313. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  314. parentNode = parentNode.parentNode
  315. }
  316. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  317. const authorText = (parentNode.data || 0).authorText;
  318. const currentDisplayed = (authorText || 0).simpleText;
  319. if (typeof currentDisplayed !== 'string') return;
  320. if (!isDisplayAsHandle(currentDisplayed)) return;
  321.  
  322. const oldDataChanged = parentNode.dataChanged;
  323. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  324. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  325. if (!newDataChanged) {
  326. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  327. newDataChanged.jkrgx = 1;
  328. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  329. }
  330. parentNode.dataChanged = newDataChanged;
  331. }
  332.  
  333. const fetchResult = await getDisplayName(mt);
  334.  
  335. if (fetchResult === null) return;
  336.  
  337. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  338.  
  339. if (externalId !== mt) return; // channel id must be the same
  340.  
  341. // anchor href might be changed by external
  342. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  343.  
  344. const parentNodeData = parentNode.data
  345. const funcPromises = [];
  346. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  347.  
  348. if (authorText.simpleText !== currentDisplayed) return;
  349. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  350. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  351. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  352.  
  353. // the inside hyperlinks will be only converted if its parent author name is handle
  354. const contentTexts = (parentNodeData.contentText || 0).runs;
  355. if (contentTexts && contentTexts.length >= 1) {
  356. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  357. const r = contentTextProcess(contentTexts, aidx);
  358. if (r instanceof Promise) funcPromises.push(r);
  359. }
  360. }
  361.  
  362. const md = Object.assign({}, parentNodeData);
  363. let setBadge = false;
  364. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  365. setBadge = true;
  366. }
  367. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  368. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  369. if (setBadge) {
  370. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  371. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  372. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  373.  
  374. }
  375. if (funcPromises.length >= 1) {
  376. let funcs = await Promise.all(funcPromises);
  377.  
  378. for (const func of funcs) {
  379. if (typeof func === 'function') {
  380. func(md);
  381. }
  382. }
  383. }
  384. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  385. }
  386.  
  387. }
  388. } catch (e) {
  389. console.warn(e);
  390. }
  391.  
  392.  
  393. }
  394.  
  395. const domChecker = () => {
  396.  
  397. const newAnchors = document.querySelectorAll('a[id][href*="channel/"]:not([jkrgy])');
  398. for (const anchor of newAnchors) {
  399. // author-text or name
  400. // normal url: /channel/xxxxxxx
  401. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  402. const href = anchor.getAttribute('href');
  403. const channelId = obtainChannelId(href); // string, can be empty
  404. anchor.setAttribute('jkrgy', channelId);
  405. domCheck(anchor, href, channelId);
  406. }
  407.  
  408. };
  409.  
  410.  
  411. /** @type {MutationObserver | null} */
  412. let domObserver = null;
  413.  
  414. document.addEventListener('yt-page-data-fetched', function (evt) {
  415.  
  416. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  417. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  418. cfg[key] = cfgData[key];
  419. }
  420.  
  421. if (!cfg['INNERTUBE_API_KEY']) {
  422. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  423. return;
  424. }
  425.  
  426. if (!domObserver) {
  427. domObserver = new MutationObserver(domChecker);
  428. } else {
  429. domObserver.takeRecords();
  430. domObserver.disconnect();
  431. }
  432.  
  433. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  434. domChecker();
  435.  
  436. });
  437.  
  438.  
  439. })();