BetterYTM.user.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @name:de BetterYTM
  4. // @namespace https://github.com/Sv443/BetterYTM#readme
  5. // @version 0.2.0
  6. // @license MIT
  7. // @author Sv443
  8. // @copyright Sv443 <[email protected]> (https://github.com/Sv443)
  9. // @description Improvements for YouTube Music
  10. // @description:de Verbesserungen für YouTube Music
  11. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  14. // @run-at document-start
  15. // @connect self
  16. // @connect youtube.com
  17. // @connect github.com
  18. // @connect githubusercontent.com
  19. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  20. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  21. // ==/UserScript==
  22. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  23. /* C&D this, Susan 🖕 */
  24. (() => {
  25. "use-strict";
  26. /*
  27. █▀▀█ ▄▄▄ █ █ ▀ ▄▄▄ ▄▄▄▄ ▄▄▄
  28. ▀▀▄▄ █▄█ █▀ █▀ ▀█ █ █ █ ▄▄ █▄▄ ▀
  29. █▄▄█ █▄▄ █▄▄ █▄▄ ▄█▄ █ █ █▄▄█ ▄▄█ ▄
  30. */
  31. /**
  32. * This is where you can enable or disable features
  33. * If this userscript ever becomes something I might add like a menu to toggle these
  34. */
  35. const features = Object.freeze({
  36. // --- Quality of Life ---
  37. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  38. arrowKeySupport: true,
  39. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  40. removeUpgradeTab: true,
  41. // --- Extra Features ---
  42. /** Whether to add a button or key combination (TODO) to switch between the YT and YTM sites on a video */
  43. switchBetweenSites: true,
  44. /** Adds a button to the media controls bar to open the current song's genius.com lyrics in a new tab */
  45. geniusLyrics: true,
  46. // --- Other ---
  47. /** Set to true to remove the watermark under the YTM logo */
  48. removeWatermark: false,
  49. // /** The theme color - accepts any CSS color value - default is "#ff0000" */
  50. // themeColor: "#0f0",
  51. });
  52. /** Set to true to enable debug mode for more output in the JS console */
  53. const dbg = true;
  54. //#MARKER types
  55. /** @typedef {"yt"|"ytm"} Domain Constant string representation of which domain this script is currently running on */
  56. //#MARKER init
  57. /** Specifies the hard limit for repetitive tasks */
  58. const triesLimit = 20;
  59. const info = Object.freeze({
  60. name: GM.info.script.name, // eslint-disable-line no-undef
  61. version: GM.info.script.version, // eslint-disable-line no-undef
  62. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  63. });
  64. function init()
  65. {
  66. try
  67. {
  68. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  69. document.addEventListener("DOMContentLoaded", onDomLoad);
  70. }
  71. catch(err)
  72. {
  73. console.error("BetterYTM - General Error:", err);
  74. }
  75. }
  76. //#MARKER events
  77. /**
  78. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  79. */
  80. function onDomLoad()
  81. {
  82. const domain = getDomain();
  83. dbg && console.info(`BetterYTM: Initializing features for domain '${domain}'`);
  84. try
  85. {
  86. // YTM-specific
  87. if(domain === "ytm")
  88. {
  89. if(features.arrowKeySupport)
  90. {
  91. document.addEventListener("keydown", onKeyDown);
  92. dbg && console.info(`BetterYTM: Added key press listener`);
  93. }
  94. if(features.removeUpgradeTab)
  95. removeUpgradeTab();
  96. if(!features.removeWatermark)
  97. addWatermark();
  98. if(features.geniusLyrics)
  99. addGeniusButton();
  100. }
  101. // Both YTM and YT
  102. if(features.switchBetweenSites)
  103. initSiteSwitch(domain);
  104. }
  105. catch(err)
  106. {
  107. console.error(`BetterYTM: General error while executing feature:`, err);
  108. }
  109. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  110. // applyTheme();
  111. }
  112. //#MARKER features
  113. //#SECTION arrow key skip
  114. /**
  115. * Called when the user presses keys
  116. * @param {KeyboardEvent} evt
  117. */
  118. function onKeyDown(evt)
  119. {
  120. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  121. {
  122. dbg && console.info(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  123. // ripped this stuff from the console, most of these are probably unnecessary but this was finnicky af and I am sick and tired of trial and error
  124. const defaultProps = {
  125. altKey: false,
  126. bubbles: true,
  127. cancelBubble: false,
  128. cancelable: true,
  129. charCode: 0,
  130. composed: true,
  131. ctrlKey: false,
  132. currentTarget: null,
  133. defaultPrevented: evt.defaultPrevented,
  134. explicitOriginalTarget: document.body,
  135. isTrusted: true,
  136. metaKey: false,
  137. originalTarget: document.body,
  138. repeat: false,
  139. shiftKey: false,
  140. srcElement: document.body,
  141. target: document.body,
  142. type: "keydown",
  143. view: window,
  144. };
  145. let invalidKey = false;
  146. let keyProps = {};
  147. switch(evt.code)
  148. {
  149. case "ArrowLeft":
  150. keyProps = {
  151. code: "KeyH",
  152. key: "h",
  153. keyCode: 72,
  154. which: 72,
  155. };
  156. break;
  157. case "ArrowRight":
  158. keyProps = {
  159. code: "KeyL",
  160. key: "l",
  161. keyCode: 76,
  162. which: 76,
  163. };
  164. break;
  165. default:
  166. // console.warn("BetterYTM - Unknown key", evt.code);
  167. invalidKey = true;
  168. break;
  169. }
  170. if(!invalidKey)
  171. {
  172. const proxyProps = { ...defaultProps, ...keyProps };
  173. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  174. dbg && console.info(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  175. }
  176. else if(dbg)
  177. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  178. }
  179. }
  180. //#SECTION site switch
  181. /**
  182. * Initializes the site switch feature
  183. * @param {Domain} domain
  184. */
  185. function initSiteSwitch(domain)
  186. {
  187. // TODO:
  188. // extra features:
  189. // - keep video time
  190. document.addEventListener("keydown", (e) => {
  191. if(e.key == "F9")
  192. switchSite(domain === "yt" ? "ytm" : "yt");
  193. });
  194. dbg && console.info(`BetterYTM: Initialized site switch listener`);
  195. }
  196. /**
  197. * Switches to the other site (between YT and YTM)
  198. * @param {Domain} newDomain
  199. */
  200. function switchSite(newDomain)
  201. {
  202. dbg && console.info(`BetterYTM: Switching from domain '${getDomain()}' to '${newDomain}'`);
  203. try
  204. {
  205. let subdomain;
  206. if(newDomain === "ytm")
  207. subdomain = "music";
  208. else if(newDomain === "yt")
  209. subdomain = "www";
  210. if(!subdomain)
  211. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  212. const { pathname, search, hash } = new URL(location.href);
  213. const vt = getVideoTime() ?? 0;
  214. dbg && console.info(`BetterYTM: Found video time of ${vt} seconds`);
  215. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  216. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  217. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  218. location.href = url;
  219. }
  220. catch(err)
  221. {
  222. console.error(`BetterYTM: Error while switching site:`, err);
  223. }
  224. }
  225. //#SECTION remove upgrade tab
  226. let removeUpgradeTries = 0;
  227. /**
  228. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  229. */
  230. function removeUpgradeTab()
  231. {
  232. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  233. if(tabElem)
  234. {
  235. tabElem.remove();
  236. dbg && console.info(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  237. }
  238. else if(removeUpgradeTries < triesLimit)
  239. {
  240. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  241. removeUpgradeTries++;
  242. }
  243. else
  244. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  245. }
  246. //#SECTION add watermark
  247. /**
  248. * Adds a watermark beneath the logo
  249. */
  250. function addWatermark()
  251. {
  252. const watermark = document.createElement("a");
  253. watermark.id = "betterytm-watermark";
  254. watermark.className = "style-scope ytmusic-nav-bar";
  255. watermark.innerText = info.name;
  256. watermark.title = `${info.name} v${info.version}`;
  257. watermark.href = info.namespace;
  258. watermark.target = "_blank";
  259. watermark.rel = "noopener noreferrer";
  260. const style = `\
  261. #betterytm-watermark {
  262. position: absolute;
  263. left: 45px;
  264. top: 43px;
  265. z-index: 10;
  266. color: white;
  267. text-decoration: none;
  268. cursor: pointer;
  269. }
  270. #betterytm-watermark:hover {
  271. text-decoration: underline;
  272. }`;
  273. addGlobalStyle(style, "watermark");
  274. const logoElem = document.querySelector("#left-content");
  275. insertAfter(logoElem, watermark);
  276. dbg && console.info(`BetterYTM: Added watermark element:`, watermark);
  277. }
  278. //#SECTION genius.com lyrics button
  279. let currentSongTitle = "";
  280. let lyricsButtonAddTries = 0;
  281. /**
  282. * Adds a genius.com lyrics button to the media controls bar
  283. */
  284. function addGeniusButton()
  285. {
  286. const menuElem = document.querySelector(".middle-controls-buttons tp-yt-paper-icon-button.dropdown-trigger");
  287. if(!menuElem)
  288. {
  289. lyricsButtonAddTries++;
  290. if(lyricsButtonAddTries < triesLimit)
  291. return setTimeout(addGeniusButton, 250); // TODO: improve this
  292. return console.error(`BetterYTM: Couldn't find media control menu button to append lyrics button to, after ${lyricsButtonAddTries} tries`);
  293. }
  294. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  295. const linkElem = document.createElement("a");
  296. linkElem.id = "betterytm-lyrics-button";
  297. linkElem.title = "Search for lyrics on genius.com";
  298. linkElem.href = getGeniusUrl();
  299. linkElem.target = "_blank";
  300. linkElem.rel = "noopener noreferrer";
  301. const style = `\
  302. #betterytm-lyrics-button {
  303. display: inline-flex;
  304. align-items: center;
  305. justify-content: center;
  306. position: relative;
  307. vertical-align: middle;
  308. margin-left: 8px;
  309. width: 40px;
  310. height: 40px;
  311. border-radius: 100%;
  312. background-color: transparent;
  313. }
  314. #betterytm-lyrics-button:hover {
  315. background-color: #383838;
  316. }
  317. #betterytm-lyrics-img {
  318. display: inline-block;
  319. z-index: 10;
  320. width: 24px;
  321. height: 24px;
  322. padding: 5px;
  323. }`;
  324. addGlobalStyle(style, "lyrics");
  325. const imgElem = document.createElement("img");
  326. imgElem.id = "betterytm-lyrics-img";
  327. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/develop/resources/external/genius.png";
  328. linkElem.appendChild(imgElem);
  329. dbg && console.info(`BetterYTM: Inserted genius button after ${lyricsButtonAddTries} tries:`, linkElem);
  330. insertAfter(menuElem, linkElem);
  331. currentSongTitle = songTitleElem.title;
  332. /** @param {MutationRecord[]} mutations */
  333. const onMutation = (mutations) => {
  334. mutations.forEach(mut => {
  335. const newTitle = mut.target.title;
  336. if(newTitle != currentSongTitle)
  337. {
  338. dbg && console.info(`BetterYTM: Song title changed from '${currentSongTitle}' to '${newTitle}'`);
  339. currentSongTitle = newTitle;
  340. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  341. lyricsBtn.href = getGeniusUrl();
  342. }
  343. });
  344. };
  345. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  346. const obs = new MutationObserver(onMutation);
  347. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  348. }
  349. //#MARKER other
  350. /**
  351. * Returns the current domain as a constant string representation
  352. * @returns {Domain}
  353. */
  354. function getDomain()
  355. {
  356. const { hostname } = new URL(location.href);
  357. return hostname.toLowerCase().includes("music") ? "ytm" : "yt"; // other cases are caught by the `@match`es at the top
  358. }
  359. /**
  360. * Returns the current video time in seconds
  361. * @returns {number|null} Returns null if the video time is unavailable
  362. */
  363. function getVideoTime()
  364. {
  365. const domain = getDomain();
  366. try
  367. {
  368. if(domain === "ytm")
  369. {
  370. const pbEl = document.querySelector("#progress-bar");
  371. return pbEl.value ?? null;
  372. }
  373. else if(domain === "yt") // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  374. return 0;
  375. return null;
  376. }
  377. catch(err)
  378. {
  379. console.error("BetterYTM: Couldn't get video time due to error:", err);
  380. return null;
  381. }
  382. }
  383. /**
  384. * Returns the genius.com search URL for the current song
  385. * @returns {string}
  386. */
  387. function getGeniusUrl()
  388. {
  389. try
  390. {
  391. const sanitizeSongName = (songName) => {
  392. let sanitized;
  393. if(songName.match(/\(|feat|ft/gmi))
  394. {
  395. // should hopefully trim right after the song name
  396. sanitized = songName.substring(0, songName.indexOf("("));
  397. }
  398. return (sanitized || songName).trim();
  399. };
  400. const songNameRaw = document.querySelector(".content-info-wrapper > yt-formatted-string").title;
  401. const songName = sanitizeSongName(songNameRaw);
  402. const songMeta = document.querySelector("span.subtitle > yt-formatted-string:first-child").title;
  403. const artist = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  404. // TODO: artist might need further splitting before comma or ampersand
  405. const url = `https://genius.com/search?q=${encodeURIComponent(songName)}%20${encodeURIComponent(artist)}`;
  406. dbg && console.info(`BetterYTM: Resolved genius.com URL for song '${songName}' by '${artist}': ${url}`);
  407. return url;
  408. }
  409. catch(err)
  410. {
  411. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  412. }
  413. }
  414. /**
  415. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  416. * @param {HTMLElement} beforeNode
  417. * @param {HTMLElement} afterNode
  418. * @returns {HTMLElement} Returns the `afterNode`
  419. */
  420. function insertAfter(beforeNode, afterNode)
  421. {
  422. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  423. return afterNode;
  424. }
  425. /**
  426. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  427. * @param {string} style CSS string
  428. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  429. */
  430. function addGlobalStyle(style, ref)
  431. {
  432. const styleElem = document.createElement("style");
  433. styleElem.id = `betterytm-${ref}-style`;
  434. if(styleElem.styleSheet)
  435. styleElem.styleSheet.cssText = style;
  436. else
  437. styleElem.appendChild(document.createTextNode(style));
  438. document.querySelector("head").appendChild(styleElem);
  439. dbg && console.info(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  440. }
  441. init(); // call init() when script is loaded
  442. })();