YouTube: Add Channel Name to Shorts Thumbnail

在 YouTube Shorts 缩略图中添加频道名称

当前为 2025-01-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube: Add Channel Name to Shorts Thumbnail
  3. // @namespace UserScript
  4. // @match https://www.youtube.com/*
  5. // @version 0.2.6
  6. // @license MIT License
  7. // @author CY Fung
  8. // @grant none
  9. // @unwrap
  10. // @inject-into page
  11. // @run-at document-start
  12. // @description To add channel name to YouTube Shorts thumbnail
  13. // @description:ja YouTube Shortsのサムネイルにチャンネル名を追加する
  14. // @description:zh-TW 在 YouTube Shorts 縮圖中添加頻道名稱
  15. // @description:zh-CN 在 YouTube Shorts 缩略图中添加频道名称
  16. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@8fac46500c5a916e6ed21149f6c25f8d1c56a6a3/library/ytZara.js
  17. // ==/UserScript==
  18.  
  19. /*
  20.  
  21. MIT License
  22.  
  23. Copyright 2024 CY Fung
  24.  
  25. Permission is hereby granted, free of charge, to any person obtaining a copy
  26. of this software and associated documentation files (the "Software"), to deal
  27. in the Software without restriction, including without limitation the rights
  28. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29. copies of the Software, and to permit persons to whom the Software is
  30. furnished to do so, subject to the following conditions:
  31.  
  32. The above copyright notice and this permission notice shall be included in all
  33. copies or substantial portions of the Software.
  34.  
  35. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  36. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  41. SOFTWARE.
  42.  
  43. */
  44.  
  45.  
  46.  
  47. (() => {
  48.  
  49.  
  50. !window.TTP && (() => {
  51. // credit to Benjamin Philipp
  52. // original source: https://greasyfork.org/en/scripts/433051-trusted-types-helper
  53.  
  54. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  55.  
  56. const overwrite_default = false; // If a default policy already exists, it might be best not to overwrite it, but to try and set a custom policy and use it to manually generate trusted types. Try at your own risk
  57. const prefix = `TTP`;
  58. var passThroughFunc = function (string, sink) {
  59. return string; // Anything passing through this function will be returned without change
  60. }
  61. var TTPName = "passthrough";
  62. var TTP_default, TTP = { createHTML: passThroughFunc, createScript: passThroughFunc, createScriptURL: passThroughFunc }; // We can use TTP.createHTML for all our assignments even if we don't need or even have Trusted Types; this should make fallbacks and polyfills easy
  63. var needsTrustedHTML = false;
  64. function doit() {
  65. try {
  66. if (typeof window.isSecureContext !== 'undefined' && window.isSecureContext) {
  67. if (window.trustedTypes && window.trustedTypes.createPolicy) {
  68. needsTrustedHTML = true;
  69. if (trustedTypes.defaultPolicy) {
  70. log("TT Default Policy exists");
  71. if (overwrite_default)
  72. TTP = window.trustedTypes.createPolicy("default", TTP);
  73. else
  74. TTP = window.trustedTypes.createPolicy(TTPName, TTP); // Is the default policy permissive enough? If it already exists, best not to overwrite it
  75. TTP_default = trustedTypes.defaultPolicy;
  76.  
  77. log("Created custom passthrough policy, in case the default policy is too restrictive: Use Policy '" + TTPName + "' in var 'TTP':", TTP);
  78. }
  79. else {
  80. TTP_default = TTP = window.trustedTypes.createPolicy("default", TTP);
  81. }
  82. log("Trusted-Type Policies: TTP:", TTP, "TTP_default:", TTP_default);
  83. }
  84. }
  85. } catch (e) {
  86. log(e);
  87. }
  88. }
  89.  
  90. function log(...args) {
  91. if ("undefined" != typeof (prefix) && !!prefix)
  92. args = [prefix + ":", ...args];
  93. if ("undefined" != typeof (debugging) && !!debugging)
  94. args = [...args, new Error().stack.replace(/^\s*(Error|Stack trace):?\n/gi, "").replace(/^([^\n]*\n)/, "\n")];
  95. console.log(...args);
  96. }
  97.  
  98. doit();
  99.  
  100. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  101.  
  102. window.TTP = TTP;
  103.  
  104. })();
  105.  
  106. function createHTML(s) {
  107. if (typeof TTP !== 'undefined' && typeof TTP.createHTML === 'function') return TTP.createHTML(s);
  108. return s;
  109. }
  110.  
  111. let trustHTMLErr = null;
  112. try {
  113. document.createElement('div').innerHTML = createHTML('1');
  114. } catch (e) {
  115. trustHTMLErr = e;
  116. }
  117.  
  118. if (trustHTMLErr) {
  119. console.log(`trustHTMLErr`, trustHTMLErr);
  120. trustHTMLErr(); // exit userscript
  121. }
  122.  
  123.  
  124. // -----------------------------------------------------------------------------------------------------------------------------
  125.  
  126.  
  127.  
  128.  
  129. /** @type {globalThis.PromiseConstructor} */
  130. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  131.  
  132. const fetch_ = fetch;
  133.  
  134. const HTMLElement_ = HTMLElement;
  135.  
  136. /**
  137. * @param {Element} elm
  138. * @param {string} selector
  139. * @returns {Element | null}
  140. * */
  141. const qsOne = (elm, selector) => {
  142. return HTMLElement_.prototype.querySelector.call(elm, selector);
  143. }
  144.  
  145. /**
  146. * @param {Element} elm
  147. * @param {string} selector
  148. * @returns {NodeListOf<Element>}
  149. * */
  150. const qsAll = (elm, selector) => {
  151. return HTMLElement_.prototype.querySelectorAll.call(elm, selector);
  152. }
  153.  
  154. const cssFn = () => `
  155.  
  156. [ePCWu]::before {
  157. width: 100%;
  158. content: attr(ePCWu);
  159. display: block;
  160. max-width: 100%;
  161. text-overflow: ellipsis;
  162. overflow: hidden;
  163. white-space: nowrap;
  164. }
  165. `;
  166.  
  167.  
  168. const addCSSProcess = () => {
  169. if (document.querySelector('style#ePCWv')) return;
  170. const style = document.createElement('style')
  171. style.id = 'ePCWv'
  172. style.textContent = cssFn();
  173. document.head.appendChild(style);
  174. };
  175.  
  176. const { networkRequestOfChannelName } = (() => {
  177.  
  178. let chainPromise = Promise.resolve();
  179.  
  180. const resolvedValues = new Map();
  181.  
  182. /**
  183. *
  184. * @param {Response} fetchRes
  185. * @param {(value: any)=>void} resolve
  186. */
  187. const onFetched = async (fetchRes, resolve) => {
  188. const resText = await fetchRes.text();
  189. let resultName = '';
  190. let wIdx2 = resText.indexOf('itemprop="author"');
  191. let wIdx1 = wIdx2 > 0 ? resText.lastIndexOf('<span', wIdx2) : -1;
  192. let wIdx3 = wIdx1 > 0 ? resText.indexOf('<\/span>', wIdx2) : -1;
  193. if (wIdx3 > 0) {
  194. let mText = resText.substring(wIdx1, wIdx3 + '<\/span>'.length);
  195. let template = document.createElement('template');
  196. template.innerHTML = createHTML(mText);
  197. let span = template.content.firstElementChild;
  198. if (span && span.nodeName === "SPAN") {
  199. const nameElm = qsOne(span, 'link[itemprop="name"]')
  200. resultName = (nameElm ? nameElm.getAttribute('content') : '') || '';
  201. }
  202. template.innerHTML = createHTML('');
  203. }
  204. resolve(resultName);
  205. }
  206.  
  207. const createPromise = (videoId) => {
  208.  
  209. return new Promise(resolve => {
  210.  
  211. chainPromise = chainPromise.then(async () => {
  212.  
  213. let fetchRes = null;
  214. try {
  215.  
  216. fetchRes = await fetch_(`/watch?v=${videoId}`, {
  217.  
  218. "method": "GET",
  219. "mode": "same-origin",
  220. "credentials": "omit",
  221. referrerPolicy: "no-referrer",
  222. cache: "default",
  223. redirect: "error", // there shall be no redirection in this API request
  224. integrity: "",
  225. keepalive: false,
  226.  
  227. "headers": {
  228. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  229. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  230. // seems YouTube RSS Feeds server insists its own Cache-Control.
  231.  
  232. // "Content-Type": "text/xml; charset=UTF-8",
  233. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  234. // X-Youtube-Bootstrap-Logged-In: false,
  235. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  236. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  237.  
  238. "Accept": "text/html",
  239. "Pragma": ""
  240. }
  241.  
  242. });
  243.  
  244. } catch (e) {
  245. console.warn(e);
  246. }
  247.  
  248. fetchRes && onFetched(fetchRes, resolve).catch(console.warn);
  249.  
  250. });
  251.  
  252.  
  253. });
  254.  
  255.  
  256. };
  257.  
  258. const networkRequestOfChannelName = (videoId) => {
  259. let promise = resolvedValues.get(videoId);
  260. if (!promise) {
  261. promise = createPromise(videoId);
  262. resolvedValues.set(videoId, promise);
  263. }
  264. return promise;
  265. }
  266.  
  267. return { networkRequestOfChannelName };
  268.  
  269. })();
  270.  
  271.  
  272.  
  273. const firstObjectKey = (obj) => {
  274. for (const key in obj) {
  275. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  276. }
  277. return null;
  278. }
  279.  
  280. const getEntryVideoId = (wtObj) => {
  281.  
  282. let videoId = '';
  283.  
  284. if (wtObj.overlayMetadata && typeof wtObj.entityId == 'string' && (wtObj.inlinePlayerData || 0).onVisible) {
  285. const watchEndpoint = ((wtObj.inlinePlayerData || 0).onVisible.innertubeCommand || 0).watchEndpoint || 0;
  286. if (watchEndpoint && typeof (watchEndpoint.videoId || 0) === 'string') {
  287. videoId = watchEndpoint.videoId;
  288. }
  289. }
  290.  
  291. if (!videoId && wtObj.overlayMetadata && typeof wtObj.entityId == 'string' && (wtObj.onTap || 0).innertubeCommand) {
  292. const reelWatchEndpoint = ((wtObj.onTap || 0).innertubeCommand || 0).reelWatchEndpoint || 0;
  293. if (reelWatchEndpoint && typeof (reelWatchEndpoint.videoId || 0) === 'string') {
  294. videoId = reelWatchEndpoint.videoId;
  295. }
  296. }
  297.  
  298. return videoId;
  299. }
  300.  
  301. const getSubheadElement = (mainElement) => {
  302. return qsOne(mainElement, '.ShortsLockupViewModelHostMetadataSubhead, .ShortsLockupViewModelHostOutsideMetadataSubhead, .shortsLockupViewModelHostMetadataSubhead, .shortsLockupViewModelHostOutsideMetadataSubhead');
  303. }
  304.  
  305. const addChannelNamePerItem = async (entry) => {
  306. const wKey = firstObjectKey(entry);
  307. const wObj = wKey ? entry[wKey] : null;
  308. if (wObj) {
  309. const rsVideoId = wObj.rsVideoId;
  310. const videoId = getEntryVideoId(wObj);
  311. if (videoId === rsVideoId && videoId) {
  312. return {
  313. entry,
  314. rsVideoId,
  315. rsChannelName: wObj.rsChannelName
  316. };
  317. } else if (videoId !== rsVideoId && videoId) {
  318. const name = await networkRequestOfChannelName(videoId);
  319. return {
  320. entry,
  321. rsVideoId: videoId,
  322. rsChannelName: name
  323. };
  324. }
  325. }
  326. return {
  327. entry,
  328. rsVideoId: '',
  329. rsChannelName: ''
  330. };
  331. };
  332.  
  333. const apGridListFn = async function (cnt_) {
  334.  
  335. const cnt = cnt_ || this;
  336. // const hostElement = cnt.hostElement || cnt;
  337. const data = cnt.data;
  338.  
  339. const items = data.items;
  340. if (!items || !items.length) return;
  341.  
  342. const itemsElm = (cnt.$ || 0).items || 0;
  343. if (!itemsElm) return;
  344.  
  345. const results = await Promise.all(items.map(addChannelNamePerItem));
  346.  
  347. const mapping = new Map();
  348.  
  349. for (const result of results) {
  350. if (!result || !result.rsVideoId) continue;
  351. const entry = (result.entry || 0);
  352. if (!entry) continue;
  353. const wKey = firstObjectKey(entry);
  354. const wObj = wKey ? entry[wKey] : null;
  355. const entityId = wObj ? wObj.entityId : null;
  356. if (typeof entityId === 'string') {
  357. mapping.set(entityId, result);
  358. }
  359. }
  360.  
  361. for (const elm of qsAll(itemsElm, 'ytm-shorts-lockup-view-model')) {
  362. const entityId = ((elm.data || 0).entityId || 0);
  363.  
  364. let nameToAdd = '';
  365. if (typeof entityId === 'string') {
  366. const result = mapping.get(entityId);
  367. if (result) {
  368. elm.data.rsVideoId = result.rsVideoId;
  369. elm.data.rsChannelName = result.rsChannelName;
  370. nameToAdd = result.rsChannelName;
  371. }
  372. }
  373.  
  374. const subhead = getSubheadElement(elm);
  375. if (subhead) {
  376. if (nameToAdd) {
  377. subhead.setAttribute('ePCWu', nameToAdd);
  378. } else {
  379. subhead.removeAttribute('ePCWu');
  380. }
  381. } else {
  382. console.log('subhead cannot be found', elm);
  383. }
  384.  
  385. }
  386.  
  387. mapping.clear();
  388.  
  389.  
  390. }
  391.  
  392. const apSingleGridFn = async function (cnt_) {
  393.  
  394. let useOldModel = true;
  395. const cnt = cnt_ || this;
  396. const hostElement = cnt.hostElement || cnt;
  397. let nameToAdd = '';
  398. const data = cnt.data;
  399.  
  400. const details = data && data.videoType && data.videoId ? ((cnt.$ || 0).details || 0) : null;
  401. const content = data && data.videoType && data.videoId ? null : ((cnt.$ || 0).content || 0);
  402.  
  403. if (data && data.videoType === "REEL_VIDEO_TYPE_VIDEO" && typeof data.videoId === 'string') {
  404. const videoId = data.videoId;
  405. if (data.rsVideoId === videoId && typeof data.rsChannelName === 'string') {
  406. nameToAdd = data.rsChannelName;
  407.  
  408. const metaline = details ? qsOne(details, '#details #metadata-line') : qsOne(hostElement, 'ytd-reel-item-renderer #details #metadata-line');
  409. if (metaline) {
  410. metaline.setAttribute('ePCWu', nameToAdd);
  411. } else {
  412. console.log('metaline cannot be found', content);
  413. }
  414.  
  415. } else {
  416. const name = await networkRequestOfChannelName(videoId);
  417. cnt.data = Object.assign({}, cnt.data, { rsVideoId: videoId, rsChannelName: name });
  418. }
  419.  
  420. } else if (data && data.content && content instanceof Element) {
  421.  
  422. useOldModel = false;
  423. const wKey = firstObjectKey(data.content);
  424. const wObj = wKey ? data.content[wKey] : null;
  425.  
  426. if (wObj) {
  427.  
  428. const rsVideoId = wObj.rsVideoId;
  429. const videoId = getEntryVideoId(wObj);
  430.  
  431. if (videoId !== rsVideoId && videoId) {
  432. const name = await networkRequestOfChannelName(videoId);
  433. const newFirstObject = Object.assign({}, cnt.data.content[wKey], { rsVideoId: videoId, rsChannelName: name });
  434. const newContent = Object.assign({}, cnt.data.content, { [wKey]: newFirstObject });
  435. cnt.data = Object.assign({}, cnt.data, { content: newContent });
  436. } else if (rsVideoId === videoId && rsVideoId) {
  437. nameToAdd = wObj.rsChannelName;
  438. const subhead = getSubheadElement(content);
  439. if (subhead) {
  440. subhead.setAttribute('ePCWu', nameToAdd);
  441. } else {
  442. console.log('subhead cannot be found', content);
  443. }
  444. }
  445.  
  446. }
  447.  
  448. }
  449.  
  450. if (!nameToAdd) {
  451. if (useOldModel) {
  452. const metaline = details ? qsOne(details, '[ePCWu]') : qsOne(hostElement, '[ePCWu]');
  453. if (metaline) {
  454. metaline.removeAttribute('ePCWu');
  455. }
  456. } else if (content) {
  457. const subhead = qsOne(content, '[ePCWu]');
  458. if (subhead) {
  459. subhead.removeAttribute('ePCWu');
  460. }
  461. }
  462. }
  463.  
  464. };
  465.  
  466. ytZara.ytProtoAsync("ytd-rich-grid-slim-media").then((cProto) => {
  467. Promise.resolve().then(addCSSProcess);
  468. if (cProto && !cProto.__ulLSbep46I6H__ && typeof cProto.onDataChanged === 'function') {
  469. cProto.__ulLSbep46I6H__ = apSingleGridFn;
  470. const onDataChanged = cProto.onDataChanged;
  471. cProto.onDataChanged = function () {
  472. const cnt = this;
  473. Promise.resolve(this).then(apSingleGridFn).catch(console.warn);
  474. return onDataChanged ? onDataChanged.apply(cnt, arguments) : void 0;
  475. };
  476. }
  477. });
  478.  
  479.  
  480. const onVisiblePn = (cProto) => {
  481. Promise.resolve().then(addCSSProcess);
  482. if (cProto && !cProto.__ulLSbep46I6H__ && typeof cProto.onVisible === 'function') {
  483. cProto.__ulLSbep46I6H__ = apSingleGridFn;
  484. const onVisible = cProto.onVisible;
  485. cProto.onVisible = function () {
  486. const cnt = this;
  487. Promise.resolve(this).then(apSingleGridFn).catch(console.warn);
  488. return onVisible ? onVisible.apply(cnt, arguments) : void 0;
  489. };
  490. }
  491. };
  492.  
  493. ytZara.ytProtoAsync("ytd-reel-item-renderer").then(onVisiblePn);
  494. ytZara.ytProtoAsync("ytd-rich-item-renderer").then(onVisiblePn);
  495.  
  496. ytZara.ytProtoAsync("yt-horizontal-list-renderer").then((cProto) => {
  497. Promise.resolve().then(addCSSProcess);
  498. if (cProto && !cProto.__wwVgbwDkvCQY__ && typeof cProto.onVisible === 'function') {
  499. cProto.__wwVgbwDkvCQY__ = apGridListFn;
  500. const onVisible = cProto.onVisible;
  501. cProto.onVisible = function () {
  502. const cnt = this;
  503. Promise.resolve(this).then(apGridListFn).catch(console.warn);
  504. return onVisible ? onVisible.apply(cnt, arguments) : void 0;
  505. };
  506. }
  507. });
  508.  
  509.  
  510. })();