BetterYTM.user.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. // @match https://genius.com/search*
  14. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  15. // @run-at document-start
  16. // @connect self
  17. // @connect youtube.com
  18. // @connect github.com
  19. // @connect githubusercontent.com
  20. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  21. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  22. // ==/UserScript==
  23. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  24. /* C&D this, Susan 🖕 */
  25. (() => {
  26. "use-strict";
  27. /*
  28. █▀▀█ ▄▄▄ █ █ ▀ ▄▄▄ ▄▄▄▄ ▄▄▄
  29. ▀▀▄▄ █▄█ █▀ █▀ ▀█ █ █ █ ▄▄ █▄▄ ▀
  30. █▄▄█ █▄▄ █▄▄ █▄▄ ▄█▄ █ █ █▄▄█ ▄▄█ ▄
  31. */
  32. /**
  33. * This is where you can enable or disable features
  34. * If this userscript ever becomes something I might add like a menu to toggle these
  35. */
  36. const features = Object.freeze({
  37. // --- Quality of Life ---
  38. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  39. arrowKeySupport: true,
  40. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  41. removeUpgradeTab: true,
  42. // --- Extra Features ---
  43. /** Whether to add a button or key combination (TODO) to switch between the YT and YTM sites on a video */
  44. switchBetweenSites: true,
  45. /** Adds a button to the media controls bar to search for the current song's lyrics on genius.com in a new tab */
  46. geniusLyrics: true,
  47. /** This option makes the genius.com lyrics search button from above automatically open the best matching result */
  48. geniusAutoclickBestResult: true,
  49. // --- Other ---
  50. /** Set to true to remove the watermark under the YTM logo */
  51. removeWatermark: false,
  52. // /** The theme color - accepts any CSS color value - default is "#ff0000" */
  53. // themeColor: "#0f0",
  54. });
  55. /** Set to true to enable debug mode for more output in the JS console */
  56. const dbg = true;
  57. //#MARKER types
  58. /** @typedef {"yt"|"ytm"|"genius"} Domain Constant string representation of which domain this script is currently running on */
  59. //#MARKER init
  60. /** Specifies the hard limit for repetitive tasks */
  61. const triesLimit = 20;
  62. const info = Object.freeze({
  63. name: GM.info.script.name, // eslint-disable-line no-undef
  64. version: GM.info.script.version, // eslint-disable-line no-undef
  65. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  66. });
  67. function init()
  68. {
  69. try
  70. {
  71. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  72. document.addEventListener("DOMContentLoaded", onDomLoad);
  73. }
  74. catch(err)
  75. {
  76. console.error("BetterYTM - General Error:", err);
  77. }
  78. }
  79. //#MARKER events
  80. /**
  81. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  82. */
  83. function onDomLoad()
  84. {
  85. const domain = getDomain();
  86. dbg && console.info(`BetterYTM: Initializing features for domain '${domain}'`);
  87. try
  88. {
  89. if(domain === "ytm")
  90. {
  91. if(features.arrowKeySupport)
  92. {
  93. document.addEventListener("keydown", onKeyDown);
  94. dbg && console.info(`BetterYTM: Added key press listener`);
  95. }
  96. if(features.removeUpgradeTab)
  97. removeUpgradeTab();
  98. if(!features.removeWatermark)
  99. addWatermark();
  100. if(features.geniusLyrics)
  101. addGeniusButton();
  102. }
  103. if(["ytm", "yt"].includes(domain))
  104. {
  105. if(features.switchBetweenSites)
  106. initSiteSwitch(domain);
  107. }
  108. if(domain === "genius")
  109. {
  110. if(features.geniusAutoclickBestResult)
  111. autoclickGeniusResult();
  112. }
  113. }
  114. catch(err)
  115. {
  116. console.error(`BetterYTM: General error while executing feature:`, err);
  117. }
  118. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  119. // applyTheme();
  120. }
  121. //#MARKER features
  122. //#SECTION arrow key skip
  123. /**
  124. * Called when the user presses keys
  125. * @param {KeyboardEvent} evt
  126. */
  127. function onKeyDown(evt)
  128. {
  129. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  130. {
  131. dbg && console.info(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  132. // 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
  133. const defaultProps = {
  134. altKey: false,
  135. bubbles: true,
  136. cancelBubble: false,
  137. cancelable: true,
  138. charCode: 0,
  139. composed: true,
  140. ctrlKey: false,
  141. currentTarget: null,
  142. defaultPrevented: evt.defaultPrevented,
  143. explicitOriginalTarget: document.body,
  144. isTrusted: true,
  145. metaKey: false,
  146. originalTarget: document.body,
  147. repeat: false,
  148. shiftKey: false,
  149. srcElement: document.body,
  150. target: document.body,
  151. type: "keydown",
  152. view: window,
  153. };
  154. let invalidKey = false;
  155. let keyProps = {};
  156. switch(evt.code)
  157. {
  158. case "ArrowLeft":
  159. keyProps = {
  160. code: "KeyH",
  161. key: "h",
  162. keyCode: 72,
  163. which: 72,
  164. };
  165. break;
  166. case "ArrowRight":
  167. keyProps = {
  168. code: "KeyL",
  169. key: "l",
  170. keyCode: 76,
  171. which: 76,
  172. };
  173. break;
  174. default:
  175. // console.warn("BetterYTM - Unknown key", evt.code);
  176. invalidKey = true;
  177. break;
  178. }
  179. if(!invalidKey)
  180. {
  181. const proxyProps = { ...defaultProps, ...keyProps };
  182. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  183. dbg && console.info(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  184. }
  185. else if(dbg)
  186. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  187. }
  188. }
  189. //#SECTION site switch
  190. /**
  191. * Initializes the site switch feature
  192. * @param {Domain} domain
  193. */
  194. function initSiteSwitch(domain)
  195. {
  196. // TODO:
  197. // extra features:
  198. // - keep video time
  199. document.addEventListener("keydown", (e) => {
  200. if(e.key == "F9")
  201. switchSite(domain === "yt" ? "ytm" : "yt");
  202. });
  203. dbg && console.info(`BetterYTM: Initialized site switch listener`);
  204. }
  205. /**
  206. * Switches to the other site (between YT and YTM)
  207. * @param {Domain} newDomain
  208. */
  209. function switchSite(newDomain)
  210. {
  211. dbg && console.info(`BetterYTM: Switching from domain '${getDomain()}' to '${newDomain}'`);
  212. try
  213. {
  214. let subdomain;
  215. if(newDomain === "ytm")
  216. subdomain = "music";
  217. else if(newDomain === "yt")
  218. subdomain = "www";
  219. if(!subdomain)
  220. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  221. const { pathname, search, hash } = new URL(location.href);
  222. const vt = getVideoTime() ?? 0;
  223. dbg && console.info(`BetterYTM: Found video time of ${vt} seconds`);
  224. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  225. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  226. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  227. location.href = url;
  228. }
  229. catch(err)
  230. {
  231. console.error(`BetterYTM: Error while switching site:`, err);
  232. }
  233. }
  234. //#SECTION remove upgrade tab
  235. let removeUpgradeTries = 0;
  236. /**
  237. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  238. */
  239. function removeUpgradeTab()
  240. {
  241. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  242. if(tabElem)
  243. {
  244. tabElem.remove();
  245. dbg && console.info(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  246. }
  247. else if(removeUpgradeTries < triesLimit)
  248. {
  249. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  250. removeUpgradeTries++;
  251. }
  252. else
  253. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  254. }
  255. //#SECTION add watermark
  256. /**
  257. * Adds a watermark beneath the logo
  258. */
  259. function addWatermark()
  260. {
  261. const watermark = document.createElement("a");
  262. watermark.id = "betterytm-watermark";
  263. watermark.className = "style-scope ytmusic-nav-bar";
  264. watermark.innerText = info.name;
  265. watermark.title = `${info.name} v${info.version}`;
  266. watermark.href = info.namespace;
  267. watermark.target = "_blank";
  268. watermark.rel = "noopener noreferrer";
  269. const style = `\
  270. #betterytm-watermark {
  271. position: absolute;
  272. left: 45px;
  273. top: 43px;
  274. z-index: 10;
  275. color: white;
  276. text-decoration: none;
  277. cursor: pointer;
  278. }
  279. #betterytm-watermark:hover {
  280. text-decoration: underline;
  281. }`;
  282. addGlobalStyle(style, "watermark");
  283. const logoElem = document.querySelector("#left-content");
  284. insertAfter(logoElem, watermark);
  285. dbg && console.info(`BetterYTM: Added watermark element:`, watermark);
  286. }
  287. //#SECTION genius.com lyrics button
  288. let currentSongTitle = "";
  289. let lyricsButtonAddTries = 0;
  290. /**
  291. * Adds a genius.com lyrics button to the media controls bar
  292. */
  293. function addGeniusButton()
  294. {
  295. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  296. if(!likeContainer)
  297. {
  298. lyricsButtonAddTries++;
  299. if(lyricsButtonAddTries < triesLimit)
  300. return setTimeout(addGeniusButton, 250); // TODO: improve this
  301. return console.error(`BetterYTM: Couldn't find like buttons to append lyrics button to after ${lyricsButtonAddTries} tries`);
  302. }
  303. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  304. const gUrl = getGeniusUrl();
  305. const linkElem = document.createElement("a");
  306. linkElem.id = "betterytm-lyrics-button";
  307. linkElem.className = "ytmusic-player-bar";
  308. linkElem.title = "Search for lyrics on genius.com";
  309. linkElem.href = gUrl;
  310. linkElem.target = "_blank";
  311. linkElem.rel = "noopener noreferrer";
  312. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  313. const style = `\
  314. #betterytm-lyrics-button {
  315. display: inline-flex;
  316. align-items: center;
  317. justify-content: center;
  318. position: relative;
  319. vertical-align: middle;
  320. margin-left: 8px;
  321. width: 40px;
  322. height: 40px;
  323. border-radius: 100%;
  324. background-color: transparent;
  325. }
  326. #betterytm-lyrics-button:hover {
  327. background-color: #383838;
  328. }
  329. #betterytm-lyrics-img {
  330. display: inline-block;
  331. z-index: 10;
  332. width: 24px;
  333. height: 24px;
  334. padding: 5px;
  335. }`;
  336. addGlobalStyle(style, "lyrics");
  337. const imgElem = document.createElement("img");
  338. imgElem.id = "betterytm-lyrics-img";
  339. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/develop/resources/external/genius.png";
  340. linkElem.appendChild(imgElem);
  341. dbg && console.info(`BetterYTM: Inserted genius button after ${lyricsButtonAddTries} tries:`, linkElem);
  342. insertAfter(likeContainer, linkElem);
  343. currentSongTitle = songTitleElem.title;
  344. /** @param {MutationRecord[]} mutations */
  345. const onMutation = (mutations) => {
  346. mutations.forEach(mut => {
  347. const newTitle = mut.target.title;
  348. if(newTitle != currentSongTitle)
  349. {
  350. dbg && console.info(`BetterYTM: Song title changed from '${currentSongTitle}' to '${newTitle}'`);
  351. currentSongTitle = newTitle;
  352. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  353. lyricsBtn.href = getGeniusUrl();
  354. lyricsBtn.style.visibility = "initial";
  355. }
  356. });
  357. };
  358. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  359. const obs = new MutationObserver(onMutation);
  360. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  361. }
  362. /**
  363. * Returns the genius.com search URL for the current song
  364. * @returns {string|null}
  365. */
  366. function getGeniusUrl()
  367. {
  368. try
  369. {
  370. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  371. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  372. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  373. return null;
  374. const sanitizeSongName = (songName) => {
  375. let sanitized;
  376. if(songName.match(/\(|feat|ft/gmi))
  377. {
  378. // should hopefully trim right after the song name
  379. sanitized = songName.substring(0, songName.indexOf("("));
  380. }
  381. return (sanitized || songName).trim();
  382. };
  383. const songNameRaw = songTitleElem.title;
  384. const songName = sanitizeSongName(songNameRaw);
  385. const songMeta = songMetaElem.title;
  386. const artistName = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  387. // TODO: artist might need further splitting before comma or ampersand
  388. const sn = encodeURIComponent(songName);
  389. const an = encodeURIComponent(artistName);
  390. const acParams = features.geniusAutoclickBestResult ? `&bytm-ac-sn=${sn}&bytm-ac-an=${an}` : "";
  391. const url = `https://genius.com/search?q=${sn}%20${an}${acParams}`;
  392. dbg && console.info(`BetterYTM: Resolved genius.com URL for song '${songName}' by '${artistName}': ${url}`);
  393. return url;
  394. }
  395. catch(err)
  396. {
  397. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  398. }
  399. }
  400. //#SECTION autoclick best genius.com result
  401. /**
  402. * Automatically clicks the best matching result in a genius.com search
  403. */
  404. function autoclickGeniusResult()
  405. {
  406. if(!location.pathname.includes("/search"))
  407. return;
  408. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  409. if(!miniCards || miniCards.length == 0)
  410. {
  411. if(geniusAutoclickTries < Math.round(triesLimit * 2.5)) // tries limit higher due to lower timeout
  412. {
  413. geniusAutoclickTries++;
  414. return setTimeout(autoclickGeniusResult, 100); // TODO: improve this
  415. }
  416. else
  417. return console.error(`BetterYTM: Couldn't find result minicards after ${geniusAutoclickTries} tries`);
  418. }
  419. const params = getGeniusAcParams();
  420. if(!params)
  421. return console.info("BetterYTM: No query params present, not autoclicking");
  422. const { songName, artistName } = params;
  423. const resultNode = findMatchingGeniusResult(songName, artistName);
  424. if(!resultNode)
  425. return console.error("BetterYTM: Couldn't find matching result node");
  426. dbg && console.info(`BetterYTM: Found matching result node after ${geniusAutoclickTries} tries:`, resultNode);
  427. resultNode.click();
  428. }
  429. let geniusAutoclickTries = 0;
  430. /**
  431. * Finds a result minicard node that matches the provided song and artist names (case insensitive)
  432. * @param {string} song
  433. * @param {string} artist
  434. * @returns {Node|null}
  435. */
  436. function findMatchingGeniusResult(song, artist)
  437. {
  438. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  439. dbg && console.info(`BetterYTM: Found ${miniCards.length} minicards in results, searching for match...`);
  440. for(const card of miniCards)
  441. {
  442. if(card.childNodes && card.childNodes.length > 0)
  443. {
  444. const title = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-title"));
  445. const subTitle = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-subtitle"));
  446. if(!title || !subTitle || !title.innerText || !subTitle.innerText)
  447. continue;
  448. const songName = title.innerText.toLowerCase();
  449. const artistName = subTitle.innerText.toLowerCase();
  450. // TODO: there can be multiple artists and since their order and spelling on YTM and genius can differ, I need to split them and compare one by one
  451. if(songName.includes(song.toLowerCase()) && artistName.includes(artist.toLowerCase()))
  452. return card;
  453. }
  454. }
  455. return null;
  456. }
  457. /**
  458. * Returns autoclick query params if they exist, else returns null
  459. * @returns {({ songName: string, artistName: string })|null}
  460. */
  461. function getGeniusAcParams()
  462. {
  463. const params = location.search.substring(1).split(/&/g);
  464. if(params.find(p => p.includes("bytm-ac-sn=")) && params.find(p => p.includes("bytm-ac-an=")))
  465. {
  466. const songName = decodeURIComponent(params.find(p => p.includes("bytm-ac-sn=")).split(/=/)[1]);
  467. const artistName = decodeURIComponent(params.find(p => p.includes("bytm-ac-an=")).split(/=/)[1]);
  468. return { songName, artistName };
  469. }
  470. return null;
  471. }
  472. //#MARKER other
  473. /**
  474. * Returns the current domain as a constant string representation
  475. * @throws {Error} If script runs on an unexpected website
  476. * @returns {Domain}
  477. */
  478. function getDomain()
  479. {
  480. const { hostname } = new URL(location.href);
  481. if(hostname.includes("music.youtube"))
  482. return "ytm";
  483. else if(hostname.includes("youtube"))
  484. return "yt";
  485. else if(hostname.includes("genius"))
  486. return "genius";
  487. else
  488. throw new Error("BetterYTM is running on an unexpected website");
  489. }
  490. /**
  491. * Returns the current video time in seconds
  492. * @returns {number|null} Returns null if the video time is unavailable
  493. */
  494. function getVideoTime()
  495. {
  496. const domain = getDomain();
  497. try
  498. {
  499. if(domain === "ytm")
  500. {
  501. const pbEl = document.querySelector("#progress-bar");
  502. return pbEl.value ?? null;
  503. }
  504. 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
  505. return 0;
  506. return null;
  507. }
  508. catch(err)
  509. {
  510. console.error("BetterYTM: Couldn't get video time due to error:", err);
  511. return null;
  512. }
  513. }
  514. /**
  515. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  516. * @param {HTMLElement} beforeNode
  517. * @param {HTMLElement} afterNode
  518. * @returns {HTMLElement} Returns the `afterNode`
  519. */
  520. function insertAfter(beforeNode, afterNode)
  521. {
  522. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  523. return afterNode;
  524. }
  525. /**
  526. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  527. * @param {string} style CSS string
  528. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  529. */
  530. function addGlobalStyle(style, ref)
  531. {
  532. const styleElem = document.createElement("style");
  533. styleElem.id = `betterytm-${ref}-style`;
  534. if(styleElem.styleSheet)
  535. styleElem.styleSheet.cssText = style;
  536. else
  537. styleElem.appendChild(document.createTextNode(style));
  538. document.querySelector("head").appendChild(styleElem);
  539. dbg && console.info(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  540. }
  541. init(); // call init() when script is loaded
  542. })();