YouTube: Add Channel Name to Shorts Thumbnail

To add channel name to Shorts thumbnail

目前为 2024-10-11 提交的版本,查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2024 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 YouTube: Add Channel Name to Shorts Thumbnail
  28. // @namespace UserScript
  29. // @match https://www.youtube.com/*
  30. // @grant none
  31. // @version 0.2.3
  32. // @license MIT License
  33. // @author CY Fung
  34. // @description To add channel name to Shorts thumbnail
  35. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@8fac46500c5a916e6ed21149f6c25f8d1c56a6a3/library/ytZara.js
  36. // @run-at document-start
  37. // ==/UserScript==
  38.  
  39.  
  40.  
  41. !window.TTP && (()=>{
  42. // credit to Benjamin Philipp
  43. // original source: https://greasyfork.org/en/scripts/433051-trusted-types-helper
  44.  
  45. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  46.  
  47. 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
  48. const prefix = `TTP`;
  49. var passThroughFunc = function(string, sink){
  50. return string; // Anything passing through this function will be returned without change
  51. }
  52. var TTPName = "passthrough";
  53. 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
  54. var needsTrustedHTML = false;
  55. function doit(){
  56. try{
  57. if(typeof window.isSecureContext !== 'undefined' && window.isSecureContext){
  58. if (window.trustedTypes && window.trustedTypes.createPolicy){
  59. needsTrustedHTML = true;
  60. if(trustedTypes.defaultPolicy){
  61. log("TT Default Policy exists");
  62. if(overwrite_default)
  63. TTP = window.trustedTypes.createPolicy("default", TTP);
  64. else
  65. TTP = window.trustedTypes.createPolicy(TTPName, TTP); // Is the default policy permissive enough? If it already exists, best not to overwrite it
  66. TTP_default = trustedTypes.defaultPolicy;
  67.  
  68. log("Created custom passthrough policy, in case the default policy is too restrictive: Use Policy '" + TTPName + "' in var 'TTP':", TTP);
  69. }
  70. else{
  71. TTP_default = TTP = window.trustedTypes.createPolicy("default", TTP);
  72. }
  73. log("Trusted-Type Policies: TTP:", TTP, "TTP_default:", TTP_default);
  74. }
  75. }
  76. }catch(e){
  77. log(e);
  78. }
  79. }
  80.  
  81. function log(...args){
  82. if("undefined" != typeof(prefix) && !!prefix)
  83. args = [prefix + ":", ...args];
  84. if("undefined" != typeof(debugging) && !!debugging)
  85. args = [...args, new Error().stack.replace(/^\s*(Error|Stack trace):?\n/gi, "").replace(/^([^\n]*\n)/, "\n")];
  86. console.log(...args);
  87. }
  88.  
  89. doit();
  90.  
  91. // --------------------------------------------------- Trusted Types Helper ---------------------------------------------------
  92.  
  93. window.TTP = TTP;
  94.  
  95. })();
  96.  
  97. function createHTML(s) {
  98. if (typeof TTP !== 'undefined' && typeof TTP.createHTML === 'function') return TTP.createHTML(s);
  99. return s;
  100. }
  101.  
  102. let trustHTMLErr = null;
  103. try {
  104. document.createElement('div').innerHTML = createHTML('1');
  105. } catch (e) {
  106. trustHTMLErr = e;
  107. }
  108.  
  109. if (trustHTMLErr) {
  110. console.log(`trustHTMLErr`, trustHTMLErr);
  111. trustHTMLErr(); // exit userscript
  112. }
  113.  
  114.  
  115. // -----------------------------------------------------------------------------------------------------------------------------
  116.  
  117.  
  118.  
  119. ((__CONTEXT__) => {
  120.  
  121. const { Promise, fetch } = __CONTEXT__;
  122.  
  123. class Mutex {
  124.  
  125. constructor() {
  126. this.p = Promise.resolve()
  127. }
  128.  
  129. /**
  130. * @param {(lockResolve: () => void)} f
  131. */
  132. lockWith(f) {
  133. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  134. }
  135.  
  136. }
  137.  
  138.  
  139. const addCSSProcess = () => {
  140.  
  141. if (document.querySelector('style#ePCWh')) return;
  142.  
  143.  
  144. let style = document.createElement('style')
  145. style.id = 'ePCWh'
  146. style.textContent = `
  147.  
  148. #metadata-line[ePCWh]::before {
  149. width: 100%;
  150. content: attr(ePCWh);
  151. display: block;
  152. max-width: 100%;
  153. text-overflow: ellipsis;
  154. overflow: hidden;
  155. white-space: nowrap;
  156. }
  157.  
  158.  
  159. [ePCWu]::before {
  160. width: 100%;
  161. content: attr(ePCWu);
  162. display: block;
  163. max-width: 100%;
  164. text-overflow: ellipsis;
  165. overflow: hidden;
  166. white-space: nowrap;
  167. }
  168.  
  169. `;
  170. document.head.appendChild(style);
  171.  
  172. }
  173.  
  174. const { requestVideoInfoAsync } = (() => {
  175.  
  176. const mutex = new Mutex();
  177.  
  178. const resolvedValues = new Map();
  179.  
  180. const createPromise = (videoId) => {
  181.  
  182. return new Promise(resolve => {
  183.  
  184. mutex.lockWith(lockResolve => {
  185.  
  186. fetch(`/watch?v=${videoId}`, {
  187.  
  188. "method": "GET",
  189. "mode": "same-origin",
  190. "credentials": "omit",
  191. referrerPolicy: "no-referrer",
  192. cache: "default",
  193. redirect: "error", // there shall be no redirection in this API request
  194. integrity: "",
  195. keepalive: false,
  196.  
  197. "headers": {
  198. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  199. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  200. // seems YouTube RSS Feeds server insists its own Cache-Control.
  201.  
  202. // "Content-Type": "text/xml; charset=UTF-8",
  203. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  204. // X-Youtube-Bootstrap-Logged-In: false,
  205. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  206. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  207.  
  208. "Accept": "text/html",
  209. "Pragma": ""
  210. }
  211.  
  212. }).then(res => {
  213. lockResolve();
  214. return res.text();
  215. }).then(resText => {
  216.  
  217. let wIdx2 = resText.indexOf('itemprop="author"');
  218. let wIdx1 = wIdx2 > 0 ? resText.lastIndexOf('<span', wIdx2) : -1;
  219. let wIdx3 = wIdx1 > 0 ? resText.indexOf('<\/span>', wIdx2) : -1;
  220. if (wIdx3 > 0) {
  221.  
  222. let mText = resText.substring(wIdx1, wIdx3 + '<\/span>'.length);
  223. let template = document.createElement('template');
  224. template.innerHTML = createHTML(mText);
  225. let span = template.content.firstElementChild;
  226. if (span && span.nodeName === "SPAN") {
  227. let name = span.querySelector('link[itemprop="name"]')
  228. if (name) {
  229. name = name.getAttribute('content');
  230. if (name) {
  231. return name;
  232. }
  233. }
  234. }
  235. template.innerHTML = createHTML('');
  236. }
  237.  
  238. return '';
  239.  
  240. }).then(resolve);
  241.  
  242. })
  243.  
  244. });
  245.  
  246. };
  247.  
  248. const requestVideoInfoAsync = (videoId) => {
  249.  
  250. let promise = resolvedValues.get(videoId);
  251. if (!promise) {
  252. promise = createPromise(videoId);
  253. resolvedValues.set(videoId, promise);
  254. }
  255. return promise;
  256. }
  257.  
  258. return { requestVideoInfoAsync };
  259.  
  260. })();
  261.  
  262.  
  263. const firstKey = (obj) => {
  264. for (const key in obj) {
  265. if (obj.hasOwnProperty(key)) return key;
  266. }
  267. return null;
  268. }
  269.  
  270. const __addChannelName582__ = function (){
  271.  
  272.  
  273. let useOldModel = true;
  274. const cnt = this;
  275. const hostElement = this.hostElement || this;
  276. let nameToAdd = '';
  277. const data = cnt.data;
  278.  
  279. const details = data && data.videoType && data.videoId ? ((this.$ || 0).details || 0) : null;
  280. const content = data && data.videoType && data.videoId ? null : ((this.$ || 0).content || 0);
  281.  
  282. if (data && data.videoType === "REEL_VIDEO_TYPE_VIDEO" && typeof data.videoId === 'string') {
  283. const videoId = data.videoId;
  284. if (data.rsVideoId === videoId && typeof data.rsChannelName === 'string') {
  285. nameToAdd = data.rsChannelName;
  286.  
  287. let ml = details ? HTMLElement.prototype.querySelector.call(details, '#details #metadata-line') : HTMLElement.prototype.querySelector.call(hostElement, 'ytd-reel-item-renderer #details #metadata-line');
  288. if (ml) {
  289. ml.setAttribute('ePCWh', nameToAdd);
  290. }
  291.  
  292. } else {
  293. requestVideoInfoAsync(videoId).then(name => {
  294. cnt.data = Object.assign({}, cnt.data, { rsVideoId: videoId, rsChannelName: name });
  295. });
  296. }
  297.  
  298.  
  299.  
  300. } else if (data && data.content && content instanceof Element){
  301.  
  302.  
  303.  
  304. useOldModel = false;
  305. const mFirstKey = firstKey(data.content);
  306. const mFirstObj = data.content[mFirstKey];
  307.  
  308. const rsVideoId = mFirstObj.rsVideoId;
  309. let videoId = '';
  310.  
  311. if(mFirstObj.overlayMetadata && typeof mFirstObj.entityId == 'string' && (mFirstObj.inlinePlayerData||0).onVisible){
  312. const watchEndpoint = ((mFirstObj.inlinePlayerData||0).onVisible.innertubeCommand||0).watchEndpoint || 0;
  313. if(watchEndpoint && typeof (watchEndpoint.videoId||0) === 'string'){
  314. videoId = watchEndpoint.videoId;
  315. }
  316. }
  317.  
  318.  
  319.  
  320. if(!videoId && mFirstObj.overlayMetadata && typeof mFirstObj.entityId == 'string' && (mFirstObj.onTap||0).innertubeCommand){
  321. const reelWatchEndpoint = ((mFirstObj.onTap||0).innertubeCommand||0).reelWatchEndpoint || 0;
  322. if(reelWatchEndpoint && typeof (reelWatchEndpoint.videoId||0) === 'string'){
  323. videoId = reelWatchEndpoint.videoId;
  324. }
  325. }
  326.  
  327. if (videoId !== rsVideoId && videoId) {
  328.  
  329. requestVideoInfoAsync(videoId).then(name => {
  330. const newFirstObject = Object.assign({}, cnt.data.content[mFirstKey], { rsVideoId: videoId, rsChannelName: name });
  331. const newContent = Object.assign({}, cnt.data.content, { [mFirstKey]: newFirstObject });
  332. cnt.data = Object.assign({}, cnt.data, { content: newContent });
  333. });
  334.  
  335. } else if(rsVideoId === videoId && rsVideoId){
  336. nameToAdd = mFirstObj.rsChannelName;
  337. const subhead = HTMLElement.prototype.querySelector.call(content, '.ShortsLockupViewModelHostMetadataSubhead, .ShortsLockupViewModelHostOutsideMetadataSubhead');
  338. subhead.setAttribute('ePCWu', nameToAdd);
  339. }
  340.  
  341. }
  342.  
  343. if (!nameToAdd) {
  344. if (useOldModel) {
  345. const ml = details ? HTMLElement.prototype.querySelector.call(details, '#details #metadata-line') : HTMLElement.prototype.querySelector.call(hostElement, 'ytd-reel-item-renderer #details #metadata-line');
  346. if (ml) {
  347. ml.removeAttribute('ePCWh');
  348. }
  349. } else if (content) {
  350. const subhead = HTMLElement.prototype.querySelector.call(content, '[ePCWu]');
  351. if (subhead) {
  352. subhead.removeAttribute('ePCWu');
  353. }
  354. }
  355. }
  356.  
  357. }
  358.  
  359. ytZara.ytProtoAsync("ytd-rich-grid-slim-media").then((cProto) => {
  360. Promise.resolve().then(addCSSProcess);
  361. console.log(4717);
  362. cProto.__addChannelName582__ = __addChannelName582__;
  363. const onDataChanged = cProto.onDataChanged;
  364. cProto.onDataChanged = function () {
  365. const cnt = this;
  366. console.log(4719, 1);
  367. Promise.resolve().then(()=>{
  368. this.__addChannelName582__();
  369. }).catch(console.warn);
  370. return onDataChanged ? onDataChanged.apply(cnt, arguments) : void 0;
  371. };
  372.  
  373. });
  374.  
  375.  
  376. const onVisiblePn = (cProto) => {
  377. Promise.resolve().then(addCSSProcess);
  378. console.log(4718);
  379. cProto.__addChannelName582__ = __addChannelName582__;
  380. const onVisible = cProto.onVisible;
  381. cProto.onVisible = function () {
  382. const cnt = this;
  383. console.log(4719, 2);
  384. Promise.resolve().then(()=>{
  385. this.__addChannelName582__();
  386. }).catch(console.warn);
  387. return onVisible ? onVisible.apply(cnt, arguments) : void 0;
  388. };
  389.  
  390. };
  391.  
  392. ytZara.ytProtoAsync("ytd-reel-item-renderer").then(onVisiblePn);
  393. ytZara.ytProtoAsync("ytd-rich-item-renderer").then(onVisiblePn);
  394.  
  395.  
  396. })({ Promise, fetch });